babylon.2.1-rc.debug.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (r === void 0) { r = 0; }
  6. if (g === void 0) { g = 0; }
  7. if (b === void 0) { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. // Operators
  16. Color3.prototype.toArray = function (array, index) {
  17. if (index === undefined) {
  18. index = 0;
  19. }
  20. array[index] = this.r;
  21. array[index + 1] = this.g;
  22. array[index + 2] = this.b;
  23. return this;
  24. };
  25. Color3.prototype.toColor4 = function (alpha) {
  26. if (alpha === void 0) { alpha = 1; }
  27. return new Color4(this.r, this.g, this.b, alpha);
  28. };
  29. Color3.prototype.asArray = function () {
  30. var result = [];
  31. this.toArray(result, 0);
  32. return result;
  33. };
  34. Color3.prototype.toLuminance = function () {
  35. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  36. };
  37. Color3.prototype.multiply = function (otherColor) {
  38. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  39. };
  40. Color3.prototype.multiplyToRef = function (otherColor, result) {
  41. result.r = this.r * otherColor.r;
  42. result.g = this.g * otherColor.g;
  43. result.b = this.b * otherColor.b;
  44. return this;
  45. };
  46. Color3.prototype.equals = function (otherColor) {
  47. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  48. };
  49. Color3.prototype.scale = function (scale) {
  50. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  51. };
  52. Color3.prototype.scaleToRef = function (scale, result) {
  53. result.r = this.r * scale;
  54. result.g = this.g * scale;
  55. result.b = this.b * scale;
  56. return this;
  57. };
  58. Color3.prototype.add = function (otherColor) {
  59. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  60. };
  61. Color3.prototype.addToRef = function (otherColor, result) {
  62. result.r = this.r + otherColor.r;
  63. result.g = this.g + otherColor.g;
  64. result.b = this.b + otherColor.b;
  65. return this;
  66. };
  67. Color3.prototype.subtract = function (otherColor) {
  68. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  69. };
  70. Color3.prototype.subtractToRef = function (otherColor, result) {
  71. result.r = this.r - otherColor.r;
  72. result.g = this.g - otherColor.g;
  73. result.b = this.b - otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. return this;
  84. };
  85. Color3.prototype.copyFromFloats = function (r, g, b) {
  86. this.r = r;
  87. this.g = g;
  88. this.b = b;
  89. return this;
  90. };
  91. // Statics
  92. Color3.FromArray = function (array, offset) {
  93. if (offset === void 0) { offset = 0; }
  94. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  95. };
  96. Color3.FromInts = function (r, g, b) {
  97. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  98. };
  99. Color3.Lerp = function (start, end, amount) {
  100. var r = start.r + ((end.r - start.r) * amount);
  101. var g = start.g + ((end.g - start.g) * amount);
  102. var b = start.b + ((end.b - start.b) * amount);
  103. return new Color3(r, g, b);
  104. };
  105. Color3.Red = function () { return new Color3(1, 0, 0); };
  106. Color3.Green = function () { return new Color3(0, 1, 0); };
  107. Color3.Blue = function () { return new Color3(0, 0, 1); };
  108. Color3.Black = function () { return new Color3(0, 0, 0); };
  109. Color3.White = function () { return new Color3(1, 1, 1); };
  110. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  111. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  112. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  113. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  114. return Color3;
  115. })();
  116. BABYLON.Color3 = Color3;
  117. var Color4 = (function () {
  118. function Color4(r, g, b, a) {
  119. this.r = r;
  120. this.g = g;
  121. this.b = b;
  122. this.a = a;
  123. }
  124. // Operators
  125. Color4.prototype.addInPlace = function (right) {
  126. this.r += right.r;
  127. this.g += right.g;
  128. this.b += right.b;
  129. this.a += right.a;
  130. return this;
  131. };
  132. Color4.prototype.asArray = function () {
  133. var result = [];
  134. this.toArray(result, 0);
  135. return result;
  136. };
  137. Color4.prototype.toArray = function (array, index) {
  138. if (index === undefined) {
  139. index = 0;
  140. }
  141. array[index] = this.r;
  142. array[index + 1] = this.g;
  143. array[index + 2] = this.b;
  144. array[index + 3] = this.a;
  145. return this;
  146. };
  147. Color4.prototype.add = function (right) {
  148. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  149. };
  150. Color4.prototype.subtract = function (right) {
  151. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  152. };
  153. Color4.prototype.subtractToRef = function (right, result) {
  154. result.r = this.r - right.r;
  155. result.g = this.g - right.g;
  156. result.b = this.b - right.b;
  157. result.a = this.a - right.a;
  158. return this;
  159. };
  160. Color4.prototype.scale = function (scale) {
  161. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  162. };
  163. Color4.prototype.scaleToRef = function (scale, result) {
  164. result.r = this.r * scale;
  165. result.g = this.g * scale;
  166. result.b = this.b * scale;
  167. result.a = this.a * scale;
  168. return this;
  169. };
  170. Color4.prototype.toString = function () {
  171. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  172. };
  173. Color4.prototype.clone = function () {
  174. return new Color4(this.r, this.g, this.b, this.a);
  175. };
  176. Color4.prototype.copyFrom = function (source) {
  177. this.r = source.r;
  178. this.g = source.g;
  179. this.b = source.b;
  180. this.a = source.a;
  181. return this;
  182. };
  183. // Statics
  184. Color4.Lerp = function (left, right, amount) {
  185. var result = new Color4(0, 0, 0, 0);
  186. Color4.LerpToRef(left, right, amount, result);
  187. return result;
  188. };
  189. Color4.LerpToRef = function (left, right, amount, result) {
  190. result.r = left.r + (right.r - left.r) * amount;
  191. result.g = left.g + (right.g - left.g) * amount;
  192. result.b = left.b + (right.b - left.b) * amount;
  193. result.a = left.a + (right.a - left.a) * amount;
  194. };
  195. Color4.FromArray = function (array, offset) {
  196. if (offset === void 0) { offset = 0; }
  197. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  198. };
  199. Color4.FromInts = function (r, g, b, a) {
  200. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  201. };
  202. return Color4;
  203. })();
  204. BABYLON.Color4 = Color4;
  205. var Vector2 = (function () {
  206. function Vector2(x, y) {
  207. this.x = x;
  208. this.y = y;
  209. }
  210. Vector2.prototype.toString = function () {
  211. return "{X: " + this.x + " Y:" + this.y + "}";
  212. };
  213. // Operators
  214. Vector2.prototype.toArray = function (array, index) {
  215. if (index === void 0) { index = 0; }
  216. array[index] = this.x;
  217. array[index + 1] = this.y;
  218. return this;
  219. };
  220. Vector2.prototype.asArray = function () {
  221. var result = [];
  222. this.toArray(result, 0);
  223. return result;
  224. };
  225. Vector2.prototype.copyFrom = function (source) {
  226. this.x = source.x;
  227. this.y = source.y;
  228. return this;
  229. };
  230. Vector2.prototype.copyFromFloats = function (x, y) {
  231. this.x = x;
  232. this.y = y;
  233. return this;
  234. };
  235. Vector2.prototype.add = function (otherVector) {
  236. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  237. };
  238. Vector2.prototype.addVector3 = function (otherVector) {
  239. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  240. };
  241. Vector2.prototype.subtract = function (otherVector) {
  242. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  243. };
  244. Vector2.prototype.subtractInPlace = function (otherVector) {
  245. this.x -= otherVector.x;
  246. this.y -= otherVector.y;
  247. return this;
  248. };
  249. Vector2.prototype.multiplyInPlace = function (otherVector) {
  250. this.x *= otherVector.x;
  251. this.y *= otherVector.y;
  252. return this;
  253. };
  254. Vector2.prototype.multiply = function (otherVector) {
  255. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  256. };
  257. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  258. result.x = this.x * otherVector.x;
  259. result.y = this.y * otherVector.y;
  260. return this;
  261. };
  262. Vector2.prototype.multiplyByFloats = function (x, y) {
  263. return new Vector2(this.x * x, this.y * y);
  264. };
  265. Vector2.prototype.divide = function (otherVector) {
  266. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  267. };
  268. Vector2.prototype.divideToRef = function (otherVector, result) {
  269. result.x = this.x / otherVector.x;
  270. result.y = this.y / otherVector.y;
  271. return this;
  272. };
  273. Vector2.prototype.negate = function () {
  274. return new Vector2(-this.x, -this.y);
  275. };
  276. Vector2.prototype.scaleInPlace = function (scale) {
  277. this.x *= scale;
  278. this.y *= scale;
  279. return this;
  280. };
  281. Vector2.prototype.scale = function (scale) {
  282. return new Vector2(this.x * scale, this.y * scale);
  283. };
  284. Vector2.prototype.equals = function (otherVector) {
  285. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  286. };
  287. Vector2.prototype.equalsWithEpsilon = function (otherVector) {
  288. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y);
  289. };
  290. // Properties
  291. Vector2.prototype.length = function () {
  292. return Math.sqrt(this.x * this.x + this.y * this.y);
  293. };
  294. Vector2.prototype.lengthSquared = function () {
  295. return (this.x * this.x + this.y * this.y);
  296. };
  297. // Methods
  298. Vector2.prototype.normalize = function () {
  299. var len = this.length();
  300. if (len === 0)
  301. return this;
  302. var num = 1.0 / len;
  303. this.x *= num;
  304. this.y *= num;
  305. return this;
  306. };
  307. Vector2.prototype.clone = function () {
  308. return new Vector2(this.x, this.y);
  309. };
  310. // Statics
  311. Vector2.Zero = function () {
  312. return new Vector2(0, 0);
  313. };
  314. Vector2.FromArray = function (array, offset) {
  315. if (offset === void 0) { offset = 0; }
  316. return new Vector2(array[offset], array[offset + 1]);
  317. };
  318. Vector2.FromArrayToRef = function (array, offset, result) {
  319. result.x = array[offset];
  320. result.y = array[offset + 1];
  321. };
  322. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  323. var squared = amount * amount;
  324. var cubed = amount * squared;
  325. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  326. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  327. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  328. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  329. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  330. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Clamp = function (value, min, max) {
  334. var x = value.x;
  335. x = (x > max.x) ? max.x : x;
  336. x = (x < min.x) ? min.x : x;
  337. var y = value.y;
  338. y = (y > max.y) ? max.y : y;
  339. y = (y < min.y) ? min.y : y;
  340. return new Vector2(x, y);
  341. };
  342. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  347. var part3 = (cubed - (2.0 * squared)) + amount;
  348. var part4 = cubed - squared;
  349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Lerp = function (start, end, amount) {
  354. var x = start.x + ((end.x - start.x) * amount);
  355. var y = start.y + ((end.y - start.y) * amount);
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Dot = function (left, right) {
  359. return left.x * right.x + left.y * right.y;
  360. };
  361. Vector2.Normalize = function (vector) {
  362. var newVector = vector.clone();
  363. newVector.normalize();
  364. return newVector;
  365. };
  366. Vector2.Minimize = function (left, right) {
  367. var x = (left.x < right.x) ? left.x : right.x;
  368. var y = (left.y < right.y) ? left.y : right.y;
  369. return new Vector2(x, y);
  370. };
  371. Vector2.Maximize = function (left, right) {
  372. var x = (left.x > right.x) ? left.x : right.x;
  373. var y = (left.y > right.y) ? left.y : right.y;
  374. return new Vector2(x, y);
  375. };
  376. Vector2.Transform = function (vector, transformation) {
  377. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  378. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  379. return new Vector2(x, y);
  380. };
  381. Vector2.Distance = function (value1, value2) {
  382. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  383. };
  384. Vector2.DistanceSquared = function (value1, value2) {
  385. var x = value1.x - value2.x;
  386. var y = value1.y - value2.y;
  387. return (x * x) + (y * y);
  388. };
  389. return Vector2;
  390. })();
  391. BABYLON.Vector2 = Vector2;
  392. var Vector3 = (function () {
  393. function Vector3(x, y, z) {
  394. this.x = x;
  395. this.y = y;
  396. this.z = z;
  397. }
  398. Vector3.prototype.toString = function () {
  399. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  400. };
  401. // Operators
  402. Vector3.prototype.asArray = function () {
  403. var result = [];
  404. this.toArray(result, 0);
  405. return result;
  406. };
  407. Vector3.prototype.toArray = function (array, index) {
  408. if (index === void 0) { index = 0; }
  409. array[index] = this.x;
  410. array[index + 1] = this.y;
  411. array[index + 2] = this.z;
  412. return this;
  413. };
  414. Vector3.prototype.toQuaternion = function () {
  415. var result = new Quaternion(0, 0, 0, 1);
  416. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  417. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  418. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  419. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  420. var cosy = Math.cos(this.y * 0.5);
  421. var siny = Math.sin(this.y * 0.5);
  422. result.x = coszMinusx * siny;
  423. result.y = -sinzMinusx * siny;
  424. result.z = sinxPlusz * cosy;
  425. result.w = cosxPlusz * cosy;
  426. return result;
  427. };
  428. Vector3.prototype.addInPlace = function (otherVector) {
  429. this.x += otherVector.x;
  430. this.y += otherVector.y;
  431. this.z += otherVector.z;
  432. return this;
  433. };
  434. Vector3.prototype.add = function (otherVector) {
  435. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  436. };
  437. Vector3.prototype.addToRef = function (otherVector, result) {
  438. result.x = this.x + otherVector.x;
  439. result.y = this.y + otherVector.y;
  440. result.z = this.z + otherVector.z;
  441. return this;
  442. };
  443. Vector3.prototype.subtractInPlace = function (otherVector) {
  444. this.x -= otherVector.x;
  445. this.y -= otherVector.y;
  446. this.z -= otherVector.z;
  447. return this;
  448. };
  449. Vector3.prototype.subtract = function (otherVector) {
  450. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  451. };
  452. Vector3.prototype.subtractToRef = function (otherVector, result) {
  453. result.x = this.x - otherVector.x;
  454. result.y = this.y - otherVector.y;
  455. result.z = this.z - otherVector.z;
  456. return this;
  457. };
  458. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  459. return new Vector3(this.x - x, this.y - y, this.z - z);
  460. };
  461. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  462. result.x = this.x - x;
  463. result.y = this.y - y;
  464. result.z = this.z - z;
  465. return this;
  466. };
  467. Vector3.prototype.negate = function () {
  468. return new Vector3(-this.x, -this.y, -this.z);
  469. };
  470. Vector3.prototype.scaleInPlace = function (scale) {
  471. this.x *= scale;
  472. this.y *= scale;
  473. this.z *= scale;
  474. return this;
  475. };
  476. Vector3.prototype.scale = function (scale) {
  477. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  478. };
  479. Vector3.prototype.scaleToRef = function (scale, result) {
  480. result.x = this.x * scale;
  481. result.y = this.y * scale;
  482. result.z = this.z * scale;
  483. };
  484. Vector3.prototype.equals = function (otherVector) {
  485. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  486. };
  487. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  488. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z);
  489. };
  490. Vector3.prototype.equalsToFloats = function (x, y, z) {
  491. return this.x === x && this.y === y && this.z === z;
  492. };
  493. Vector3.prototype.multiplyInPlace = function (otherVector) {
  494. this.x *= otherVector.x;
  495. this.y *= otherVector.y;
  496. this.z *= otherVector.z;
  497. return this;
  498. };
  499. Vector3.prototype.multiply = function (otherVector) {
  500. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  501. };
  502. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  503. result.x = this.x * otherVector.x;
  504. result.y = this.y * otherVector.y;
  505. result.z = this.z * otherVector.z;
  506. return this;
  507. };
  508. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  509. return new Vector3(this.x * x, this.y * y, this.z * z);
  510. };
  511. Vector3.prototype.divide = function (otherVector) {
  512. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  513. };
  514. Vector3.prototype.divideToRef = function (otherVector, result) {
  515. result.x = this.x / otherVector.x;
  516. result.y = this.y / otherVector.y;
  517. result.z = this.z / otherVector.z;
  518. return this;
  519. };
  520. Vector3.prototype.MinimizeInPlace = function (other) {
  521. if (other.x < this.x)
  522. this.x = other.x;
  523. if (other.y < this.y)
  524. this.y = other.y;
  525. if (other.z < this.z)
  526. this.z = other.z;
  527. return this;
  528. };
  529. Vector3.prototype.MaximizeInPlace = function (other) {
  530. if (other.x > this.x)
  531. this.x = other.x;
  532. if (other.y > this.y)
  533. this.y = other.y;
  534. if (other.z > this.z)
  535. this.z = other.z;
  536. return this;
  537. };
  538. // Properties
  539. Vector3.prototype.length = function () {
  540. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  541. };
  542. Vector3.prototype.lengthSquared = function () {
  543. return (this.x * this.x + this.y * this.y + this.z * this.z);
  544. };
  545. // Methods
  546. Vector3.prototype.normalize = function () {
  547. var len = this.length();
  548. if (len === 0 || len === 1.0)
  549. return this;
  550. var num = 1.0 / len;
  551. this.x *= num;
  552. this.y *= num;
  553. this.z *= num;
  554. return this;
  555. };
  556. Vector3.prototype.clone = function () {
  557. return new Vector3(this.x, this.y, this.z);
  558. };
  559. Vector3.prototype.copyFrom = function (source) {
  560. this.x = source.x;
  561. this.y = source.y;
  562. this.z = source.z;
  563. return this;
  564. };
  565. Vector3.prototype.copyFromFloats = function (x, y, z) {
  566. this.x = x;
  567. this.y = y;
  568. this.z = z;
  569. return this;
  570. };
  571. // Statics
  572. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  573. var d0 = Vector3.Dot(vector0, axis) - size;
  574. var d1 = Vector3.Dot(vector1, axis) - size;
  575. var s = d0 / (d0 - d1);
  576. return s;
  577. };
  578. Vector3.FromArray = function (array, offset) {
  579. if (!offset) {
  580. offset = 0;
  581. }
  582. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  583. };
  584. Vector3.FromArrayToRef = function (array, offset, result) {
  585. result.x = array[offset];
  586. result.y = array[offset + 1];
  587. result.z = array[offset + 2];
  588. };
  589. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  590. result.x = array[offset];
  591. result.y = array[offset + 1];
  592. result.z = array[offset + 2];
  593. };
  594. Vector3.FromFloatsToRef = function (x, y, z, result) {
  595. result.x = x;
  596. result.y = y;
  597. result.z = z;
  598. };
  599. Vector3.Zero = function () {
  600. return new Vector3(0, 0, 0);
  601. };
  602. Vector3.Up = function () {
  603. return new Vector3(0, 1.0, 0);
  604. };
  605. Vector3.TransformCoordinates = function (vector, transformation) {
  606. var result = Vector3.Zero();
  607. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  608. return result;
  609. };
  610. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  611. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  612. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  613. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  614. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  615. result.x = x / w;
  616. result.y = y / w;
  617. result.z = z / w;
  618. };
  619. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  620. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  621. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  622. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  623. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  624. result.x = rx / rw;
  625. result.y = ry / rw;
  626. result.z = rz / rw;
  627. };
  628. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  629. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  630. var m0 = SIMD.float32x4.load(transformation.m, 0);
  631. var m1 = SIMD.float32x4.load(transformation.m, 4);
  632. var m2 = SIMD.float32x4.load(transformation.m, 8);
  633. var m3 = SIMD.float32x4.load(transformation.m, 12);
  634. 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));
  635. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  636. SIMD.float32x4.storeXYZ(result._data, 0, r);
  637. };
  638. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  639. var v0 = SIMD.float32x4.splat(x);
  640. var v1 = SIMD.float32x4.splat(y);
  641. var v2 = SIMD.float32x4.splat(z);
  642. var m0 = SIMD.float32x4.load(transformation.m, 0);
  643. var m1 = SIMD.float32x4.load(transformation.m, 4);
  644. var m2 = SIMD.float32x4.load(transformation.m, 8);
  645. var m3 = SIMD.float32x4.load(transformation.m, 12);
  646. 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));
  647. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  648. SIMD.float32x4.storeXYZ(result._data, 0, r);
  649. };
  650. Vector3.TransformNormal = function (vector, transformation) {
  651. var result = Vector3.Zero();
  652. Vector3.TransformNormalToRef(vector, transformation, result);
  653. return result;
  654. };
  655. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  656. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  657. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  658. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  659. };
  660. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  661. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  662. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  663. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  664. };
  665. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  666. var squared = amount * amount;
  667. var cubed = amount * squared;
  668. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  669. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  670. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  671. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  672. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  673. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  674. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  675. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  676. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  677. return new Vector3(x, y, z);
  678. };
  679. Vector3.Clamp = function (value, min, max) {
  680. var x = value.x;
  681. x = (x > max.x) ? max.x : x;
  682. x = (x < min.x) ? min.x : x;
  683. var y = value.y;
  684. y = (y > max.y) ? max.y : y;
  685. y = (y < min.y) ? min.y : y;
  686. var z = value.z;
  687. z = (z > max.z) ? max.z : z;
  688. z = (z < min.z) ? min.z : z;
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  692. var squared = amount * amount;
  693. var cubed = amount * squared;
  694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  696. var part3 = (cubed - (2.0 * squared)) + amount;
  697. var part4 = cubed - squared;
  698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  701. return new Vector3(x, y, z);
  702. };
  703. Vector3.Lerp = function (start, end, amount) {
  704. var x = start.x + ((end.x - start.x) * amount);
  705. var y = start.y + ((end.y - start.y) * amount);
  706. var z = start.z + ((end.z - start.z) * amount);
  707. return new Vector3(x, y, z);
  708. };
  709. Vector3.Dot = function (left, right) {
  710. return (left.x * right.x + left.y * right.y + left.z * right.z);
  711. };
  712. Vector3.Cross = function (left, right) {
  713. var result = Vector3.Zero();
  714. Vector3.CrossToRef(left, right, result);
  715. return result;
  716. };
  717. Vector3.CrossToRef = function (left, right, result) {
  718. result.x = left.y * right.z - left.z * right.y;
  719. result.y = left.z * right.x - left.x * right.z;
  720. result.z = left.x * right.y - left.y * right.x;
  721. };
  722. Vector3.Normalize = function (vector) {
  723. var result = Vector3.Zero();
  724. Vector3.NormalizeToRef(vector, result);
  725. return result;
  726. };
  727. Vector3.NormalizeToRef = function (vector, result) {
  728. result.copyFrom(vector);
  729. result.normalize();
  730. };
  731. Vector3.Project = function (vector, world, transform, viewport) {
  732. var cw = viewport.width;
  733. var ch = viewport.height;
  734. var cx = viewport.x;
  735. var cy = viewport.y;
  736. 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);
  737. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  738. return Vector3.TransformCoordinates(vector, finalMatrix);
  739. };
  740. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  741. var matrix = world.multiply(transform);
  742. matrix.invert();
  743. source.x = source.x / viewportWidth * 2 - 1;
  744. source.y = -(source.y / viewportHeight * 2 - 1);
  745. var vector = Vector3.TransformCoordinates(source, matrix);
  746. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  747. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  748. vector = vector.scale(1.0 / num);
  749. }
  750. return vector;
  751. };
  752. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  753. var matrix = world.multiply(view).multiply(projection);
  754. matrix.invert();
  755. source.x = source.x / viewportWidth * 2 - 1;
  756. source.y = -(source.y / viewportHeight * 2 - 1);
  757. var vector = Vector3.TransformCoordinates(source, matrix);
  758. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  759. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  760. vector = vector.scale(1.0 / num);
  761. }
  762. return vector;
  763. };
  764. Vector3.Minimize = function (left, right) {
  765. var min = left.clone();
  766. min.MinimizeInPlace(right);
  767. return min;
  768. };
  769. Vector3.Maximize = function (left, right) {
  770. var max = left.clone();
  771. max.MaximizeInPlace(right);
  772. return max;
  773. };
  774. Vector3.Distance = function (value1, value2) {
  775. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  776. };
  777. Vector3.DistanceSquared = function (value1, value2) {
  778. var x = value1.x - value2.x;
  779. var y = value1.y - value2.y;
  780. var z = value1.z - value2.z;
  781. return (x * x) + (y * y) + (z * z);
  782. };
  783. Vector3.Center = function (value1, value2) {
  784. var center = value1.add(value2);
  785. center.scaleInPlace(0.5);
  786. return center;
  787. };
  788. /**
  789. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  790. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  791. * to something in order to rotate it from its local system to the given target system.
  792. */
  793. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  794. var u = Vector3.Normalize(axis1);
  795. var v = Vector3.Normalize(axis2);
  796. var w = Vector3.Normalize(axis3);
  797. // world axis
  798. var X = Axis.X;
  799. var Y = Axis.Y;
  800. var Z = Axis.Z;
  801. // equation unknowns and vars
  802. var yaw = 0.0;
  803. var pitch = 0.0;
  804. var roll = 0.0;
  805. var x = 0.0;
  806. var y = 0.0;
  807. var z = 0.0;
  808. var t = 0.0;
  809. var sign = -1.0;
  810. var pi = Math.PI;
  811. var nbRevert = 0;
  812. var cross;
  813. var dot = 0.0;
  814. // step 1 : rotation around w
  815. // Rv3(u) = u1, and u1 belongs to plane xOz
  816. // Rv3(w) = w1 = w invariant
  817. var u1;
  818. var v1;
  819. if (w.z == 0) {
  820. z = 1.0;
  821. }
  822. else if (w.x == 0) {
  823. x = 1.0;
  824. }
  825. else {
  826. t = w.z / w.x;
  827. x = -t * Math.sqrt(1 / (1 + t * t));
  828. z = Math.sqrt(1 / (1 + t * t));
  829. }
  830. u1 = new Vector3(x, y, z);
  831. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  832. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  833. if (Vector3.Dot(w, cross) < 0) {
  834. sign = 1;
  835. }
  836. dot = Vector3.Dot(u, u1);
  837. roll = Math.acos(dot) * sign;
  838. if (Vector3.Dot(u1, X) < 0) {
  839. roll = Math.PI + roll;
  840. u1 = u1.scaleInPlace(-1);
  841. v1 = v1.scaleInPlace(-1);
  842. nbRevert++;
  843. }
  844. // step 2 : rotate around u1
  845. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  846. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  847. var w2;
  848. var v2;
  849. x = 0.0;
  850. y = 0.0;
  851. z = 0.0;
  852. sign = -1;
  853. if (w.z == 0) {
  854. x = 1.0;
  855. }
  856. else {
  857. t = u1.z / u1.x;
  858. x = -t * Math.sqrt(1 / (1 + t * t));
  859. z = Math.sqrt(1 / (1 + t * t));
  860. }
  861. w2 = new BABYLON.Vector3(x, y, z);
  862. v2 = BABYLON.Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  863. cross = BABYLON.Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  864. if (BABYLON.Vector3.Dot(u1, cross) < 0) {
  865. sign = 1;
  866. }
  867. dot = BABYLON.Vector3.Dot(w, w2);
  868. pitch = Math.acos(dot) * sign;
  869. if (BABYLON.Vector3.Dot(v2, Y) < 0) {
  870. pitch = Math.PI + pitch;
  871. v2 = v2.scaleInPlace(-1);
  872. w2 = w2.scaleInPlace(-1);
  873. nbRevert++;
  874. }
  875. // step 3 : rotate around v2
  876. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  877. sign = -1;
  878. cross = BABYLON.Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  879. if (BABYLON.Vector3.Dot(cross, Y) < 0) {
  880. sign = 1;
  881. }
  882. dot = BABYLON.Vector3.Dot(u1, X);
  883. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  884. if (dot < 0 && nbRevert < 2) {
  885. yaw = Math.PI + yaw;
  886. }
  887. return new BABYLON.Vector3(pitch, yaw, roll);
  888. };
  889. return Vector3;
  890. })();
  891. BABYLON.Vector3 = Vector3;
  892. //Vector4 class created for EulerAngle class conversion to Quaternion
  893. var Vector4 = (function () {
  894. function Vector4(x, y, z, w) {
  895. this.x = x;
  896. this.y = y;
  897. this.z = z;
  898. this.w = w;
  899. }
  900. Vector4.prototype.toString = function () {
  901. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  902. };
  903. // Operators
  904. Vector4.prototype.asArray = function () {
  905. var result = [];
  906. this.toArray(result, 0);
  907. return result;
  908. };
  909. Vector4.prototype.toArray = function (array, index) {
  910. if (index === undefined) {
  911. index = 0;
  912. }
  913. array[index] = this.x;
  914. array[index + 1] = this.y;
  915. array[index + 2] = this.z;
  916. array[index + 3] = this.w;
  917. return this;
  918. };
  919. Vector4.prototype.addInPlace = function (otherVector) {
  920. this.x += otherVector.x;
  921. this.y += otherVector.y;
  922. this.z += otherVector.z;
  923. this.w += otherVector.w;
  924. return this;
  925. };
  926. Vector4.prototype.add = function (otherVector) {
  927. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  928. };
  929. Vector4.prototype.addToRef = function (otherVector, result) {
  930. result.x = this.x + otherVector.x;
  931. result.y = this.y + otherVector.y;
  932. result.z = this.z + otherVector.z;
  933. result.w = this.w + otherVector.w;
  934. return this;
  935. };
  936. Vector4.prototype.subtractInPlace = function (otherVector) {
  937. this.x -= otherVector.x;
  938. this.y -= otherVector.y;
  939. this.z -= otherVector.z;
  940. this.w -= otherVector.w;
  941. return this;
  942. };
  943. Vector4.prototype.subtract = function (otherVector) {
  944. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  945. };
  946. Vector4.prototype.subtractToRef = function (otherVector, result) {
  947. result.x = this.x - otherVector.x;
  948. result.y = this.y - otherVector.y;
  949. result.z = this.z - otherVector.z;
  950. result.w = this.w - otherVector.w;
  951. return this;
  952. };
  953. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  954. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  955. };
  956. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  957. result.x = this.x - x;
  958. result.y = this.y - y;
  959. result.z = this.z - z;
  960. result.w = this.w - w;
  961. return this;
  962. };
  963. Vector4.prototype.negate = function () {
  964. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  965. };
  966. Vector4.prototype.scaleInPlace = function (scale) {
  967. this.x *= scale;
  968. this.y *= scale;
  969. this.z *= scale;
  970. this.w *= scale;
  971. return this;
  972. };
  973. Vector4.prototype.scale = function (scale) {
  974. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  975. };
  976. Vector4.prototype.scaleToRef = function (scale, result) {
  977. result.x = this.x * scale;
  978. result.y = this.y * scale;
  979. result.z = this.z * scale;
  980. result.w = this.w * scale;
  981. };
  982. Vector4.prototype.equals = function (otherVector) {
  983. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  984. };
  985. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  986. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon &&
  987. Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon &&
  988. Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon &&
  989. Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  990. };
  991. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  992. return this.x === x && this.y === y && this.z === z && this.w === w;
  993. };
  994. Vector4.prototype.multiplyInPlace = function (otherVector) {
  995. this.x *= otherVector.x;
  996. this.y *= otherVector.y;
  997. this.z *= otherVector.z;
  998. this.w *= otherVector.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.multiply = function (otherVector) {
  1002. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1003. };
  1004. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1005. result.x = this.x * otherVector.x;
  1006. result.y = this.y * otherVector.y;
  1007. result.z = this.z * otherVector.z;
  1008. result.w = this.w * otherVector.w;
  1009. return this;
  1010. };
  1011. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1012. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1013. };
  1014. Vector4.prototype.divide = function (otherVector) {
  1015. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1016. };
  1017. Vector4.prototype.divideToRef = function (otherVector, result) {
  1018. result.x = this.x / otherVector.x;
  1019. result.y = this.y / otherVector.y;
  1020. result.z = this.z / otherVector.z;
  1021. result.w = this.w / otherVector.w;
  1022. return this;
  1023. };
  1024. Vector4.prototype.MinimizeInPlace = function (other) {
  1025. if (other.x < this.x)
  1026. this.x = other.x;
  1027. if (other.y < this.y)
  1028. this.y = other.y;
  1029. if (other.z < this.z)
  1030. this.z = other.z;
  1031. if (other.w < this.w)
  1032. this.w = other.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.MaximizeInPlace = function (other) {
  1036. if (other.x > this.x)
  1037. this.x = other.x;
  1038. if (other.y > this.y)
  1039. this.y = other.y;
  1040. if (other.z > this.z)
  1041. this.z = other.z;
  1042. if (other.w > this.w)
  1043. this.w = other.w;
  1044. return this;
  1045. };
  1046. // Properties
  1047. Vector4.prototype.length = function () {
  1048. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1049. };
  1050. Vector4.prototype.lengthSquared = function () {
  1051. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1052. };
  1053. // Methods
  1054. Vector4.prototype.normalize = function () {
  1055. var len = this.length();
  1056. if (len === 0)
  1057. return this;
  1058. var num = 1.0 / len;
  1059. this.x *= num;
  1060. this.y *= num;
  1061. this.z *= num;
  1062. this.w *= num;
  1063. return this;
  1064. };
  1065. Vector4.prototype.clone = function () {
  1066. return new Vector4(this.x, this.y, this.z, this.w);
  1067. };
  1068. Vector4.prototype.copyFrom = function (source) {
  1069. this.x = source.x;
  1070. this.y = source.y;
  1071. this.z = source.z;
  1072. this.w = source.w;
  1073. return this;
  1074. };
  1075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1076. this.x = x;
  1077. this.y = y;
  1078. this.z = z;
  1079. this.w = w;
  1080. return this;
  1081. };
  1082. // Statics
  1083. Vector4.FromArray = function (array, offset) {
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1088. };
  1089. Vector4.FromArrayToRef = function (array, offset, result) {
  1090. result.x = array[offset];
  1091. result.y = array[offset + 1];
  1092. result.z = array[offset + 2];
  1093. result.w = array[offset + 3];
  1094. };
  1095. Vector4.FromFloatArrayToRef = 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.FromFloatsToRef = function (x, y, z, w, result) {
  1102. result.x = x;
  1103. result.y = y;
  1104. result.z = z;
  1105. result.w = w;
  1106. };
  1107. Vector4.Zero = function () {
  1108. return new Vector4(0, 0, 0, 0);
  1109. };
  1110. Vector4.Normalize = function (vector) {
  1111. var result = Vector4.Zero();
  1112. Vector4.NormalizeToRef(vector, result);
  1113. return result;
  1114. };
  1115. Vector4.NormalizeToRef = function (vector, result) {
  1116. result.copyFrom(vector);
  1117. result.normalize();
  1118. };
  1119. Vector4.Minimize = function (left, right) {
  1120. var min = left.clone();
  1121. min.MinimizeInPlace(right);
  1122. return min;
  1123. };
  1124. Vector4.Maximize = function (left, right) {
  1125. var max = left.clone();
  1126. max.MaximizeInPlace(right);
  1127. return max;
  1128. };
  1129. Vector4.Distance = function (value1, value2) {
  1130. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1131. };
  1132. Vector4.DistanceSquared = function (value1, value2) {
  1133. var x = value1.x - value2.x;
  1134. var y = value1.y - value2.y;
  1135. var z = value1.z - value2.z;
  1136. var w = value1.w - value2.w;
  1137. return (x * x) + (y * y) + (z * z) + (w * w);
  1138. };
  1139. Vector4.Center = function (value1, value2) {
  1140. var center = value1.add(value2);
  1141. center.scaleInPlace(0.5);
  1142. return center;
  1143. };
  1144. return Vector4;
  1145. })();
  1146. BABYLON.Vector4 = Vector4;
  1147. var Quaternion = (function () {
  1148. function Quaternion(x, y, z, w) {
  1149. if (x === void 0) { x = 0; }
  1150. if (y === void 0) { y = 0; }
  1151. if (z === void 0) { z = 0; }
  1152. if (w === void 0) { w = 1; }
  1153. this.x = x;
  1154. this.y = y;
  1155. this.z = z;
  1156. this.w = w;
  1157. }
  1158. Quaternion.prototype.toString = function () {
  1159. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1160. };
  1161. Quaternion.prototype.asArray = function () {
  1162. return [this.x, this.y, this.z, this.w];
  1163. };
  1164. Quaternion.prototype.equals = function (otherQuaternion) {
  1165. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1166. };
  1167. Quaternion.prototype.clone = function () {
  1168. return new Quaternion(this.x, this.y, this.z, this.w);
  1169. };
  1170. Quaternion.prototype.copyFrom = function (other) {
  1171. this.x = other.x;
  1172. this.y = other.y;
  1173. this.z = other.z;
  1174. this.w = other.w;
  1175. return this;
  1176. };
  1177. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1178. this.x = x;
  1179. this.y = y;
  1180. this.z = z;
  1181. this.w = w;
  1182. return this;
  1183. };
  1184. Quaternion.prototype.add = function (other) {
  1185. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1186. };
  1187. Quaternion.prototype.subtract = function (other) {
  1188. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1189. };
  1190. Quaternion.prototype.scale = function (value) {
  1191. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1192. };
  1193. Quaternion.prototype.multiply = function (q1) {
  1194. var result = new Quaternion(0, 0, 0, 1.0);
  1195. this.multiplyToRef(q1, result);
  1196. return result;
  1197. };
  1198. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1199. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1200. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1201. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1202. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1203. result.copyFromFloats(x, y, z, w);
  1204. return this;
  1205. };
  1206. Quaternion.prototype.length = function () {
  1207. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1208. };
  1209. Quaternion.prototype.normalize = function () {
  1210. var length = 1.0 / this.length();
  1211. this.x *= length;
  1212. this.y *= length;
  1213. this.z *= length;
  1214. this.w *= length;
  1215. return this;
  1216. };
  1217. Quaternion.prototype.toEulerAngles = function () {
  1218. var result = Vector3.Zero();
  1219. this.toEulerAnglesToRef(result);
  1220. return result;
  1221. };
  1222. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1223. //result is an EulerAngles in the in the z-x-z convention
  1224. var qx = this.x;
  1225. var qy = this.y;
  1226. var qz = this.z;
  1227. var qw = this.w;
  1228. var qxy = qx * qy;
  1229. var qxz = qx * qz;
  1230. var qwy = qw * qy;
  1231. var qwz = qw * qz;
  1232. var qwx = qw * qx;
  1233. var qyz = qy * qz;
  1234. var sqx = qx * qx;
  1235. var sqy = qy * qy;
  1236. var determinant = sqx + sqy;
  1237. if (determinant !== 0.000 && determinant !== 1.000) {
  1238. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1239. result.y = Math.acos(1 - 2 * determinant);
  1240. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1241. }
  1242. else {
  1243. if (determinant === 0.0) {
  1244. result.x = 0.0;
  1245. result.y = 0.0;
  1246. 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)
  1247. }
  1248. else {
  1249. 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)
  1250. result.y = Math.PI;
  1251. result.z = 0.0;
  1252. }
  1253. }
  1254. return this;
  1255. };
  1256. Quaternion.prototype.toRotationMatrix = function (result) {
  1257. var xx = this.x * this.x;
  1258. var yy = this.y * this.y;
  1259. var zz = this.z * this.z;
  1260. var xy = this.x * this.y;
  1261. var zw = this.z * this.w;
  1262. var zx = this.z * this.x;
  1263. var yw = this.y * this.w;
  1264. var yz = this.y * this.z;
  1265. var xw = this.x * this.w;
  1266. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1267. result.m[1] = 2.0 * (xy + zw);
  1268. result.m[2] = 2.0 * (zx - yw);
  1269. result.m[3] = 0;
  1270. result.m[4] = 2.0 * (xy - zw);
  1271. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1272. result.m[6] = 2.0 * (yz + xw);
  1273. result.m[7] = 0;
  1274. result.m[8] = 2.0 * (zx + yw);
  1275. result.m[9] = 2.0 * (yz - xw);
  1276. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1277. result.m[11] = 0;
  1278. result.m[12] = 0;
  1279. result.m[13] = 0;
  1280. result.m[14] = 0;
  1281. result.m[15] = 1.0;
  1282. return this;
  1283. };
  1284. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1285. Quaternion.FromRotationMatrixToRef(matrix, this);
  1286. return this;
  1287. };
  1288. // Statics
  1289. Quaternion.FromRotationMatrix = function (matrix) {
  1290. var result = new Quaternion();
  1291. Quaternion.FromRotationMatrixToRef(matrix, result);
  1292. return result;
  1293. };
  1294. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1295. var data = matrix.m;
  1296. var m11 = data[0], m12 = data[4], m13 = data[8];
  1297. var m21 = data[1], m22 = data[5], m23 = data[9];
  1298. var m31 = data[2], m32 = data[6], m33 = data[10];
  1299. var trace = m11 + m22 + m33;
  1300. var s;
  1301. if (trace > 0) {
  1302. s = 0.5 / Math.sqrt(trace + 1.0);
  1303. result.w = 0.25 / s;
  1304. result.x = (m32 - m23) * s;
  1305. result.y = (m13 - m31) * s;
  1306. result.z = (m21 - m12) * s;
  1307. }
  1308. else if (m11 > m22 && m11 > m33) {
  1309. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1310. result.w = (m32 - m23) / s;
  1311. result.x = 0.25 * s;
  1312. result.y = (m12 + m21) / s;
  1313. result.z = (m13 + m31) / s;
  1314. }
  1315. else if (m22 > m33) {
  1316. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1317. result.w = (m13 - m31) / s;
  1318. result.x = (m12 + m21) / s;
  1319. result.y = 0.25 * s;
  1320. result.z = (m23 + m32) / s;
  1321. }
  1322. else {
  1323. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1324. result.w = (m21 - m12) / s;
  1325. result.x = (m13 + m31) / s;
  1326. result.y = (m23 + m32) / s;
  1327. result.z = 0.25 * s;
  1328. }
  1329. };
  1330. Quaternion.Inverse = function (q) {
  1331. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1332. };
  1333. Quaternion.Identity = function () {
  1334. return new Quaternion(0, 0, 0, 1);
  1335. };
  1336. Quaternion.RotationAxis = function (axis, angle) {
  1337. var result = new Quaternion();
  1338. var sin = Math.sin(angle / 2);
  1339. result.w = Math.cos(angle / 2);
  1340. result.x = axis.x * sin;
  1341. result.y = axis.y * sin;
  1342. result.z = axis.z * sin;
  1343. return result;
  1344. };
  1345. Quaternion.FromArray = function (array, offset) {
  1346. if (!offset) {
  1347. offset = 0;
  1348. }
  1349. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1350. };
  1351. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1352. var result = new Quaternion();
  1353. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1354. return result;
  1355. };
  1356. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1357. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1358. var halfRoll = roll * 0.5;
  1359. var halfPitch = pitch * 0.5;
  1360. var halfYaw = yaw * 0.5;
  1361. var sinRoll = Math.sin(halfRoll);
  1362. var cosRoll = Math.cos(halfRoll);
  1363. var sinPitch = Math.sin(halfPitch);
  1364. var cosPitch = Math.cos(halfPitch);
  1365. var sinYaw = Math.sin(halfYaw);
  1366. var cosYaw = Math.cos(halfYaw);
  1367. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1368. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1369. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1370. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1371. };
  1372. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1373. var result = new Quaternion();
  1374. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1375. return result;
  1376. };
  1377. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1378. // Produces a quaternion from Euler angles in the z-x-z orientation
  1379. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1380. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1381. var halfBeta = beta * 0.5;
  1382. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1383. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1384. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1385. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1386. };
  1387. Quaternion.Slerp = function (left, right, amount) {
  1388. var num2;
  1389. var num3;
  1390. var num = amount;
  1391. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1392. var flag = false;
  1393. if (num4 < 0) {
  1394. flag = true;
  1395. num4 = -num4;
  1396. }
  1397. if (num4 > 0.999999) {
  1398. num3 = 1 - num;
  1399. num2 = flag ? -num : num;
  1400. }
  1401. else {
  1402. var num5 = Math.acos(num4);
  1403. var num6 = (1.0 / Math.sin(num5));
  1404. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1405. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1406. }
  1407. 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));
  1408. };
  1409. return Quaternion;
  1410. })();
  1411. BABYLON.Quaternion = Quaternion;
  1412. var Matrix = (function () {
  1413. function Matrix() {
  1414. this.m = new Float32Array(16);
  1415. }
  1416. // Properties
  1417. Matrix.prototype.isIdentity = function () {
  1418. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1419. return false;
  1420. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1421. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1422. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1423. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1424. return false;
  1425. return true;
  1426. };
  1427. Matrix.prototype.determinant = function () {
  1428. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1429. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1430. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1431. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1432. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1433. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1434. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1435. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1436. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1437. };
  1438. // Methods
  1439. Matrix.prototype.toArray = function () {
  1440. return this.m;
  1441. };
  1442. Matrix.prototype.asArray = function () {
  1443. return this.toArray();
  1444. };
  1445. Matrix.prototype.invert = function () {
  1446. this.invertToRef(this);
  1447. return this;
  1448. };
  1449. Matrix.prototype.invertToRef = function (other) {
  1450. var l1 = this.m[0];
  1451. var l2 = this.m[1];
  1452. var l3 = this.m[2];
  1453. var l4 = this.m[3];
  1454. var l5 = this.m[4];
  1455. var l6 = this.m[5];
  1456. var l7 = this.m[6];
  1457. var l8 = this.m[7];
  1458. var l9 = this.m[8];
  1459. var l10 = this.m[9];
  1460. var l11 = this.m[10];
  1461. var l12 = this.m[11];
  1462. var l13 = this.m[12];
  1463. var l14 = this.m[13];
  1464. var l15 = this.m[14];
  1465. var l16 = this.m[15];
  1466. var l17 = (l11 * l16) - (l12 * l15);
  1467. var l18 = (l10 * l16) - (l12 * l14);
  1468. var l19 = (l10 * l15) - (l11 * l14);
  1469. var l20 = (l9 * l16) - (l12 * l13);
  1470. var l21 = (l9 * l15) - (l11 * l13);
  1471. var l22 = (l9 * l14) - (l10 * l13);
  1472. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1473. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1474. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1475. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1476. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1477. var l28 = (l7 * l16) - (l8 * l15);
  1478. var l29 = (l6 * l16) - (l8 * l14);
  1479. var l30 = (l6 * l15) - (l7 * l14);
  1480. var l31 = (l5 * l16) - (l8 * l13);
  1481. var l32 = (l5 * l15) - (l7 * l13);
  1482. var l33 = (l5 * l14) - (l6 * l13);
  1483. var l34 = (l7 * l12) - (l8 * l11);
  1484. var l35 = (l6 * l12) - (l8 * l10);
  1485. var l36 = (l6 * l11) - (l7 * l10);
  1486. var l37 = (l5 * l12) - (l8 * l9);
  1487. var l38 = (l5 * l11) - (l7 * l9);
  1488. var l39 = (l5 * l10) - (l6 * l9);
  1489. other.m[0] = l23 * l27;
  1490. other.m[4] = l24 * l27;
  1491. other.m[8] = l25 * l27;
  1492. other.m[12] = l26 * l27;
  1493. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1494. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1495. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1496. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1497. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1498. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1499. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1500. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1501. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1502. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1503. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1504. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1505. return this;
  1506. };
  1507. Matrix.prototype.invertToRefSIMD = function (other) {
  1508. var src = this.m;
  1509. var dest = other.m;
  1510. var row0, row1, row2, row3;
  1511. var tmp1;
  1512. var minor0, minor1, minor2, minor3;
  1513. var det;
  1514. // Load the 4 rows
  1515. var src0 = SIMD.float32x4.load(src, 0);
  1516. var src1 = SIMD.float32x4.load(src, 4);
  1517. var src2 = SIMD.float32x4.load(src, 8);
  1518. var src3 = SIMD.float32x4.load(src, 12);
  1519. // Transpose the source matrix. Sort of. Not a true transpose operation
  1520. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1521. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1522. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1523. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1524. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1525. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1526. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1527. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1528. // This is a true transposition, but it will lead to an incorrect result
  1529. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1530. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1531. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1532. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1533. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1534. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1535. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1536. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1537. // ----
  1538. tmp1 = SIMD.float32x4.mul(row2, row3);
  1539. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1540. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1541. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1542. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1543. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1544. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1545. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1546. // ----
  1547. tmp1 = SIMD.float32x4.mul(row1, row2);
  1548. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1549. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1550. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1551. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1552. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1553. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1554. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1555. // ----
  1556. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1557. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1558. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1559. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1560. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1561. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1562. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1563. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1564. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1565. // ----
  1566. tmp1 = SIMD.float32x4.mul(row0, row1);
  1567. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1568. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1569. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1570. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1571. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1572. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1573. // ----
  1574. tmp1 = SIMD.float32x4.mul(row0, row3);
  1575. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1576. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1577. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1578. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1579. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1580. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1581. // ----
  1582. tmp1 = SIMD.float32x4.mul(row0, row2);
  1583. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1584. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1585. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1586. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1587. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1588. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1589. // Compute determinant
  1590. det = SIMD.float32x4.mul(row0, minor0);
  1591. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1592. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1593. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1594. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1595. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1596. // These shuffles aren't necessary if the faulty transposition is done
  1597. // up at the top of this function.
  1598. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1599. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1600. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1601. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1602. // Compute final values by multiplying with 1/det
  1603. minor0 = SIMD.float32x4.mul(det, minor0);
  1604. minor1 = SIMD.float32x4.mul(det, minor1);
  1605. minor2 = SIMD.float32x4.mul(det, minor2);
  1606. minor3 = SIMD.float32x4.mul(det, minor3);
  1607. SIMD.float32x4.store(dest, 0, minor0);
  1608. SIMD.float32x4.store(dest, 4, minor1);
  1609. SIMD.float32x4.store(dest, 8, minor2);
  1610. SIMD.float32x4.store(dest, 12, minor3);
  1611. return this;
  1612. };
  1613. Matrix.prototype.setTranslation = function (vector3) {
  1614. this.m[12] = vector3.x;
  1615. this.m[13] = vector3.y;
  1616. this.m[14] = vector3.z;
  1617. return this;
  1618. };
  1619. Matrix.prototype.multiply = function (other) {
  1620. var result = new Matrix();
  1621. this.multiplyToRef(other, result);
  1622. return result;
  1623. };
  1624. Matrix.prototype.copyFrom = function (other) {
  1625. for (var index = 0; index < 16; index++) {
  1626. this.m[index] = other.m[index];
  1627. }
  1628. return this;
  1629. };
  1630. Matrix.prototype.copyToArray = function (array, offset) {
  1631. if (offset === void 0) { offset = 0; }
  1632. for (var index = 0; index < 16; index++) {
  1633. array[offset + index] = this.m[index];
  1634. }
  1635. return this;
  1636. };
  1637. Matrix.prototype.multiplyToRef = function (other, result) {
  1638. this.multiplyToArray(other, result.m, 0);
  1639. return this;
  1640. };
  1641. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1642. var tm0 = this.m[0];
  1643. var tm1 = this.m[1];
  1644. var tm2 = this.m[2];
  1645. var tm3 = this.m[3];
  1646. var tm4 = this.m[4];
  1647. var tm5 = this.m[5];
  1648. var tm6 = this.m[6];
  1649. var tm7 = this.m[7];
  1650. var tm8 = this.m[8];
  1651. var tm9 = this.m[9];
  1652. var tm10 = this.m[10];
  1653. var tm11 = this.m[11];
  1654. var tm12 = this.m[12];
  1655. var tm13 = this.m[13];
  1656. var tm14 = this.m[14];
  1657. var tm15 = this.m[15];
  1658. var om0 = other.m[0];
  1659. var om1 = other.m[1];
  1660. var om2 = other.m[2];
  1661. var om3 = other.m[3];
  1662. var om4 = other.m[4];
  1663. var om5 = other.m[5];
  1664. var om6 = other.m[6];
  1665. var om7 = other.m[7];
  1666. var om8 = other.m[8];
  1667. var om9 = other.m[9];
  1668. var om10 = other.m[10];
  1669. var om11 = other.m[11];
  1670. var om12 = other.m[12];
  1671. var om13 = other.m[13];
  1672. var om14 = other.m[14];
  1673. var om15 = other.m[15];
  1674. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1675. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1676. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1677. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1678. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1679. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1680. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1681. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1682. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1683. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1684. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1685. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1686. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1687. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1688. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1689. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1690. return this;
  1691. };
  1692. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1693. if (offset === void 0) { offset = 0; }
  1694. var tm = this.m;
  1695. var om = other.m;
  1696. var om0 = SIMD.float32x4.load(om, 0);
  1697. var om1 = SIMD.float32x4.load(om, 4);
  1698. var om2 = SIMD.float32x4.load(om, 8);
  1699. var om3 = SIMD.float32x4.load(om, 12);
  1700. var tm0 = SIMD.float32x4.load(tm, 0);
  1701. 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)))));
  1702. var tm1 = SIMD.float32x4.load(tm, 4);
  1703. 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)))));
  1704. var tm2 = SIMD.float32x4.load(tm, 8);
  1705. 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)))));
  1706. var tm3 = SIMD.float32x4.load(tm, 12);
  1707. 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)))));
  1708. };
  1709. Matrix.prototype.equals = function (value) {
  1710. return value &&
  1711. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1712. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1713. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1714. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1715. };
  1716. Matrix.prototype.clone = function () {
  1717. 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]);
  1718. };
  1719. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1720. translation.x = this.m[12];
  1721. translation.y = this.m[13];
  1722. translation.z = this.m[14];
  1723. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1724. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1725. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1726. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1727. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1728. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1729. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1730. rotation.x = 0;
  1731. rotation.y = 0;
  1732. rotation.z = 0;
  1733. rotation.w = 1;
  1734. return false;
  1735. }
  1736. 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);
  1737. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1738. return true;
  1739. };
  1740. // Statics
  1741. Matrix.FromArray = function (array, offset) {
  1742. var result = new Matrix();
  1743. if (!offset) {
  1744. offset = 0;
  1745. }
  1746. Matrix.FromArrayToRef(array, offset, result);
  1747. return result;
  1748. };
  1749. Matrix.FromArrayToRef = function (array, offset, result) {
  1750. for (var index = 0; index < 16; index++) {
  1751. result.m[index] = array[index + offset];
  1752. }
  1753. };
  1754. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1755. result.m[0] = initialM11;
  1756. result.m[1] = initialM12;
  1757. result.m[2] = initialM13;
  1758. result.m[3] = initialM14;
  1759. result.m[4] = initialM21;
  1760. result.m[5] = initialM22;
  1761. result.m[6] = initialM23;
  1762. result.m[7] = initialM24;
  1763. result.m[8] = initialM31;
  1764. result.m[9] = initialM32;
  1765. result.m[10] = initialM33;
  1766. result.m[11] = initialM34;
  1767. result.m[12] = initialM41;
  1768. result.m[13] = initialM42;
  1769. result.m[14] = initialM43;
  1770. result.m[15] = initialM44;
  1771. };
  1772. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1773. var result = new Matrix();
  1774. result.m[0] = initialM11;
  1775. result.m[1] = initialM12;
  1776. result.m[2] = initialM13;
  1777. result.m[3] = initialM14;
  1778. result.m[4] = initialM21;
  1779. result.m[5] = initialM22;
  1780. result.m[6] = initialM23;
  1781. result.m[7] = initialM24;
  1782. result.m[8] = initialM31;
  1783. result.m[9] = initialM32;
  1784. result.m[10] = initialM33;
  1785. result.m[11] = initialM34;
  1786. result.m[12] = initialM41;
  1787. result.m[13] = initialM42;
  1788. result.m[14] = initialM43;
  1789. result.m[15] = initialM44;
  1790. return result;
  1791. };
  1792. Matrix.Compose = function (scale, rotation, translation) {
  1793. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1794. var rotationMatrix = Matrix.Identity();
  1795. rotation.toRotationMatrix(rotationMatrix);
  1796. result = result.multiply(rotationMatrix);
  1797. result.setTranslation(translation);
  1798. return result;
  1799. };
  1800. Matrix.Identity = function () {
  1801. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1802. };
  1803. Matrix.IdentityToRef = function (result) {
  1804. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1805. };
  1806. Matrix.Zero = function () {
  1807. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1808. };
  1809. Matrix.RotationX = function (angle) {
  1810. var result = new Matrix();
  1811. Matrix.RotationXToRef(angle, result);
  1812. return result;
  1813. };
  1814. Matrix.Invert = function (source) {
  1815. var result = new Matrix();
  1816. source.invertToRef(result);
  1817. return result;
  1818. };
  1819. Matrix.RotationXToRef = function (angle, result) {
  1820. var s = Math.sin(angle);
  1821. var c = Math.cos(angle);
  1822. result.m[0] = 1.0;
  1823. result.m[15] = 1.0;
  1824. result.m[5] = c;
  1825. result.m[10] = c;
  1826. result.m[9] = -s;
  1827. result.m[6] = s;
  1828. result.m[1] = 0;
  1829. result.m[2] = 0;
  1830. result.m[3] = 0;
  1831. result.m[4] = 0;
  1832. result.m[7] = 0;
  1833. result.m[8] = 0;
  1834. result.m[11] = 0;
  1835. result.m[12] = 0;
  1836. result.m[13] = 0;
  1837. result.m[14] = 0;
  1838. };
  1839. Matrix.RotationY = function (angle) {
  1840. var result = new Matrix();
  1841. Matrix.RotationYToRef(angle, result);
  1842. return result;
  1843. };
  1844. Matrix.RotationYToRef = function (angle, result) {
  1845. var s = Math.sin(angle);
  1846. var c = Math.cos(angle);
  1847. result.m[5] = 1.0;
  1848. result.m[15] = 1.0;
  1849. result.m[0] = c;
  1850. result.m[2] = -s;
  1851. result.m[8] = s;
  1852. result.m[10] = c;
  1853. result.m[1] = 0;
  1854. result.m[3] = 0;
  1855. result.m[4] = 0;
  1856. result.m[6] = 0;
  1857. result.m[7] = 0;
  1858. result.m[9] = 0;
  1859. result.m[11] = 0;
  1860. result.m[12] = 0;
  1861. result.m[13] = 0;
  1862. result.m[14] = 0;
  1863. };
  1864. Matrix.RotationZ = function (angle) {
  1865. var result = new Matrix();
  1866. Matrix.RotationZToRef(angle, result);
  1867. return result;
  1868. };
  1869. Matrix.RotationZToRef = function (angle, result) {
  1870. var s = Math.sin(angle);
  1871. var c = Math.cos(angle);
  1872. result.m[10] = 1.0;
  1873. result.m[15] = 1.0;
  1874. result.m[0] = c;
  1875. result.m[1] = s;
  1876. result.m[4] = -s;
  1877. result.m[5] = c;
  1878. result.m[2] = 0;
  1879. result.m[3] = 0;
  1880. result.m[6] = 0;
  1881. result.m[7] = 0;
  1882. result.m[8] = 0;
  1883. result.m[9] = 0;
  1884. result.m[11] = 0;
  1885. result.m[12] = 0;
  1886. result.m[13] = 0;
  1887. result.m[14] = 0;
  1888. };
  1889. Matrix.RotationAxis = function (axis, angle) {
  1890. var s = Math.sin(-angle);
  1891. var c = Math.cos(-angle);
  1892. var c1 = 1 - c;
  1893. axis.normalize();
  1894. var result = Matrix.Zero();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. return result;
  1909. };
  1910. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1911. var result = new Matrix();
  1912. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1913. return result;
  1914. };
  1915. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1916. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1917. this._tempQuaternion.toRotationMatrix(result);
  1918. };
  1919. Matrix.Scaling = function (x, y, z) {
  1920. var result = Matrix.Zero();
  1921. Matrix.ScalingToRef(x, y, z, result);
  1922. return result;
  1923. };
  1924. Matrix.ScalingToRef = function (x, y, z, result) {
  1925. result.m[0] = x;
  1926. result.m[1] = 0;
  1927. result.m[2] = 0;
  1928. result.m[3] = 0;
  1929. result.m[4] = 0;
  1930. result.m[5] = y;
  1931. result.m[6] = 0;
  1932. result.m[7] = 0;
  1933. result.m[8] = 0;
  1934. result.m[9] = 0;
  1935. result.m[10] = z;
  1936. result.m[11] = 0;
  1937. result.m[12] = 0;
  1938. result.m[13] = 0;
  1939. result.m[14] = 0;
  1940. result.m[15] = 1.0;
  1941. };
  1942. Matrix.Translation = function (x, y, z) {
  1943. var result = Matrix.Identity();
  1944. Matrix.TranslationToRef(x, y, z, result);
  1945. return result;
  1946. };
  1947. Matrix.TranslationToRef = function (x, y, z, result) {
  1948. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1949. };
  1950. Matrix.LookAtLH = function (eye, target, up) {
  1951. var result = Matrix.Zero();
  1952. Matrix.LookAtLHToRef(eye, target, up, result);
  1953. return result;
  1954. };
  1955. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1956. // Z axis
  1957. target.subtractToRef(eye, this._zAxis);
  1958. this._zAxis.normalize();
  1959. // X axis
  1960. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1961. this._xAxis.normalize();
  1962. // Y axis
  1963. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1964. this._yAxis.normalize();
  1965. // Eye angles
  1966. var ex = -Vector3.Dot(this._xAxis, eye);
  1967. var ey = -Vector3.Dot(this._yAxis, eye);
  1968. var ez = -Vector3.Dot(this._zAxis, eye);
  1969. 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);
  1970. };
  1971. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1972. var out = result.m;
  1973. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1974. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1975. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1976. // cc.kmVec3Subtract(f, pCenter, pEye);
  1977. var f = SIMD.float32x4.sub(center, eye);
  1978. // cc.kmVec3Normalize(f, f);
  1979. var tmp = SIMD.float32x4.mul(f, f);
  1980. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1981. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1982. // cc.kmVec3Assign(up, pUp);
  1983. // cc.kmVec3Normalize(up, up);
  1984. tmp = SIMD.float32x4.mul(up, up);
  1985. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1986. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1987. // cc.kmVec3Cross(s, f, up);
  1988. 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)));
  1989. // cc.kmVec3Normalize(s, s);
  1990. tmp = SIMD.float32x4.mul(s, s);
  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. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1993. // cc.kmVec3Cross(u, s, f);
  1994. 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)));
  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. var zero = SIMD.float32x4.splat(0.0);
  2000. s = SIMD.float32x4.neg(s);
  2001. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2002. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2003. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2004. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2005. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2006. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2007. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2008. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2009. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2010. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2011. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2012. var b3 = SIMD.float32x4.neg(eye);
  2013. b3 = SIMD.float32x4.withW(b3, 1.0);
  2014. 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)))));
  2015. 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)))));
  2016. 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)))));
  2017. 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)))));
  2018. };
  2019. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2020. var matrix = Matrix.Zero();
  2021. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2022. return matrix;
  2023. };
  2024. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2025. var hw = 2.0 / width;
  2026. var hh = 2.0 / height;
  2027. var id = 1.0 / (zfar - znear);
  2028. var nid = znear / (znear - zfar);
  2029. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2030. };
  2031. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2037. result.m[0] = 2.0 / (right - left);
  2038. result.m[1] = result.m[2] = result.m[3] = 0;
  2039. result.m[5] = 2.0 / (top - bottom);
  2040. result.m[4] = result.m[6] = result.m[7] = 0;
  2041. result.m[10] = -1.0 / (znear - zfar);
  2042. result.m[8] = result.m[9] = result.m[11] = 0;
  2043. result.m[12] = (left + right) / (left - right);
  2044. result.m[13] = (top + bottom) / (bottom - top);
  2045. result.m[14] = znear / (znear - zfar);
  2046. result.m[15] = 1.0;
  2047. };
  2048. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2049. var matrix = Matrix.Zero();
  2050. matrix.m[0] = (2.0 * znear) / width;
  2051. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2052. matrix.m[5] = (2.0 * znear) / height;
  2053. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2054. matrix.m[10] = -zfar / (znear - zfar);
  2055. matrix.m[8] = matrix.m[9] = 0.0;
  2056. matrix.m[11] = 1.0;
  2057. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2058. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2059. return matrix;
  2060. };
  2061. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2062. var matrix = Matrix.Zero();
  2063. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2064. return matrix;
  2065. };
  2066. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2067. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2068. var tan = 1.0 / (Math.tan(fov * 0.5));
  2069. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2070. if (v_fixed) {
  2071. result.m[0] = tan / aspect;
  2072. }
  2073. else {
  2074. result.m[0] = tan;
  2075. }
  2076. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2077. if (v_fixed) {
  2078. result.m[5] = tan;
  2079. }
  2080. else {
  2081. result.m[5] = tan * aspect;
  2082. }
  2083. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2084. result.m[8] = result.m[9] = 0.0;
  2085. result.m[10] = -zfar / (znear - zfar);
  2086. result.m[11] = 1.0;
  2087. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2088. result.m[14] = (znear * zfar) / (znear - zfar);
  2089. };
  2090. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2091. var cw = viewport.width;
  2092. var ch = viewport.height;
  2093. var cx = viewport.x;
  2094. var cy = viewport.y;
  2095. 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);
  2096. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2097. };
  2098. Matrix.Transpose = function (matrix) {
  2099. var result = new Matrix();
  2100. result.m[0] = matrix.m[0];
  2101. result.m[1] = matrix.m[4];
  2102. result.m[2] = matrix.m[8];
  2103. result.m[3] = matrix.m[12];
  2104. result.m[4] = matrix.m[1];
  2105. result.m[5] = matrix.m[5];
  2106. result.m[6] = matrix.m[9];
  2107. result.m[7] = matrix.m[13];
  2108. result.m[8] = matrix.m[2];
  2109. result.m[9] = matrix.m[6];
  2110. result.m[10] = matrix.m[10];
  2111. result.m[11] = matrix.m[14];
  2112. result.m[12] = matrix.m[3];
  2113. result.m[13] = matrix.m[7];
  2114. result.m[14] = matrix.m[11];
  2115. result.m[15] = matrix.m[15];
  2116. return result;
  2117. };
  2118. Matrix.Reflection = function (plane) {
  2119. var matrix = new Matrix();
  2120. Matrix.ReflectionToRef(plane, matrix);
  2121. return matrix;
  2122. };
  2123. Matrix.ReflectionToRef = function (plane, result) {
  2124. plane.normalize();
  2125. var x = plane.normal.x;
  2126. var y = plane.normal.y;
  2127. var z = plane.normal.z;
  2128. var temp = -2 * x;
  2129. var temp2 = -2 * y;
  2130. var temp3 = -2 * z;
  2131. result.m[0] = (temp * x) + 1;
  2132. result.m[1] = temp2 * x;
  2133. result.m[2] = temp3 * x;
  2134. result.m[3] = 0.0;
  2135. result.m[4] = temp * y;
  2136. result.m[5] = (temp2 * y) + 1;
  2137. result.m[6] = temp3 * y;
  2138. result.m[7] = 0.0;
  2139. result.m[8] = temp * z;
  2140. result.m[9] = temp2 * z;
  2141. result.m[10] = (temp3 * z) + 1;
  2142. result.m[11] = 0.0;
  2143. result.m[12] = temp * plane.d;
  2144. result.m[13] = temp2 * plane.d;
  2145. result.m[14] = temp3 * plane.d;
  2146. result.m[15] = 1.0;
  2147. };
  2148. Matrix._tempQuaternion = new Quaternion();
  2149. Matrix._xAxis = Vector3.Zero();
  2150. Matrix._yAxis = Vector3.Zero();
  2151. Matrix._zAxis = Vector3.Zero();
  2152. return Matrix;
  2153. })();
  2154. BABYLON.Matrix = Matrix;
  2155. var Plane = (function () {
  2156. function Plane(a, b, c, d) {
  2157. this.normal = new Vector3(a, b, c);
  2158. this.d = d;
  2159. }
  2160. Plane.prototype.asArray = function () {
  2161. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2162. };
  2163. // Methods
  2164. Plane.prototype.clone = function () {
  2165. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2166. };
  2167. Plane.prototype.normalize = function () {
  2168. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2169. var magnitude = 0;
  2170. if (norm !== 0) {
  2171. magnitude = 1.0 / norm;
  2172. }
  2173. this.normal.x *= magnitude;
  2174. this.normal.y *= magnitude;
  2175. this.normal.z *= magnitude;
  2176. this.d *= magnitude;
  2177. return this;
  2178. };
  2179. Plane.prototype.transform = function (transformation) {
  2180. var transposedMatrix = Matrix.Transpose(transformation);
  2181. var x = this.normal.x;
  2182. var y = this.normal.y;
  2183. var z = this.normal.z;
  2184. var d = this.d;
  2185. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2186. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2187. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2188. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2189. return new Plane(normalX, normalY, normalZ, finalD);
  2190. };
  2191. Plane.prototype.dotCoordinate = function (point) {
  2192. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2193. };
  2194. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2195. var x1 = point2.x - point1.x;
  2196. var y1 = point2.y - point1.y;
  2197. var z1 = point2.z - point1.z;
  2198. var x2 = point3.x - point1.x;
  2199. var y2 = point3.y - point1.y;
  2200. var z2 = point3.z - point1.z;
  2201. var yz = (y1 * z2) - (z1 * y2);
  2202. var xz = (z1 * x2) - (x1 * z2);
  2203. var xy = (x1 * y2) - (y1 * x2);
  2204. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2205. var invPyth;
  2206. if (pyth !== 0) {
  2207. invPyth = 1.0 / pyth;
  2208. }
  2209. else {
  2210. invPyth = 0;
  2211. }
  2212. this.normal.x = yz * invPyth;
  2213. this.normal.y = xz * invPyth;
  2214. this.normal.z = xy * invPyth;
  2215. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2216. return this;
  2217. };
  2218. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2219. var dot = Vector3.Dot(this.normal, direction);
  2220. return (dot <= epsilon);
  2221. };
  2222. Plane.prototype.signedDistanceTo = function (point) {
  2223. return Vector3.Dot(point, this.normal) + this.d;
  2224. };
  2225. // Statics
  2226. Plane.FromArray = function (array) {
  2227. return new Plane(array[0], array[1], array[2], array[3]);
  2228. };
  2229. Plane.FromPoints = function (point1, point2, point3) {
  2230. var result = new Plane(0, 0, 0, 0);
  2231. result.copyFromPoints(point1, point2, point3);
  2232. return result;
  2233. };
  2234. Plane.FromPositionAndNormal = function (origin, normal) {
  2235. var result = new Plane(0, 0, 0, 0);
  2236. normal.normalize();
  2237. result.normal = normal;
  2238. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2239. return result;
  2240. };
  2241. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2242. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2243. return Vector3.Dot(point, normal) + d;
  2244. };
  2245. return Plane;
  2246. })();
  2247. BABYLON.Plane = Plane;
  2248. var Viewport = (function () {
  2249. function Viewport(x, y, width, height) {
  2250. this.x = x;
  2251. this.y = y;
  2252. this.width = width;
  2253. this.height = height;
  2254. }
  2255. Viewport.prototype.toGlobal = function (engine) {
  2256. var width = engine.getRenderWidth();
  2257. var height = engine.getRenderHeight();
  2258. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2259. };
  2260. return Viewport;
  2261. })();
  2262. BABYLON.Viewport = Viewport;
  2263. var Frustum = (function () {
  2264. function Frustum() {
  2265. }
  2266. Frustum.GetPlanes = function (transform) {
  2267. var frustumPlanes = [];
  2268. for (var index = 0; index < 6; index++) {
  2269. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2270. }
  2271. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2272. return frustumPlanes;
  2273. };
  2274. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2275. // Near
  2276. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2277. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2278. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2279. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2280. frustumPlanes[0].normalize();
  2281. // Far
  2282. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2283. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2284. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2285. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2286. frustumPlanes[1].normalize();
  2287. // Left
  2288. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2289. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2290. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2291. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2292. frustumPlanes[2].normalize();
  2293. // Right
  2294. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2295. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2296. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2297. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2298. frustumPlanes[3].normalize();
  2299. // Top
  2300. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2301. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2302. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2303. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2304. frustumPlanes[4].normalize();
  2305. // Bottom
  2306. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2307. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2308. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2309. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2310. frustumPlanes[5].normalize();
  2311. };
  2312. return Frustum;
  2313. })();
  2314. BABYLON.Frustum = Frustum;
  2315. var Ray = (function () {
  2316. function Ray(origin, direction, length) {
  2317. if (length === void 0) { length = Number.MAX_VALUE; }
  2318. this.origin = origin;
  2319. this.direction = direction;
  2320. this.length = length;
  2321. }
  2322. // Methods
  2323. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2324. var d = 0.0;
  2325. var maxValue = Number.MAX_VALUE;
  2326. if (Math.abs(this.direction.x) < 0.0000001) {
  2327. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2328. return false;
  2329. }
  2330. }
  2331. else {
  2332. var inv = 1.0 / this.direction.x;
  2333. var min = (minimum.x - this.origin.x) * inv;
  2334. var max = (maximum.x - this.origin.x) * inv;
  2335. if (max === -Infinity) {
  2336. max = Infinity;
  2337. }
  2338. if (min > max) {
  2339. var temp = min;
  2340. min = max;
  2341. max = temp;
  2342. }
  2343. d = Math.max(min, d);
  2344. maxValue = Math.min(max, maxValue);
  2345. if (d > maxValue) {
  2346. return false;
  2347. }
  2348. }
  2349. if (Math.abs(this.direction.y) < 0.0000001) {
  2350. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2351. return false;
  2352. }
  2353. }
  2354. else {
  2355. inv = 1.0 / this.direction.y;
  2356. min = (minimum.y - this.origin.y) * inv;
  2357. max = (maximum.y - this.origin.y) * inv;
  2358. if (max === -Infinity) {
  2359. max = Infinity;
  2360. }
  2361. if (min > max) {
  2362. temp = min;
  2363. min = max;
  2364. max = temp;
  2365. }
  2366. d = Math.max(min, d);
  2367. maxValue = Math.min(max, maxValue);
  2368. if (d > maxValue) {
  2369. return false;
  2370. }
  2371. }
  2372. if (Math.abs(this.direction.z) < 0.0000001) {
  2373. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2374. return false;
  2375. }
  2376. }
  2377. else {
  2378. inv = 1.0 / this.direction.z;
  2379. min = (minimum.z - this.origin.z) * inv;
  2380. max = (maximum.z - this.origin.z) * inv;
  2381. if (max === -Infinity) {
  2382. max = Infinity;
  2383. }
  2384. if (min > max) {
  2385. temp = min;
  2386. min = max;
  2387. max = temp;
  2388. }
  2389. d = Math.max(min, d);
  2390. maxValue = Math.min(max, maxValue);
  2391. if (d > maxValue) {
  2392. return false;
  2393. }
  2394. }
  2395. return true;
  2396. };
  2397. Ray.prototype.intersectsBox = function (box) {
  2398. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2399. };
  2400. Ray.prototype.intersectsSphere = function (sphere) {
  2401. var x = sphere.center.x - this.origin.x;
  2402. var y = sphere.center.y - this.origin.y;
  2403. var z = sphere.center.z - this.origin.z;
  2404. var pyth = (x * x) + (y * y) + (z * z);
  2405. var rr = sphere.radius * sphere.radius;
  2406. if (pyth <= rr) {
  2407. return true;
  2408. }
  2409. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2410. if (dot < 0.0) {
  2411. return false;
  2412. }
  2413. var temp = pyth - (dot * dot);
  2414. return temp <= rr;
  2415. };
  2416. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2417. if (!this._edge1) {
  2418. this._edge1 = Vector3.Zero();
  2419. this._edge2 = Vector3.Zero();
  2420. this._pvec = Vector3.Zero();
  2421. this._tvec = Vector3.Zero();
  2422. this._qvec = Vector3.Zero();
  2423. }
  2424. vertex1.subtractToRef(vertex0, this._edge1);
  2425. vertex2.subtractToRef(vertex0, this._edge2);
  2426. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2427. var det = Vector3.Dot(this._edge1, this._pvec);
  2428. if (det === 0) {
  2429. return null;
  2430. }
  2431. var invdet = 1 / det;
  2432. this.origin.subtractToRef(vertex0, this._tvec);
  2433. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2434. if (bu < 0 || bu > 1.0) {
  2435. return null;
  2436. }
  2437. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2438. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2439. if (bv < 0 || bu + bv > 1.0) {
  2440. return null;
  2441. }
  2442. //check if the distance is longer than the predefined length.
  2443. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2444. if (distance > this.length) {
  2445. return null;
  2446. }
  2447. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2448. };
  2449. // Statics
  2450. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2451. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2452. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2453. var direction = end.subtract(start);
  2454. direction.normalize();
  2455. return new Ray(start, direction);
  2456. };
  2457. /**
  2458. * 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
  2459. * transformed to the given world matrix.
  2460. * @param origin The origin point
  2461. * @param end The end point
  2462. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2463. */
  2464. Ray.CreateNewFromTo = function (origin, end, world) {
  2465. if (world === void 0) { world = Matrix.Identity(); }
  2466. var direction = end.subtract(origin);
  2467. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2468. direction.normalize();
  2469. return Ray.Transform(new Ray(origin, direction, length), world);
  2470. };
  2471. Ray.Transform = function (ray, matrix) {
  2472. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2473. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2474. return new Ray(newOrigin, newDirection, ray.length);
  2475. };
  2476. return Ray;
  2477. })();
  2478. BABYLON.Ray = Ray;
  2479. (function (Space) {
  2480. Space[Space["LOCAL"] = 0] = "LOCAL";
  2481. Space[Space["WORLD"] = 1] = "WORLD";
  2482. })(BABYLON.Space || (BABYLON.Space = {}));
  2483. var Space = BABYLON.Space;
  2484. var Axis = (function () {
  2485. function Axis() {
  2486. }
  2487. Axis.X = new Vector3(1, 0, 0);
  2488. Axis.Y = new Vector3(0, 1, 0);
  2489. Axis.Z = new Vector3(0, 0, 1);
  2490. return Axis;
  2491. })();
  2492. BABYLON.Axis = Axis;
  2493. ;
  2494. var BezierCurve = (function () {
  2495. function BezierCurve() {
  2496. }
  2497. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2498. // Extract X (which is equal to time here)
  2499. var f0 = 1 - 3 * x2 + 3 * x1;
  2500. var f1 = 3 * x2 - 6 * x1;
  2501. var f2 = 3 * x1;
  2502. var refinedT = t;
  2503. for (var i = 0; i < 5; i++) {
  2504. var refinedT2 = refinedT * refinedT;
  2505. var refinedT3 = refinedT2 * refinedT;
  2506. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2507. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2508. refinedT -= (x - t) * slope;
  2509. refinedT = Math.min(1, Math.max(0, refinedT));
  2510. }
  2511. // Resolve cubic bezier for the given x
  2512. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2513. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2514. Math.pow(refinedT, 3);
  2515. };
  2516. return BezierCurve;
  2517. })();
  2518. BABYLON.BezierCurve = BezierCurve;
  2519. (function (Orientation) {
  2520. Orientation[Orientation["CW"] = 0] = "CW";
  2521. Orientation[Orientation["CCW"] = 1] = "CCW";
  2522. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2523. var Orientation = BABYLON.Orientation;
  2524. var Angle = (function () {
  2525. function Angle(radians) {
  2526. var _this = this;
  2527. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2528. this.radians = function () { return _this._radians; };
  2529. this._radians = radians;
  2530. if (this._radians < 0)
  2531. this._radians += (2 * Math.PI);
  2532. }
  2533. Angle.BetweenTwoPoints = function (a, b) {
  2534. var delta = b.subtract(a);
  2535. var theta = Math.atan2(delta.y, delta.x);
  2536. return new Angle(theta);
  2537. };
  2538. Angle.FromRadians = function (radians) {
  2539. return new Angle(radians);
  2540. };
  2541. Angle.FromDegrees = function (degrees) {
  2542. return new Angle(degrees * Math.PI / 180);
  2543. };
  2544. return Angle;
  2545. })();
  2546. BABYLON.Angle = Angle;
  2547. var Arc2 = (function () {
  2548. function Arc2(startPoint, midPoint, endPoint) {
  2549. this.startPoint = startPoint;
  2550. this.midPoint = midPoint;
  2551. this.endPoint = endPoint;
  2552. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2553. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2554. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2555. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2556. 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);
  2557. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2558. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2559. var a1 = this.startAngle.degrees();
  2560. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2561. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2562. // angles correction
  2563. if (a2 - a1 > +180.0)
  2564. a2 -= 360.0;
  2565. if (a2 - a1 < -180.0)
  2566. a2 += 360.0;
  2567. if (a3 - a2 > +180.0)
  2568. a3 -= 360.0;
  2569. if (a3 - a2 < -180.0)
  2570. a3 += 360.0;
  2571. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2572. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2573. }
  2574. return Arc2;
  2575. })();
  2576. BABYLON.Arc2 = Arc2;
  2577. var PathCursor = (function () {
  2578. function PathCursor(path) {
  2579. this.path = path;
  2580. this._onchange = new Array();
  2581. this.value = 0;
  2582. this.animations = new Array();
  2583. }
  2584. PathCursor.prototype.getPoint = function () {
  2585. var point = this.path.getPointAtLengthPosition(this.value);
  2586. return new Vector3(point.x, 0, point.y);
  2587. };
  2588. PathCursor.prototype.moveAhead = function (step) {
  2589. if (step === void 0) { step = 0.002; }
  2590. this.move(step);
  2591. return this;
  2592. };
  2593. PathCursor.prototype.moveBack = function (step) {
  2594. if (step === void 0) { step = 0.002; }
  2595. this.move(-step);
  2596. return this;
  2597. };
  2598. PathCursor.prototype.move = function (step) {
  2599. if (Math.abs(step) > 1) {
  2600. throw "step size should be less than 1.";
  2601. }
  2602. this.value += step;
  2603. this.ensureLimits();
  2604. this.raiseOnChange();
  2605. return this;
  2606. };
  2607. PathCursor.prototype.ensureLimits = function () {
  2608. while (this.value > 1) {
  2609. this.value -= 1;
  2610. }
  2611. while (this.value < 0) {
  2612. this.value += 1;
  2613. }
  2614. return this;
  2615. };
  2616. // used by animation engine
  2617. PathCursor.prototype.markAsDirty = function (propertyName) {
  2618. this.ensureLimits();
  2619. this.raiseOnChange();
  2620. return this;
  2621. };
  2622. PathCursor.prototype.raiseOnChange = function () {
  2623. var _this = this;
  2624. this._onchange.forEach(function (f) { return f(_this); });
  2625. return this;
  2626. };
  2627. PathCursor.prototype.onchange = function (f) {
  2628. this._onchange.push(f);
  2629. return this;
  2630. };
  2631. return PathCursor;
  2632. })();
  2633. BABYLON.PathCursor = PathCursor;
  2634. var Path2 = (function () {
  2635. function Path2(x, y) {
  2636. this._points = new Array();
  2637. this._length = 0;
  2638. this.closed = false;
  2639. this._points.push(new Vector2(x, y));
  2640. }
  2641. Path2.prototype.addLineTo = function (x, y) {
  2642. if (closed) {
  2643. BABYLON.Tools.Error("cannot add lines to closed paths");
  2644. return this;
  2645. }
  2646. var newPoint = new Vector2(x, y);
  2647. var previousPoint = this._points[this._points.length - 1];
  2648. this._points.push(newPoint);
  2649. this._length += newPoint.subtract(previousPoint).length();
  2650. return this;
  2651. };
  2652. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2653. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2654. if (closed) {
  2655. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2656. return this;
  2657. }
  2658. var startPoint = this._points[this._points.length - 1];
  2659. var midPoint = new Vector2(midX, midY);
  2660. var endPoint = new Vector2(endX, endY);
  2661. var arc = new Arc2(startPoint, midPoint, endPoint);
  2662. var increment = arc.angle.radians() / numberOfSegments;
  2663. if (arc.orientation === Orientation.CW)
  2664. increment *= -1;
  2665. var currentAngle = arc.startAngle.radians() + increment;
  2666. for (var i = 0; i < numberOfSegments; i++) {
  2667. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2668. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2669. this.addLineTo(x, y);
  2670. currentAngle += increment;
  2671. }
  2672. return this;
  2673. };
  2674. Path2.prototype.close = function () {
  2675. this.closed = true;
  2676. return this;
  2677. };
  2678. Path2.prototype.length = function () {
  2679. var result = this._length;
  2680. if (!this.closed) {
  2681. var lastPoint = this._points[this._points.length - 1];
  2682. var firstPoint = this._points[0];
  2683. result += (firstPoint.subtract(lastPoint).length());
  2684. }
  2685. return result;
  2686. };
  2687. Path2.prototype.getPoints = function () {
  2688. return this._points;
  2689. };
  2690. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2691. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2692. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2693. return Vector2.Zero();
  2694. }
  2695. var lengthPosition = normalizedLengthPosition * this.length();
  2696. var previousOffset = 0;
  2697. for (var i = 0; i < this._points.length; i++) {
  2698. var j = (i + 1) % this._points.length;
  2699. var a = this._points[i];
  2700. var b = this._points[j];
  2701. var bToA = b.subtract(a);
  2702. var nextOffset = (bToA.length() + previousOffset);
  2703. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2704. var dir = bToA.normalize();
  2705. var localOffset = lengthPosition - previousOffset;
  2706. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2707. }
  2708. previousOffset = nextOffset;
  2709. }
  2710. BABYLON.Tools.Error("internal error");
  2711. return Vector2.Zero();
  2712. };
  2713. Path2.StartingAt = function (x, y) {
  2714. return new Path2(x, y);
  2715. };
  2716. return Path2;
  2717. })();
  2718. BABYLON.Path2 = Path2;
  2719. var Path3D = (function () {
  2720. function Path3D(path, firstNormal) {
  2721. this.path = path;
  2722. this._curve = new Array();
  2723. this._distances = new Array();
  2724. this._tangents = new Array();
  2725. this._normals = new Array();
  2726. this._binormals = new Array();
  2727. for (var p = 0; p < path.length; p++) {
  2728. this._curve[p] = path[p].clone(); // hard copy
  2729. }
  2730. this._compute(firstNormal);
  2731. }
  2732. Path3D.prototype.getCurve = function () {
  2733. return this._curve;
  2734. };
  2735. Path3D.prototype.getTangents = function () {
  2736. return this._tangents;
  2737. };
  2738. Path3D.prototype.getNormals = function () {
  2739. return this._normals;
  2740. };
  2741. Path3D.prototype.getBinormals = function () {
  2742. return this._binormals;
  2743. };
  2744. Path3D.prototype.getDistances = function () {
  2745. return this._distances;
  2746. };
  2747. Path3D.prototype.update = function (path, firstNormal) {
  2748. for (var p = 0; p < path.length; p++) {
  2749. this._curve[p].x = path[p].x;
  2750. this._curve[p].y = path[p].y;
  2751. this._curve[p].z = path[p].z;
  2752. }
  2753. this._compute(firstNormal);
  2754. return this;
  2755. };
  2756. // private function compute() : computes tangents, normals and binormals
  2757. Path3D.prototype._compute = function (firstNormal) {
  2758. var l = this._curve.length;
  2759. // first and last tangents
  2760. this._tangents[0] = this._getFirstNonNullVector(0);
  2761. this._tangents[0].normalize();
  2762. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2763. this._tangents[l - 1].normalize();
  2764. // normals and binormals at first point : arbitrary vector with _normalVector()
  2765. var tg0 = this._tangents[0];
  2766. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2767. this._normals[0] = pp0;
  2768. this._normals[0].normalize();
  2769. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2770. this._binormals[0].normalize();
  2771. this._distances[0] = 0;
  2772. // normals and binormals : next points
  2773. var prev; // previous vector (segment)
  2774. var cur; // current vector (segment)
  2775. var curTang; // current tangent
  2776. var prevNorm; // previous normal
  2777. var prevBinor; // previous binormal
  2778. for (var i = 1; i < l; i++) {
  2779. // tangents
  2780. prev = this._getLastNonNullVector(i);
  2781. if (i < l - 1) {
  2782. cur = this._getFirstNonNullVector(i);
  2783. this._tangents[i] = prev.add(cur);
  2784. this._tangents[i].normalize();
  2785. }
  2786. this._distances[i] = this._distances[i - 1] + prev.length();
  2787. // normals and binormals
  2788. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2789. curTang = this._tangents[i];
  2790. prevNorm = this._normals[i - 1];
  2791. prevBinor = this._binormals[i - 1];
  2792. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2793. this._normals[i].normalize();
  2794. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2795. this._binormals[i].normalize();
  2796. }
  2797. };
  2798. // private function getFirstNonNullVector(index)
  2799. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2800. Path3D.prototype._getFirstNonNullVector = function (index) {
  2801. var i = 1;
  2802. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2803. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2804. i++;
  2805. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2806. }
  2807. return nNVector;
  2808. };
  2809. // private function getLastNonNullVector(index)
  2810. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2811. Path3D.prototype._getLastNonNullVector = function (index) {
  2812. var i = 1;
  2813. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2814. while (nLVector.length() == 0 && index > i + 1) {
  2815. i++;
  2816. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2817. }
  2818. return nLVector;
  2819. };
  2820. // private function normalVector(v0, vt, va) :
  2821. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2822. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2823. Path3D.prototype._normalVector = function (v0, vt, va) {
  2824. var normal0;
  2825. if (va === undefined || va === null) {
  2826. var point;
  2827. if (vt.y !== 1) {
  2828. point = new Vector3(0, -1, 0);
  2829. }
  2830. else if (vt.x !== 1) {
  2831. point = new Vector3(1, 0, 0);
  2832. }
  2833. else if (vt.z !== 1) {
  2834. point = new Vector3(0, 0, 1);
  2835. }
  2836. normal0 = Vector3.Cross(vt, point);
  2837. }
  2838. else {
  2839. normal0 = Vector3.Cross(vt, va);
  2840. Vector3.CrossToRef(normal0, vt, normal0);
  2841. }
  2842. normal0.normalize();
  2843. return normal0;
  2844. };
  2845. return Path3D;
  2846. })();
  2847. BABYLON.Path3D = Path3D;
  2848. var Curve3 = (function () {
  2849. function Curve3(points) {
  2850. this._length = 0;
  2851. this._points = points;
  2852. this._length = this._computeLength(points);
  2853. }
  2854. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2855. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2856. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2857. var bez = new Array();
  2858. var equation = function (t, val0, val1, val2) {
  2859. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2860. return res;
  2861. };
  2862. for (var i = 0; i <= nbPoints; i++) {
  2863. 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)));
  2864. }
  2865. return new Curve3(bez);
  2866. };
  2867. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2868. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2869. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2870. var bez = new Array();
  2871. var equation = function (t, val0, val1, val2, val3) {
  2872. 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;
  2873. return res;
  2874. };
  2875. for (var i = 0; i <= nbPoints; i++) {
  2876. 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)));
  2877. }
  2878. return new Curve3(bez);
  2879. };
  2880. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2881. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2882. var hermite = new Array();
  2883. var step = 1 / nbPoints;
  2884. for (var i = 0; i <= nbPoints; i++) {
  2885. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2886. }
  2887. return new Curve3(hermite);
  2888. };
  2889. Curve3.prototype.getPoints = function () {
  2890. return this._points;
  2891. };
  2892. Curve3.prototype.length = function () {
  2893. return this._length;
  2894. };
  2895. Curve3.prototype.continue = function (curve) {
  2896. var lastPoint = this._points[this._points.length - 1];
  2897. var continuedPoints = this._points.slice();
  2898. var curvePoints = curve.getPoints();
  2899. for (var i = 1; i < curvePoints.length; i++) {
  2900. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2901. }
  2902. var continuedCurve = new Curve3(continuedPoints);
  2903. return continuedCurve;
  2904. };
  2905. Curve3.prototype._computeLength = function (path) {
  2906. var l = 0;
  2907. for (var i = 1; i < path.length; i++) {
  2908. l += (path[i].subtract(path[i - 1])).length();
  2909. }
  2910. return l;
  2911. };
  2912. return Curve3;
  2913. })();
  2914. BABYLON.Curve3 = Curve3;
  2915. // Vertex formats
  2916. var PositionNormalVertex = (function () {
  2917. function PositionNormalVertex(position, normal) {
  2918. if (position === void 0) { position = Vector3.Zero(); }
  2919. if (normal === void 0) { normal = Vector3.Up(); }
  2920. this.position = position;
  2921. this.normal = normal;
  2922. }
  2923. PositionNormalVertex.prototype.clone = function () {
  2924. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2925. };
  2926. return PositionNormalVertex;
  2927. })();
  2928. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2929. var PositionNormalTextureVertex = (function () {
  2930. function PositionNormalTextureVertex(position, normal, uv) {
  2931. if (position === void 0) { position = Vector3.Zero(); }
  2932. if (normal === void 0) { normal = Vector3.Up(); }
  2933. if (uv === void 0) { uv = Vector2.Zero(); }
  2934. this.position = position;
  2935. this.normal = normal;
  2936. this.uv = uv;
  2937. }
  2938. PositionNormalTextureVertex.prototype.clone = function () {
  2939. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2940. };
  2941. return PositionNormalTextureVertex;
  2942. })();
  2943. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2944. // SIMD
  2945. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2946. var previousInvertToRef = Matrix.prototype.invertToRef;
  2947. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2948. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2949. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2950. var SIMDHelper = (function () {
  2951. function SIMDHelper() {
  2952. }
  2953. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2954. get: function () {
  2955. return SIMDHelper._isEnabled;
  2956. },
  2957. enumerable: true,
  2958. configurable: true
  2959. });
  2960. SIMDHelper.DisableSIMD = function () {
  2961. // Replace functions
  2962. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2963. Matrix.prototype.invertToRef = previousInvertToRef;
  2964. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2965. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2966. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2967. SIMDHelper._isEnabled = false;
  2968. };
  2969. SIMDHelper.EnableSIMD = function () {
  2970. if (window.SIMD === undefined) {
  2971. return;
  2972. }
  2973. // Replace functions
  2974. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2975. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2976. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2977. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2978. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2979. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2980. get: function () { return this._data[0]; },
  2981. set: function (value) {
  2982. if (!this._data) {
  2983. this._data = new Float32Array(3);
  2984. }
  2985. this._data[0] = value;
  2986. }
  2987. });
  2988. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2989. get: function () { return this._data[1]; },
  2990. set: function (value) {
  2991. this._data[1] = value;
  2992. }
  2993. });
  2994. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2995. get: function () { return this._data[2]; },
  2996. set: function (value) {
  2997. this._data[2] = value;
  2998. }
  2999. });
  3000. SIMDHelper._isEnabled = true;
  3001. };
  3002. SIMDHelper._isEnabled = false;
  3003. return SIMDHelper;
  3004. })();
  3005. BABYLON.SIMDHelper = SIMDHelper;
  3006. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  3007. SIMDHelper.EnableSIMD();
  3008. }
  3009. })(BABYLON || (BABYLON = {}));
  3010. //# sourceMappingURL=babylon.math.js.map
  3011. var BABYLON;
  3012. (function (BABYLON) {
  3013. var Database = (function () {
  3014. function Database(urlToScene, callbackManifestChecked) {
  3015. // Handling various flavors of prefixed version of IndexedDB
  3016. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3017. this.callbackManifestChecked = callbackManifestChecked;
  3018. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  3019. this.db = null;
  3020. this.enableSceneOffline = false;
  3021. this.enableTexturesOffline = false;
  3022. this.manifestVersionFound = 0;
  3023. this.mustUpdateRessources = false;
  3024. this.hasReachedQuota = false;
  3025. this.checkManifestFile();
  3026. }
  3027. Database.prototype.checkManifestFile = function () {
  3028. var _this = this;
  3029. function noManifestFile() {
  3030. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  3031. that.enableSceneOffline = false;
  3032. that.enableTexturesOffline = false;
  3033. that.callbackManifestChecked(false);
  3034. }
  3035. var that = this;
  3036. var manifestURL = this.currentSceneUrl + ".manifest";
  3037. var xhr = new XMLHttpRequest();
  3038. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3039. xhr.open("GET", manifestURLTimeStamped, true);
  3040. xhr.addEventListener("load", function () {
  3041. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3042. try {
  3043. var manifestFile = JSON.parse(xhr.response);
  3044. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3045. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3046. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3047. _this.manifestVersionFound = manifestFile.version;
  3048. }
  3049. if (_this.callbackManifestChecked) {
  3050. _this.callbackManifestChecked(true);
  3051. }
  3052. }
  3053. catch (ex) {
  3054. noManifestFile();
  3055. }
  3056. }
  3057. else {
  3058. noManifestFile();
  3059. }
  3060. }, false);
  3061. xhr.addEventListener("error", function (event) {
  3062. noManifestFile();
  3063. }, false);
  3064. try {
  3065. xhr.send();
  3066. }
  3067. catch (ex) {
  3068. BABYLON.Tools.Error("Error on XHR send request.");
  3069. that.callbackManifestChecked(false);
  3070. }
  3071. };
  3072. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3073. var _this = this;
  3074. function handleError() {
  3075. that.isSupported = false;
  3076. if (errorCallback)
  3077. errorCallback();
  3078. }
  3079. var that = this;
  3080. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3081. // Your browser doesn't support IndexedDB
  3082. this.isSupported = false;
  3083. if (errorCallback)
  3084. errorCallback();
  3085. }
  3086. else {
  3087. // If the DB hasn't been opened or created yet
  3088. if (!this.db) {
  3089. this.hasReachedQuota = false;
  3090. this.isSupported = true;
  3091. var request = this.idbFactory.open("babylonjs", 1);
  3092. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3093. request.onerror = function (event) {
  3094. handleError();
  3095. };
  3096. // executes when a version change transaction cannot complete due to other active transactions
  3097. request.onblocked = function (event) {
  3098. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3099. handleError();
  3100. };
  3101. // DB has been opened successfully
  3102. request.onsuccess = function (event) {
  3103. _this.db = request.result;
  3104. successCallback();
  3105. };
  3106. // Initialization of the DB. Creating Scenes & Textures stores
  3107. request.onupgradeneeded = function (event) {
  3108. _this.db = (event.target).result;
  3109. try {
  3110. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3111. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3112. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3113. }
  3114. catch (ex) {
  3115. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3116. handleError();
  3117. }
  3118. };
  3119. }
  3120. else {
  3121. if (successCallback)
  3122. successCallback();
  3123. }
  3124. }
  3125. };
  3126. Database.prototype.loadImageFromDB = function (url, image) {
  3127. var _this = this;
  3128. var completeURL = Database.ReturnFullUrlLocation(url);
  3129. var saveAndLoadImage = function () {
  3130. if (!_this.hasReachedQuota && _this.db !== null) {
  3131. // the texture is not yet in the DB, let's try to save it
  3132. _this._saveImageIntoDBAsync(completeURL, image);
  3133. }
  3134. else {
  3135. image.src = url;
  3136. }
  3137. };
  3138. if (!this.mustUpdateRessources) {
  3139. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3140. }
  3141. else {
  3142. saveAndLoadImage();
  3143. }
  3144. };
  3145. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3146. if (this.isSupported && this.db !== null) {
  3147. var texture;
  3148. var transaction = this.db.transaction(["textures"]);
  3149. transaction.onabort = function (event) {
  3150. image.src = url;
  3151. };
  3152. transaction.oncomplete = function (event) {
  3153. var blobTextureURL;
  3154. if (texture) {
  3155. var URL = window.URL || window.webkitURL;
  3156. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3157. image.onerror = function () {
  3158. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3159. image.src = url;
  3160. };
  3161. image.src = blobTextureURL;
  3162. }
  3163. else {
  3164. notInDBCallback();
  3165. }
  3166. };
  3167. var getRequest = transaction.objectStore("textures").get(url);
  3168. getRequest.onsuccess = function (event) {
  3169. texture = (event.target).result;
  3170. };
  3171. getRequest.onerror = function (event) {
  3172. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3173. image.src = url;
  3174. };
  3175. }
  3176. else {
  3177. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3178. image.src = url;
  3179. }
  3180. };
  3181. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3182. var _this = this;
  3183. if (this.isSupported) {
  3184. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3185. var generateBlobUrl = function () {
  3186. var blobTextureURL;
  3187. if (blob) {
  3188. var URL = window.URL || window.webkitURL;
  3189. try {
  3190. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3191. }
  3192. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3193. catch (ex) {
  3194. blobTextureURL = URL.createObjectURL(blob);
  3195. }
  3196. }
  3197. image.src = blobTextureURL;
  3198. };
  3199. if (Database.isUASupportingBlobStorage) {
  3200. var xhr = new XMLHttpRequest(), blob;
  3201. xhr.open("GET", url, true);
  3202. xhr.responseType = "blob";
  3203. xhr.addEventListener("load", function () {
  3204. if (xhr.status === 200) {
  3205. // Blob as response (XHR2)
  3206. blob = xhr.response;
  3207. var transaction = _this.db.transaction(["textures"], "readwrite");
  3208. // the transaction could abort because of a QuotaExceededError error
  3209. transaction.onabort = function (event) {
  3210. try {
  3211. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3212. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3213. this.hasReachedQuota = true;
  3214. }
  3215. }
  3216. catch (ex) { }
  3217. generateBlobUrl();
  3218. };
  3219. transaction.oncomplete = function (event) {
  3220. generateBlobUrl();
  3221. };
  3222. var newTexture = { textureUrl: url, data: blob };
  3223. try {
  3224. // Put the blob into the dabase
  3225. var addRequest = transaction.objectStore("textures").put(newTexture);
  3226. addRequest.onsuccess = function (event) {
  3227. };
  3228. addRequest.onerror = function (event) {
  3229. generateBlobUrl();
  3230. };
  3231. }
  3232. catch (ex) {
  3233. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3234. if (ex.code === 25) {
  3235. Database.isUASupportingBlobStorage = false;
  3236. }
  3237. image.src = url;
  3238. }
  3239. }
  3240. else {
  3241. image.src = url;
  3242. }
  3243. }, false);
  3244. xhr.addEventListener("error", function (event) {
  3245. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3246. image.src = url;
  3247. }, false);
  3248. xhr.send();
  3249. }
  3250. else {
  3251. image.src = url;
  3252. }
  3253. }
  3254. else {
  3255. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3256. image.src = url;
  3257. }
  3258. };
  3259. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3260. var _this = this;
  3261. var updateVersion = function (event) {
  3262. // the version is not yet in the DB or we need to update it
  3263. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3264. };
  3265. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3266. };
  3267. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3268. var _this = this;
  3269. if (this.isSupported) {
  3270. var version;
  3271. try {
  3272. var transaction = this.db.transaction(["versions"]);
  3273. transaction.oncomplete = function (event) {
  3274. if (version) {
  3275. // If the version in the JSON file is > than the version in DB
  3276. if (_this.manifestVersionFound > version.data) {
  3277. _this.mustUpdateRessources = true;
  3278. updateInDBCallback();
  3279. }
  3280. else {
  3281. callback(version.data);
  3282. }
  3283. }
  3284. else {
  3285. _this.mustUpdateRessources = true;
  3286. updateInDBCallback();
  3287. }
  3288. };
  3289. transaction.onabort = function (event) {
  3290. callback(-1);
  3291. };
  3292. var getRequest = transaction.objectStore("versions").get(url);
  3293. getRequest.onsuccess = function (event) {
  3294. version = (event.target).result;
  3295. };
  3296. getRequest.onerror = function (event) {
  3297. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3298. callback(-1);
  3299. };
  3300. }
  3301. catch (ex) {
  3302. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3303. callback(-1);
  3304. }
  3305. }
  3306. else {
  3307. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3308. callback(-1);
  3309. }
  3310. };
  3311. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3312. var _this = this;
  3313. if (this.isSupported && !this.hasReachedQuota) {
  3314. try {
  3315. // Open a transaction to the database
  3316. var transaction = this.db.transaction(["versions"], "readwrite");
  3317. // the transaction could abort because of a QuotaExceededError error
  3318. transaction.onabort = function (event) {
  3319. try {
  3320. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3321. _this.hasReachedQuota = true;
  3322. }
  3323. }
  3324. catch (ex) { }
  3325. callback(-1);
  3326. };
  3327. transaction.oncomplete = function (event) {
  3328. callback(_this.manifestVersionFound);
  3329. };
  3330. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3331. // Put the scene into the database
  3332. var addRequest = transaction.objectStore("versions").put(newVersion);
  3333. addRequest.onsuccess = function (event) {
  3334. };
  3335. addRequest.onerror = function (event) {
  3336. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3337. };
  3338. }
  3339. catch (ex) {
  3340. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3341. callback(-1);
  3342. }
  3343. }
  3344. else {
  3345. callback(-1);
  3346. }
  3347. };
  3348. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3349. var _this = this;
  3350. var completeUrl = Database.ReturnFullUrlLocation(url);
  3351. var saveAndLoadFile = function (event) {
  3352. // the scene is not yet in the DB, let's try to save it
  3353. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3354. };
  3355. this._checkVersionFromDB(completeUrl, function (version) {
  3356. if (version !== -1) {
  3357. if (!_this.mustUpdateRessources) {
  3358. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3359. }
  3360. else {
  3361. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3362. }
  3363. }
  3364. else {
  3365. errorCallback();
  3366. }
  3367. });
  3368. };
  3369. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3370. if (this.isSupported) {
  3371. var targetStore;
  3372. if (url.indexOf(".babylon") !== -1) {
  3373. targetStore = "scenes";
  3374. }
  3375. else {
  3376. targetStore = "textures";
  3377. }
  3378. var file;
  3379. var transaction = this.db.transaction([targetStore]);
  3380. transaction.oncomplete = function (event) {
  3381. if (file) {
  3382. callback(file.data);
  3383. }
  3384. else {
  3385. notInDBCallback();
  3386. }
  3387. };
  3388. transaction.onabort = function (event) {
  3389. notInDBCallback();
  3390. };
  3391. var getRequest = transaction.objectStore(targetStore).get(url);
  3392. getRequest.onsuccess = function (event) {
  3393. file = (event.target).result;
  3394. };
  3395. getRequest.onerror = function (event) {
  3396. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3397. notInDBCallback();
  3398. };
  3399. }
  3400. else {
  3401. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3402. callback();
  3403. }
  3404. };
  3405. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3406. var _this = this;
  3407. if (this.isSupported) {
  3408. var targetStore;
  3409. if (url.indexOf(".babylon") !== -1) {
  3410. targetStore = "scenes";
  3411. }
  3412. else {
  3413. targetStore = "textures";
  3414. }
  3415. // Create XHR
  3416. var xhr = new XMLHttpRequest(), fileData;
  3417. xhr.open("GET", url, true);
  3418. if (useArrayBuffer) {
  3419. xhr.responseType = "arraybuffer";
  3420. }
  3421. xhr.onprogress = progressCallback;
  3422. xhr.addEventListener("load", function () {
  3423. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3424. // Blob as response (XHR2)
  3425. //fileData = xhr.responseText;
  3426. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3427. if (!_this.hasReachedQuota) {
  3428. // Open a transaction to the database
  3429. var transaction = _this.db.transaction([targetStore], "readwrite");
  3430. // the transaction could abort because of a QuotaExceededError error
  3431. transaction.onabort = function (event) {
  3432. try {
  3433. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3434. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3435. this.hasReachedQuota = true;
  3436. }
  3437. }
  3438. catch (ex) { }
  3439. callback(fileData);
  3440. };
  3441. transaction.oncomplete = function (event) {
  3442. callback(fileData);
  3443. };
  3444. var newFile;
  3445. if (targetStore === "scenes") {
  3446. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3447. }
  3448. else {
  3449. newFile = { textureUrl: url, data: fileData };
  3450. }
  3451. try {
  3452. // Put the scene into the database
  3453. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3454. addRequest.onsuccess = function (event) {
  3455. };
  3456. addRequest.onerror = function (event) {
  3457. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3458. };
  3459. }
  3460. catch (ex) {
  3461. callback(fileData);
  3462. }
  3463. }
  3464. else {
  3465. callback(fileData);
  3466. }
  3467. }
  3468. else {
  3469. callback();
  3470. }
  3471. }, false);
  3472. xhr.addEventListener("error", function (event) {
  3473. BABYLON.Tools.Error("error on XHR request.");
  3474. callback();
  3475. }, false);
  3476. xhr.send();
  3477. }
  3478. else {
  3479. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3480. callback();
  3481. }
  3482. };
  3483. Database.isUASupportingBlobStorage = true;
  3484. Database.parseURL = function (url) {
  3485. var a = document.createElement('a');
  3486. a.href = url;
  3487. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3488. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3489. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3490. return absLocation;
  3491. };
  3492. Database.ReturnFullUrlLocation = function (url) {
  3493. if (url.indexOf("http:/") === -1) {
  3494. return (BABYLON.Database.parseURL(window.location.href) + url);
  3495. }
  3496. else {
  3497. return url;
  3498. }
  3499. };
  3500. return Database;
  3501. })();
  3502. BABYLON.Database = Database;
  3503. })(BABYLON || (BABYLON = {}));
  3504. //# sourceMappingURL=babylon.database.js.map
  3505. var BABYLON;
  3506. (function (BABYLON) {
  3507. var Internals;
  3508. (function (Internals) {
  3509. /*
  3510. * Based on jsTGALoader - Javascript loader for TGA file
  3511. * By Vincent Thibault
  3512. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3513. */
  3514. var TGATools = (function () {
  3515. function TGATools() {
  3516. }
  3517. TGATools.GetTGAHeader = function (data) {
  3518. var offset = 0;
  3519. var header = {
  3520. id_length: data[offset++],
  3521. colormap_type: data[offset++],
  3522. image_type: data[offset++],
  3523. colormap_index: data[offset++] | data[offset++] << 8,
  3524. colormap_length: data[offset++] | data[offset++] << 8,
  3525. colormap_size: data[offset++],
  3526. origin: [
  3527. data[offset++] | data[offset++] << 8,
  3528. data[offset++] | data[offset++] << 8
  3529. ],
  3530. width: data[offset++] | data[offset++] << 8,
  3531. height: data[offset++] | data[offset++] << 8,
  3532. pixel_size: data[offset++],
  3533. flags: data[offset++]
  3534. };
  3535. return header;
  3536. };
  3537. TGATools.UploadContent = function (gl, data) {
  3538. // Not enough data to contain header ?
  3539. if (data.length < 19) {
  3540. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3541. return;
  3542. }
  3543. // Read Header
  3544. var offset = 18;
  3545. var header = TGATools.GetTGAHeader(data);
  3546. // Assume it's a valid Targa file.
  3547. if (header.id_length + offset > data.length) {
  3548. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3549. return;
  3550. }
  3551. // Skip not needed data
  3552. offset += header.id_length;
  3553. var use_rle = false;
  3554. var use_pal = false;
  3555. var use_rgb = false;
  3556. var use_grey = false;
  3557. // Get some informations.
  3558. switch (header.image_type) {
  3559. case TGATools._TYPE_RLE_INDEXED:
  3560. use_rle = true;
  3561. case TGATools._TYPE_INDEXED:
  3562. use_pal = true;
  3563. break;
  3564. case TGATools._TYPE_RLE_RGB:
  3565. use_rle = true;
  3566. case TGATools._TYPE_RGB:
  3567. use_rgb = true;
  3568. break;
  3569. case TGATools._TYPE_RLE_GREY:
  3570. use_rle = true;
  3571. case TGATools._TYPE_GREY:
  3572. use_grey = true;
  3573. break;
  3574. }
  3575. var pixel_data;
  3576. var numAlphaBits = header.flags & 0xf;
  3577. var pixel_size = header.pixel_size >> 3;
  3578. var pixel_total = header.width * header.height * pixel_size;
  3579. // Read palettes
  3580. var palettes;
  3581. if (use_pal) {
  3582. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3583. }
  3584. // Read LRE
  3585. if (use_rle) {
  3586. pixel_data = new Uint8Array(pixel_total);
  3587. var c, count, i;
  3588. var localOffset = 0;
  3589. var pixels = new Uint8Array(pixel_size);
  3590. while (offset < pixel_total && localOffset < pixel_total) {
  3591. c = data[offset++];
  3592. count = (c & 0x7f) + 1;
  3593. // RLE pixels
  3594. if (c & 0x80) {
  3595. // Bind pixel tmp array
  3596. for (i = 0; i < pixel_size; ++i) {
  3597. pixels[i] = data[offset++];
  3598. }
  3599. // Copy pixel array
  3600. for (i = 0; i < count; ++i) {
  3601. pixel_data.set(pixels, localOffset + i * pixel_size);
  3602. }
  3603. localOffset += pixel_size * count;
  3604. }
  3605. else {
  3606. count *= pixel_size;
  3607. for (i = 0; i < count; ++i) {
  3608. pixel_data[localOffset + i] = data[offset++];
  3609. }
  3610. localOffset += count;
  3611. }
  3612. }
  3613. }
  3614. else {
  3615. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3616. }
  3617. // Load to texture
  3618. var x_start, y_start, x_step, y_step, y_end, x_end;
  3619. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3620. default:
  3621. case TGATools._ORIGIN_UL:
  3622. x_start = 0;
  3623. x_step = 1;
  3624. x_end = header.width;
  3625. y_start = 0;
  3626. y_step = 1;
  3627. y_end = header.height;
  3628. break;
  3629. case TGATools._ORIGIN_BL:
  3630. x_start = 0;
  3631. x_step = 1;
  3632. x_end = header.width;
  3633. y_start = header.height - 1;
  3634. y_step = -1;
  3635. y_end = -1;
  3636. break;
  3637. case TGATools._ORIGIN_UR:
  3638. x_start = header.width - 1;
  3639. x_step = -1;
  3640. x_end = -1;
  3641. y_start = 0;
  3642. y_step = 1;
  3643. y_end = header.height;
  3644. break;
  3645. case TGATools._ORIGIN_BR:
  3646. x_start = header.width - 1;
  3647. x_step = -1;
  3648. x_end = -1;
  3649. y_start = header.height - 1;
  3650. y_step = -1;
  3651. y_end = -1;
  3652. break;
  3653. }
  3654. // Load the specify method
  3655. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3656. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3657. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3658. };
  3659. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3660. var image = pixel_data, colormap = palettes;
  3661. var width = header.width, height = header.height;
  3662. var color, i = 0, x, y;
  3663. var imageData = new Uint8Array(width * height * 4);
  3664. for (y = y_start; y !== y_end; y += y_step) {
  3665. for (x = x_start; x !== x_end; x += x_step, i++) {
  3666. color = image[i];
  3667. imageData[(x + width * y) * 4 + 3] = 255;
  3668. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3669. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3670. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3671. }
  3672. }
  3673. return imageData;
  3674. };
  3675. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3676. var image = pixel_data;
  3677. var width = header.width, height = header.height;
  3678. var color, i = 0, x, y;
  3679. var imageData = new Uint8Array(width * height * 4);
  3680. for (y = y_start; y !== y_end; y += y_step) {
  3681. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3682. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3683. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3684. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3685. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3686. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3687. }
  3688. }
  3689. return imageData;
  3690. };
  3691. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3692. var image = pixel_data;
  3693. var width = header.width, height = header.height;
  3694. var i = 0, x, y;
  3695. var imageData = new Uint8Array(width * height * 4);
  3696. for (y = y_start; y !== y_end; y += y_step) {
  3697. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3698. imageData[(x + width * y) * 4 + 3] = 255;
  3699. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3700. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3701. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3702. }
  3703. }
  3704. return imageData;
  3705. };
  3706. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3707. var image = pixel_data;
  3708. var width = header.width, height = header.height;
  3709. var i = 0, x, y;
  3710. var imageData = new Uint8Array(width * height * 4);
  3711. for (y = y_start; y !== y_end; y += y_step) {
  3712. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3713. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3714. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3715. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3716. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3717. }
  3718. }
  3719. return imageData;
  3720. };
  3721. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3722. var image = pixel_data;
  3723. var width = header.width, height = header.height;
  3724. var color, i = 0, x, y;
  3725. var imageData = new Uint8Array(width * height * 4);
  3726. for (y = y_start; y !== y_end; y += y_step) {
  3727. for (x = x_start; x !== x_end; x += x_step, i++) {
  3728. color = image[i];
  3729. imageData[(x + width * y) * 4 + 0] = color;
  3730. imageData[(x + width * y) * 4 + 1] = color;
  3731. imageData[(x + width * y) * 4 + 2] = color;
  3732. imageData[(x + width * y) * 4 + 3] = 255;
  3733. }
  3734. }
  3735. return imageData;
  3736. };
  3737. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3738. var image = pixel_data;
  3739. var width = header.width, height = header.height;
  3740. var i = 0, x, y;
  3741. var imageData = new Uint8Array(width * height * 4);
  3742. for (y = y_start; y !== y_end; y += y_step) {
  3743. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3744. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3745. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3746. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3747. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3748. }
  3749. }
  3750. return imageData;
  3751. };
  3752. TGATools._TYPE_NO_DATA = 0;
  3753. TGATools._TYPE_INDEXED = 1;
  3754. TGATools._TYPE_RGB = 2;
  3755. TGATools._TYPE_GREY = 3;
  3756. TGATools._TYPE_RLE_INDEXED = 9;
  3757. TGATools._TYPE_RLE_RGB = 10;
  3758. TGATools._TYPE_RLE_GREY = 11;
  3759. TGATools._ORIGIN_MASK = 0x30;
  3760. TGATools._ORIGIN_SHIFT = 0x04;
  3761. TGATools._ORIGIN_BL = 0x00;
  3762. TGATools._ORIGIN_BR = 0x01;
  3763. TGATools._ORIGIN_UL = 0x02;
  3764. TGATools._ORIGIN_UR = 0x03;
  3765. return TGATools;
  3766. })();
  3767. Internals.TGATools = TGATools;
  3768. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3769. })(BABYLON || (BABYLON = {}));
  3770. //# sourceMappingURL=babylon.tools.tga.js.map
  3771. var BABYLON;
  3772. (function (BABYLON) {
  3773. var Internals;
  3774. (function (Internals) {
  3775. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3776. // All values and structures referenced from:
  3777. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3778. var DDS_MAGIC = 0x20534444;
  3779. 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;
  3780. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3781. 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;
  3782. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3783. function FourCCToInt32(value) {
  3784. return value.charCodeAt(0) +
  3785. (value.charCodeAt(1) << 8) +
  3786. (value.charCodeAt(2) << 16) +
  3787. (value.charCodeAt(3) << 24);
  3788. }
  3789. function Int32ToFourCC(value) {
  3790. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3791. }
  3792. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3793. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3794. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3795. var headerLengthInt = 31; // The header length in 32 bit ints
  3796. // Offsets into the header array
  3797. var off_magic = 0;
  3798. var off_size = 1;
  3799. var off_flags = 2;
  3800. var off_height = 3;
  3801. var off_width = 4;
  3802. var off_mipmapCount = 7;
  3803. var off_pfFlags = 20;
  3804. var off_pfFourCC = 21;
  3805. var off_RGBbpp = 22;
  3806. var off_RMask = 23;
  3807. var off_GMask = 24;
  3808. var off_BMask = 25;
  3809. var off_AMask = 26;
  3810. var off_caps1 = 27;
  3811. var off_caps2 = 28;
  3812. ;
  3813. var DDSTools = (function () {
  3814. function DDSTools() {
  3815. }
  3816. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3817. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3818. var mipmapCount = 1;
  3819. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3820. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3821. }
  3822. return {
  3823. width: header[off_width],
  3824. height: header[off_height],
  3825. mipmapCount: mipmapCount,
  3826. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3827. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3828. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3829. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3830. };
  3831. };
  3832. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3833. var byteArray = new Uint8Array(dataLength);
  3834. var srcData = new Uint8Array(arrayBuffer);
  3835. var index = 0;
  3836. for (var y = height - 1; y >= 0; y--) {
  3837. for (var x = 0; x < width; x++) {
  3838. var srcPos = dataOffset + (x + y * width) * 4;
  3839. byteArray[index + 2] = srcData[srcPos];
  3840. byteArray[index + 1] = srcData[srcPos + 1];
  3841. byteArray[index] = srcData[srcPos + 2];
  3842. byteArray[index + 3] = srcData[srcPos + 3];
  3843. index += 4;
  3844. }
  3845. }
  3846. return byteArray;
  3847. };
  3848. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3849. var byteArray = new Uint8Array(dataLength);
  3850. var srcData = new Uint8Array(arrayBuffer);
  3851. var index = 0;
  3852. for (var y = height - 1; y >= 0; y--) {
  3853. for (var x = 0; x < width; x++) {
  3854. var srcPos = dataOffset + (x + y * width) * 3;
  3855. byteArray[index + 2] = srcData[srcPos];
  3856. byteArray[index + 1] = srcData[srcPos + 1];
  3857. byteArray[index] = srcData[srcPos + 2];
  3858. index += 3;
  3859. }
  3860. }
  3861. return byteArray;
  3862. };
  3863. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3864. var byteArray = new Uint8Array(dataLength);
  3865. var srcData = new Uint8Array(arrayBuffer);
  3866. var index = 0;
  3867. for (var y = height - 1; y >= 0; y--) {
  3868. for (var x = 0; x < width; x++) {
  3869. var srcPos = dataOffset + (x + y * width);
  3870. byteArray[index] = srcData[srcPos];
  3871. index++;
  3872. }
  3873. }
  3874. return byteArray;
  3875. };
  3876. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3877. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3878. if (header[off_magic] != DDS_MAGIC) {
  3879. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3880. return;
  3881. }
  3882. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3883. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3884. return;
  3885. }
  3886. if (info.isFourCC) {
  3887. fourCC = header[off_pfFourCC];
  3888. switch (fourCC) {
  3889. case FOURCC_DXT1:
  3890. blockBytes = 8;
  3891. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3892. break;
  3893. case FOURCC_DXT3:
  3894. blockBytes = 16;
  3895. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3896. break;
  3897. case FOURCC_DXT5:
  3898. blockBytes = 16;
  3899. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3900. break;
  3901. default:
  3902. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3903. return;
  3904. }
  3905. }
  3906. mipmapCount = 1;
  3907. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3908. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3909. }
  3910. var bpp = header[off_RGBbpp];
  3911. for (var face = 0; face < faces; face++) {
  3912. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3913. width = header[off_width];
  3914. height = header[off_height];
  3915. dataOffset = header[off_size] + 4;
  3916. for (i = 0; i < mipmapCount; ++i) {
  3917. if (info.isRGB) {
  3918. if (bpp == 24) {
  3919. dataLength = width * height * 3;
  3920. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3921. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3922. }
  3923. else {
  3924. dataLength = width * height * 4;
  3925. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3926. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3927. }
  3928. }
  3929. else if (info.isLuminance) {
  3930. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3931. var unpaddedRowSize = width;
  3932. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3933. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3934. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3935. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3936. }
  3937. else {
  3938. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3939. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3940. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3941. }
  3942. dataOffset += dataLength;
  3943. width *= 0.5;
  3944. height *= 0.5;
  3945. width = Math.max(1.0, width);
  3946. height = Math.max(1.0, height);
  3947. }
  3948. }
  3949. };
  3950. return DDSTools;
  3951. })();
  3952. Internals.DDSTools = DDSTools;
  3953. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3954. })(BABYLON || (BABYLON = {}));
  3955. //# sourceMappingURL=babylon.tools.dds.js.map
  3956. var BABYLON;
  3957. (function (BABYLON) {
  3958. var SmartArray = (function () {
  3959. function SmartArray(capacity) {
  3960. this.length = 0;
  3961. this._duplicateId = 0;
  3962. this.data = new Array(capacity);
  3963. this._id = SmartArray._GlobalId++;
  3964. }
  3965. SmartArray.prototype.push = function (value) {
  3966. this.data[this.length++] = value;
  3967. if (this.length > this.data.length) {
  3968. this.data.length *= 2;
  3969. }
  3970. if (!value.__smartArrayFlags) {
  3971. value.__smartArrayFlags = {};
  3972. }
  3973. value.__smartArrayFlags[this._id] = this._duplicateId;
  3974. };
  3975. SmartArray.prototype.pushNoDuplicate = function (value) {
  3976. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3977. return;
  3978. }
  3979. this.push(value);
  3980. };
  3981. SmartArray.prototype.sort = function (compareFn) {
  3982. this.data.sort(compareFn);
  3983. };
  3984. SmartArray.prototype.reset = function () {
  3985. this.length = 0;
  3986. this._duplicateId++;
  3987. };
  3988. SmartArray.prototype.concat = function (array) {
  3989. if (array.length === 0) {
  3990. return;
  3991. }
  3992. if (this.length + array.length > this.data.length) {
  3993. this.data.length = (this.length + array.length) * 2;
  3994. }
  3995. for (var index = 0; index < array.length; index++) {
  3996. this.data[this.length++] = (array.data || array)[index];
  3997. }
  3998. };
  3999. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4000. if (array.length === 0) {
  4001. return;
  4002. }
  4003. if (this.length + array.length > this.data.length) {
  4004. this.data.length = (this.length + array.length) * 2;
  4005. }
  4006. for (var index = 0; index < array.length; index++) {
  4007. var item = (array.data || array)[index];
  4008. this.pushNoDuplicate(item);
  4009. }
  4010. };
  4011. SmartArray.prototype.indexOf = function (value) {
  4012. var position = this.data.indexOf(value);
  4013. if (position >= this.length) {
  4014. return -1;
  4015. }
  4016. return position;
  4017. };
  4018. // Statics
  4019. SmartArray._GlobalId = 0;
  4020. return SmartArray;
  4021. })();
  4022. BABYLON.SmartArray = SmartArray;
  4023. })(BABYLON || (BABYLON = {}));
  4024. //# sourceMappingURL=babylon.smartArray.js.map
  4025. var BABYLON;
  4026. (function (BABYLON) {
  4027. var SmartCollection = (function () {
  4028. function SmartCollection(capacity) {
  4029. if (capacity === void 0) { capacity = 10; }
  4030. this.count = 0;
  4031. this._initialCapacity = capacity;
  4032. this.items = {};
  4033. this._keys = new Array(this._initialCapacity);
  4034. }
  4035. SmartCollection.prototype.add = function (key, item) {
  4036. if (this.items[key] != undefined) {
  4037. return -1;
  4038. }
  4039. this.items[key] = item;
  4040. //literal keys are always strings, but we keep source type of key in _keys array
  4041. this._keys[this.count++] = key;
  4042. if (this.count > this._keys.length) {
  4043. this._keys.length *= 2;
  4044. }
  4045. return this.count;
  4046. };
  4047. SmartCollection.prototype.remove = function (key) {
  4048. if (this.items[key] == undefined) {
  4049. return -1;
  4050. }
  4051. return this.removeItemOfIndex(this.indexOf(key));
  4052. };
  4053. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4054. if (index < this.count && index > -1) {
  4055. delete this.items[this._keys[index]];
  4056. //here, shifting by hand is better optimised than .splice
  4057. while (index < this.count) {
  4058. this._keys[index] = this._keys[index + 1];
  4059. index++;
  4060. }
  4061. }
  4062. else {
  4063. return -1;
  4064. }
  4065. return --this.count;
  4066. };
  4067. SmartCollection.prototype.indexOf = function (key) {
  4068. for (var i = 0; i !== this.count; i++) {
  4069. if (this._keys[i] === key) {
  4070. return i;
  4071. }
  4072. }
  4073. return -1;
  4074. };
  4075. SmartCollection.prototype.item = function (key) {
  4076. return this.items[key];
  4077. };
  4078. SmartCollection.prototype.getAllKeys = function () {
  4079. if (this.count > 0) {
  4080. var keys = new Array(this.count);
  4081. for (var i = 0; i < this.count; i++) {
  4082. keys[i] = this._keys[i];
  4083. }
  4084. return keys;
  4085. }
  4086. else {
  4087. return undefined;
  4088. }
  4089. };
  4090. SmartCollection.prototype.getKeyByIndex = function (index) {
  4091. if (index < this.count && index > -1) {
  4092. return this._keys[index];
  4093. }
  4094. else {
  4095. return undefined;
  4096. }
  4097. };
  4098. SmartCollection.prototype.getItemByIndex = function (index) {
  4099. if (index < this.count && index > -1) {
  4100. return this.items[this._keys[index]];
  4101. }
  4102. else {
  4103. return undefined;
  4104. }
  4105. };
  4106. SmartCollection.prototype.empty = function () {
  4107. if (this.count > 0) {
  4108. this.count = 0;
  4109. this.items = {};
  4110. this._keys = new Array(this._initialCapacity);
  4111. }
  4112. };
  4113. SmartCollection.prototype.forEach = function (block) {
  4114. var key;
  4115. for (key in this.items) {
  4116. if (this.items.hasOwnProperty(key)) {
  4117. block(this.items[key]);
  4118. }
  4119. }
  4120. };
  4121. return SmartCollection;
  4122. })();
  4123. BABYLON.SmartCollection = SmartCollection;
  4124. })(BABYLON || (BABYLON = {}));
  4125. //# sourceMappingURL=babylon.smartCollection.js.map
  4126. var BABYLON;
  4127. (function (BABYLON) {
  4128. // Screenshots
  4129. var screenshotCanvas;
  4130. var cloneValue = function (source, destinationObject) {
  4131. if (!source)
  4132. return null;
  4133. if (source instanceof BABYLON.Mesh) {
  4134. return null;
  4135. }
  4136. if (source instanceof BABYLON.SubMesh) {
  4137. return source.clone(destinationObject);
  4138. }
  4139. else if (source.clone) {
  4140. return source.clone();
  4141. }
  4142. return null;
  4143. };
  4144. var Tools = (function () {
  4145. function Tools() {
  4146. }
  4147. Tools.SetImmediate = function (action) {
  4148. if (window.setImmediate) {
  4149. window.setImmediate(action);
  4150. }
  4151. else {
  4152. setTimeout(action, 1);
  4153. }
  4154. };
  4155. Tools.IsExponantOfTwo = function (value) {
  4156. var count = 1;
  4157. do {
  4158. count *= 2;
  4159. } while (count < value);
  4160. return count === value;
  4161. };
  4162. Tools.GetExponantOfTwo = function (value, max) {
  4163. var count = 1;
  4164. do {
  4165. count *= 2;
  4166. } while (count < value);
  4167. if (count > max)
  4168. count = max;
  4169. return count;
  4170. };
  4171. Tools.GetFilename = function (path) {
  4172. var index = path.lastIndexOf("/");
  4173. if (index < 0)
  4174. return path;
  4175. return path.substring(index + 1);
  4176. };
  4177. Tools.GetDOMTextContent = function (element) {
  4178. var result = "";
  4179. var child = element.firstChild;
  4180. while (child) {
  4181. if (child.nodeType === 3) {
  4182. result += child.textContent;
  4183. }
  4184. child = child.nextSibling;
  4185. }
  4186. return result;
  4187. };
  4188. Tools.ToDegrees = function (angle) {
  4189. return angle * 180 / Math.PI;
  4190. };
  4191. Tools.ToRadians = function (angle) {
  4192. return angle * Math.PI / 180;
  4193. };
  4194. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4195. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4196. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4197. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4198. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4199. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4200. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4201. }
  4202. return {
  4203. minimum: minimum,
  4204. maximum: maximum
  4205. };
  4206. };
  4207. Tools.ExtractMinAndMax = function (positions, start, count) {
  4208. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4209. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4210. for (var index = start; index < start + count; index++) {
  4211. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4212. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4213. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4214. }
  4215. return {
  4216. minimum: minimum,
  4217. maximum: maximum
  4218. };
  4219. };
  4220. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4221. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4222. return undefined;
  4223. return Array.isArray(obj) ? obj : [obj];
  4224. };
  4225. // Misc.
  4226. Tools.GetPointerPrefix = function () {
  4227. var eventPrefix = "pointer";
  4228. // Check if hand.js is referenced or if the browser natively supports pointer events
  4229. if (!navigator.pointerEnabled) {
  4230. eventPrefix = "mouse";
  4231. }
  4232. return eventPrefix;
  4233. };
  4234. Tools.QueueNewFrame = function (func) {
  4235. if (window.requestAnimationFrame)
  4236. window.requestAnimationFrame(func);
  4237. else if (window.msRequestAnimationFrame)
  4238. window.msRequestAnimationFrame(func);
  4239. else if (window.webkitRequestAnimationFrame)
  4240. window.webkitRequestAnimationFrame(func);
  4241. else if (window.mozRequestAnimationFrame)
  4242. window.mozRequestAnimationFrame(func);
  4243. else if (window.oRequestAnimationFrame)
  4244. window.oRequestAnimationFrame(func);
  4245. else {
  4246. window.setTimeout(func, 16);
  4247. }
  4248. };
  4249. Tools.RequestFullscreen = function (element) {
  4250. if (element.requestFullscreen)
  4251. element.requestFullscreen();
  4252. else if (element.msRequestFullscreen)
  4253. element.msRequestFullscreen();
  4254. else if (element.webkitRequestFullscreen)
  4255. element.webkitRequestFullscreen();
  4256. else if (element.mozRequestFullScreen)
  4257. element.mozRequestFullScreen();
  4258. };
  4259. Tools.ExitFullscreen = function () {
  4260. if (document.exitFullscreen) {
  4261. document.exitFullscreen();
  4262. }
  4263. else if (document.mozCancelFullScreen) {
  4264. document.mozCancelFullScreen();
  4265. }
  4266. else if (document.webkitCancelFullScreen) {
  4267. document.webkitCancelFullScreen();
  4268. }
  4269. else if (document.msCancelFullScreen) {
  4270. document.msCancelFullScreen();
  4271. }
  4272. };
  4273. // External files
  4274. Tools.CleanUrl = function (url) {
  4275. url = url.replace(/#/mg, "%23");
  4276. return url;
  4277. };
  4278. Tools.LoadImage = function (url, onload, onerror, database) {
  4279. url = Tools.CleanUrl(url);
  4280. var img = new Image();
  4281. if (url.substr(0, 5) !== "data:")
  4282. img.crossOrigin = 'anonymous';
  4283. img.onload = function () {
  4284. onload(img);
  4285. };
  4286. img.onerror = function (err) {
  4287. onerror(img, err);
  4288. };
  4289. var noIndexedDB = function () {
  4290. img.src = url;
  4291. };
  4292. var loadFromIndexedDB = function () {
  4293. database.loadImageFromDB(url, img);
  4294. };
  4295. //ANY database to do!
  4296. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4297. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4298. }
  4299. else {
  4300. if (url.indexOf("file:") === -1) {
  4301. noIndexedDB();
  4302. }
  4303. else {
  4304. try {
  4305. var textureName = url.substring(5);
  4306. var blobURL;
  4307. try {
  4308. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4309. }
  4310. catch (ex) {
  4311. // Chrome doesn't support oneTimeOnly parameter
  4312. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4313. }
  4314. img.src = blobURL;
  4315. }
  4316. catch (e) {
  4317. Tools.Log("Error while trying to load texture: " + textureName);
  4318. img.src = null;
  4319. }
  4320. }
  4321. }
  4322. return img;
  4323. };
  4324. //ANY
  4325. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4326. url = Tools.CleanUrl(url);
  4327. var noIndexedDB = function () {
  4328. var request = new XMLHttpRequest();
  4329. var loadUrl = Tools.BaseUrl + url;
  4330. request.open('GET', loadUrl, true);
  4331. if (useArrayBuffer) {
  4332. request.responseType = "arraybuffer";
  4333. }
  4334. request.onprogress = progressCallBack;
  4335. request.onreadystatechange = function () {
  4336. if (request.readyState === 4) {
  4337. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4338. callback(!useArrayBuffer ? request.responseText : request.response);
  4339. }
  4340. else {
  4341. if (onError) {
  4342. onError();
  4343. }
  4344. else {
  4345. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4346. }
  4347. }
  4348. }
  4349. };
  4350. request.send(null);
  4351. };
  4352. var loadFromIndexedDB = function () {
  4353. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4354. };
  4355. if (url.indexOf("file:") !== -1) {
  4356. var fileName = url.substring(5);
  4357. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4358. }
  4359. else {
  4360. // Caching all files
  4361. if (database && database.enableSceneOffline) {
  4362. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4363. }
  4364. else {
  4365. noIndexedDB();
  4366. }
  4367. }
  4368. };
  4369. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4370. var reader = new FileReader();
  4371. reader.onload = function (e) {
  4372. //target doesn't have result from ts 1.3
  4373. callback(e.target['result']);
  4374. };
  4375. reader.onprogress = progressCallback;
  4376. reader.readAsDataURL(fileToLoad);
  4377. };
  4378. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4379. var reader = new FileReader();
  4380. reader.onerror = function (e) {
  4381. Tools.Log("Error while reading file: " + fileToLoad.name);
  4382. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4383. };
  4384. reader.onload = function (e) {
  4385. //target doesn't have result from ts 1.3
  4386. callback(e.target['result']);
  4387. };
  4388. reader.onprogress = progressCallBack;
  4389. if (!useArrayBuffer) {
  4390. // Asynchronous read
  4391. reader.readAsText(fileToLoad);
  4392. }
  4393. else {
  4394. reader.readAsArrayBuffer(fileToLoad);
  4395. }
  4396. };
  4397. // Misc.
  4398. Tools.Clamp = function (value, min, max) {
  4399. if (min === void 0) { min = 0; }
  4400. if (max === void 0) { max = 1; }
  4401. return Math.min(max, Math.max(min, value));
  4402. };
  4403. // Returns -1 when value is a negative number and
  4404. // +1 when value is a positive number.
  4405. Tools.Sign = function (value) {
  4406. value = +value; // convert to a number
  4407. if (value === 0 || isNaN(value))
  4408. return value;
  4409. return value > 0 ? 1 : -1;
  4410. };
  4411. Tools.Format = function (value, decimals) {
  4412. if (decimals === void 0) { decimals = 2; }
  4413. return value.toFixed(decimals);
  4414. };
  4415. Tools.CheckExtends = function (v, min, max) {
  4416. if (v.x < min.x)
  4417. min.x = v.x;
  4418. if (v.y < min.y)
  4419. min.y = v.y;
  4420. if (v.z < min.z)
  4421. min.z = v.z;
  4422. if (v.x > max.x)
  4423. max.x = v.x;
  4424. if (v.y > max.y)
  4425. max.y = v.y;
  4426. if (v.z > max.z)
  4427. max.z = v.z;
  4428. };
  4429. Tools.WithinEpsilon = function (a, b, epsilon) {
  4430. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4431. var num = a - b;
  4432. return -epsilon <= num && num <= epsilon;
  4433. };
  4434. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4435. for (var prop in source) {
  4436. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4437. continue;
  4438. }
  4439. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4440. continue;
  4441. }
  4442. var sourceValue = source[prop];
  4443. var typeOfSourceValue = typeof sourceValue;
  4444. if (typeOfSourceValue === "function") {
  4445. continue;
  4446. }
  4447. if (typeOfSourceValue === "object") {
  4448. if (sourceValue instanceof Array) {
  4449. destination[prop] = [];
  4450. if (sourceValue.length > 0) {
  4451. if (typeof sourceValue[0] == "object") {
  4452. for (var index = 0; index < sourceValue.length; index++) {
  4453. var clonedValue = cloneValue(sourceValue[index], destination);
  4454. if (destination[prop].indexOf(clonedValue) === -1) {
  4455. destination[prop].push(clonedValue);
  4456. }
  4457. }
  4458. }
  4459. else {
  4460. destination[prop] = sourceValue.slice(0);
  4461. }
  4462. }
  4463. }
  4464. else {
  4465. destination[prop] = cloneValue(sourceValue, destination);
  4466. }
  4467. }
  4468. else {
  4469. destination[prop] = sourceValue;
  4470. }
  4471. }
  4472. };
  4473. Tools.IsEmpty = function (obj) {
  4474. for (var i in obj) {
  4475. return false;
  4476. }
  4477. return true;
  4478. };
  4479. Tools.RegisterTopRootEvents = function (events) {
  4480. for (var index = 0; index < events.length; index++) {
  4481. var event = events[index];
  4482. window.addEventListener(event.name, event.handler, false);
  4483. try {
  4484. if (window.parent) {
  4485. window.parent.addEventListener(event.name, event.handler, false);
  4486. }
  4487. }
  4488. catch (e) {
  4489. }
  4490. }
  4491. };
  4492. Tools.UnregisterTopRootEvents = function (events) {
  4493. for (var index = 0; index < events.length; index++) {
  4494. var event = events[index];
  4495. window.removeEventListener(event.name, event.handler);
  4496. try {
  4497. if (window.parent) {
  4498. window.parent.removeEventListener(event.name, event.handler);
  4499. }
  4500. }
  4501. catch (e) {
  4502. }
  4503. }
  4504. };
  4505. Tools.DumpFramebuffer = function (width, height, engine) {
  4506. // Read the contents of the framebuffer
  4507. var numberOfChannelsByLine = width * 4;
  4508. var halfHeight = height / 2;
  4509. //Reading datas from WebGL
  4510. var data = engine.readPixels(0, 0, width, height);
  4511. //To flip image on Y axis.
  4512. for (var i = 0; i < halfHeight; i++) {
  4513. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4514. var currentCell = j + i * numberOfChannelsByLine;
  4515. var targetLine = height - i - 1;
  4516. var targetCell = j + targetLine * numberOfChannelsByLine;
  4517. var temp = data[currentCell];
  4518. data[currentCell] = data[targetCell];
  4519. data[targetCell] = temp;
  4520. }
  4521. }
  4522. // Create a 2D canvas to store the result
  4523. if (!screenshotCanvas) {
  4524. screenshotCanvas = document.createElement('canvas');
  4525. }
  4526. screenshotCanvas.width = width;
  4527. screenshotCanvas.height = height;
  4528. var context = screenshotCanvas.getContext('2d');
  4529. // Copy the pixels to a 2D canvas
  4530. var imageData = context.createImageData(width, height);
  4531. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4532. var castData = imageData.data;
  4533. castData.set(data);
  4534. context.putImageData(imageData, 0, 0);
  4535. var base64Image = screenshotCanvas.toDataURL();
  4536. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4537. if (("download" in document.createElement("a"))) {
  4538. var a = window.document.createElement("a");
  4539. a.href = base64Image;
  4540. var date = new Date();
  4541. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4542. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4543. window.document.body.appendChild(a);
  4544. a.addEventListener("click", function () {
  4545. a.parentElement.removeChild(a);
  4546. });
  4547. a.click();
  4548. }
  4549. else {
  4550. var newWindow = window.open("");
  4551. var img = newWindow.document.createElement("img");
  4552. img.src = base64Image;
  4553. newWindow.document.body.appendChild(img);
  4554. }
  4555. };
  4556. Tools.CreateScreenshot = function (engine, camera, size) {
  4557. var width;
  4558. var height;
  4559. var scene = camera.getScene();
  4560. var previousCamera = null;
  4561. if (scene.activeCamera !== camera) {
  4562. previousCamera = scene.activeCamera;
  4563. scene.activeCamera = camera;
  4564. }
  4565. //If a precision value is specified
  4566. if (size.precision) {
  4567. width = Math.round(engine.getRenderWidth() * size.precision);
  4568. height = Math.round(width / engine.getAspectRatio(camera));
  4569. size = { width: width, height: height };
  4570. }
  4571. else if (size.width && size.height) {
  4572. width = size.width;
  4573. height = size.height;
  4574. }
  4575. else if (size.width && !size.height) {
  4576. width = size.width;
  4577. height = Math.round(width / engine.getAspectRatio(camera));
  4578. size = { width: width, height: height };
  4579. }
  4580. else if (size.height && !size.width) {
  4581. height = size.height;
  4582. width = Math.round(height * engine.getAspectRatio(camera));
  4583. size = { width: width, height: height };
  4584. }
  4585. else if (!isNaN(size)) {
  4586. height = size;
  4587. width = size;
  4588. }
  4589. else {
  4590. Tools.Error("Invalid 'size' parameter !");
  4591. return;
  4592. }
  4593. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4594. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4595. texture.renderList = scene.meshes;
  4596. texture.onAfterRender = function () {
  4597. Tools.DumpFramebuffer(width, height, engine);
  4598. };
  4599. scene.incrementRenderId();
  4600. texture.render(true);
  4601. texture.dispose();
  4602. if (previousCamera) {
  4603. scene.activeCamera = previousCamera;
  4604. }
  4605. };
  4606. // XHR response validator for local file scenario
  4607. Tools.ValidateXHRData = function (xhr, dataType) {
  4608. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4609. if (dataType === void 0) { dataType = 7; }
  4610. try {
  4611. if (dataType & 1) {
  4612. if (xhr.responseText && xhr.responseText.length > 0) {
  4613. return true;
  4614. }
  4615. else if (dataType === 1) {
  4616. return false;
  4617. }
  4618. }
  4619. if (dataType & 2) {
  4620. // Check header width and height since there is no "TGA" magic number
  4621. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4622. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4623. return true;
  4624. }
  4625. else if (dataType === 2) {
  4626. return false;
  4627. }
  4628. }
  4629. if (dataType & 4) {
  4630. // Check for the "DDS" magic number
  4631. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4632. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4633. return true;
  4634. }
  4635. else {
  4636. return false;
  4637. }
  4638. }
  4639. }
  4640. catch (e) {
  4641. }
  4642. return false;
  4643. };
  4644. Object.defineProperty(Tools, "NoneLogLevel", {
  4645. get: function () {
  4646. return Tools._NoneLogLevel;
  4647. },
  4648. enumerable: true,
  4649. configurable: true
  4650. });
  4651. Object.defineProperty(Tools, "MessageLogLevel", {
  4652. get: function () {
  4653. return Tools._MessageLogLevel;
  4654. },
  4655. enumerable: true,
  4656. configurable: true
  4657. });
  4658. Object.defineProperty(Tools, "WarningLogLevel", {
  4659. get: function () {
  4660. return Tools._WarningLogLevel;
  4661. },
  4662. enumerable: true,
  4663. configurable: true
  4664. });
  4665. Object.defineProperty(Tools, "ErrorLogLevel", {
  4666. get: function () {
  4667. return Tools._ErrorLogLevel;
  4668. },
  4669. enumerable: true,
  4670. configurable: true
  4671. });
  4672. Object.defineProperty(Tools, "AllLogLevel", {
  4673. get: function () {
  4674. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4675. },
  4676. enumerable: true,
  4677. configurable: true
  4678. });
  4679. Tools._AddLogEntry = function (entry) {
  4680. Tools._LogCache = entry + Tools._LogCache;
  4681. if (Tools.OnNewCacheEntry) {
  4682. Tools.OnNewCacheEntry(entry);
  4683. }
  4684. };
  4685. Tools._FormatMessage = function (message) {
  4686. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4687. var date = new Date();
  4688. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4689. };
  4690. Tools._LogDisabled = function (message) {
  4691. // nothing to do
  4692. };
  4693. Tools._LogEnabled = function (message) {
  4694. var formattedMessage = Tools._FormatMessage(message);
  4695. console.log("BJS - " + formattedMessage);
  4696. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4697. Tools._AddLogEntry(entry);
  4698. };
  4699. Tools._WarnDisabled = function (message) {
  4700. // nothing to do
  4701. };
  4702. Tools._WarnEnabled = function (message) {
  4703. var formattedMessage = Tools._FormatMessage(message);
  4704. console.warn("BJS - " + formattedMessage);
  4705. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4706. Tools._AddLogEntry(entry);
  4707. };
  4708. Tools._ErrorDisabled = function (message) {
  4709. // nothing to do
  4710. };
  4711. Tools._ErrorEnabled = function (message) {
  4712. var formattedMessage = Tools._FormatMessage(message);
  4713. console.error("BJS - " + formattedMessage);
  4714. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4715. Tools._AddLogEntry(entry);
  4716. };
  4717. Object.defineProperty(Tools, "LogCache", {
  4718. get: function () {
  4719. return Tools._LogCache;
  4720. },
  4721. enumerable: true,
  4722. configurable: true
  4723. });
  4724. Object.defineProperty(Tools, "LogLevels", {
  4725. set: function (level) {
  4726. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4727. Tools.Log = Tools._LogEnabled;
  4728. }
  4729. else {
  4730. Tools.Log = Tools._LogDisabled;
  4731. }
  4732. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4733. Tools.Warn = Tools._WarnEnabled;
  4734. }
  4735. else {
  4736. Tools.Warn = Tools._WarnDisabled;
  4737. }
  4738. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4739. Tools.Error = Tools._ErrorEnabled;
  4740. }
  4741. else {
  4742. Tools.Error = Tools._ErrorDisabled;
  4743. }
  4744. },
  4745. enumerable: true,
  4746. configurable: true
  4747. });
  4748. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4749. get: function () {
  4750. return Tools._PerformanceNoneLogLevel;
  4751. },
  4752. enumerable: true,
  4753. configurable: true
  4754. });
  4755. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4756. get: function () {
  4757. return Tools._PerformanceUserMarkLogLevel;
  4758. },
  4759. enumerable: true,
  4760. configurable: true
  4761. });
  4762. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4763. get: function () {
  4764. return Tools._PerformanceConsoleLogLevel;
  4765. },
  4766. enumerable: true,
  4767. configurable: true
  4768. });
  4769. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4770. set: function (level) {
  4771. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4772. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4773. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4774. return;
  4775. }
  4776. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4777. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4778. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4779. return;
  4780. }
  4781. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4782. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4783. },
  4784. enumerable: true,
  4785. configurable: true
  4786. });
  4787. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4788. };
  4789. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4790. };
  4791. Tools._StartUserMark = function (counterName, condition) {
  4792. if (condition === void 0) { condition = true; }
  4793. if (!condition || !Tools._performance.mark) {
  4794. return;
  4795. }
  4796. Tools._performance.mark(counterName + "-Begin");
  4797. };
  4798. Tools._EndUserMark = function (counterName, condition) {
  4799. if (condition === void 0) { condition = true; }
  4800. if (!condition || !Tools._performance.mark) {
  4801. return;
  4802. }
  4803. Tools._performance.mark(counterName + "-End");
  4804. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4805. };
  4806. Tools._StartPerformanceConsole = function (counterName, condition) {
  4807. if (condition === void 0) { condition = true; }
  4808. if (!condition) {
  4809. return;
  4810. }
  4811. Tools._StartUserMark(counterName, condition);
  4812. if (console.time) {
  4813. console.time(counterName);
  4814. }
  4815. };
  4816. Tools._EndPerformanceConsole = function (counterName, condition) {
  4817. if (condition === void 0) { condition = true; }
  4818. if (!condition) {
  4819. return;
  4820. }
  4821. Tools._EndUserMark(counterName, condition);
  4822. if (console.time) {
  4823. console.timeEnd(counterName);
  4824. }
  4825. };
  4826. Object.defineProperty(Tools, "Now", {
  4827. get: function () {
  4828. if (window.performance && window.performance.now) {
  4829. return window.performance.now();
  4830. }
  4831. return new Date().getTime();
  4832. },
  4833. enumerable: true,
  4834. configurable: true
  4835. });
  4836. // Deprecated
  4837. Tools.GetFps = function () {
  4838. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4839. return 0;
  4840. };
  4841. Tools.BaseUrl = "";
  4842. // Logs
  4843. Tools._NoneLogLevel = 0;
  4844. Tools._MessageLogLevel = 1;
  4845. Tools._WarningLogLevel = 2;
  4846. Tools._ErrorLogLevel = 4;
  4847. Tools._LogCache = "";
  4848. Tools.Log = Tools._LogEnabled;
  4849. Tools.Warn = Tools._WarnEnabled;
  4850. Tools.Error = Tools._ErrorEnabled;
  4851. // Performances
  4852. Tools._PerformanceNoneLogLevel = 0;
  4853. Tools._PerformanceUserMarkLogLevel = 1;
  4854. Tools._PerformanceConsoleLogLevel = 2;
  4855. Tools._performance = window.performance;
  4856. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4857. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4858. return Tools;
  4859. })();
  4860. BABYLON.Tools = Tools;
  4861. /**
  4862. * An implementation of a loop for asynchronous functions.
  4863. */
  4864. var AsyncLoop = (function () {
  4865. /**
  4866. * Constroctor.
  4867. * @param iterations the number of iterations.
  4868. * @param _fn the function to run each iteration
  4869. * @param _successCallback the callback that will be called upon succesful execution
  4870. * @param offset starting offset.
  4871. */
  4872. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4873. if (offset === void 0) { offset = 0; }
  4874. this.iterations = iterations;
  4875. this._fn = _fn;
  4876. this._successCallback = _successCallback;
  4877. this.index = offset - 1;
  4878. this._done = false;
  4879. }
  4880. /**
  4881. * Execute the next iteration. Must be called after the last iteration was finished.
  4882. */
  4883. AsyncLoop.prototype.executeNext = function () {
  4884. if (!this._done) {
  4885. if (this.index + 1 < this.iterations) {
  4886. ++this.index;
  4887. this._fn(this);
  4888. }
  4889. else {
  4890. this.breakLoop();
  4891. }
  4892. }
  4893. };
  4894. /**
  4895. * Break the loop and run the success callback.
  4896. */
  4897. AsyncLoop.prototype.breakLoop = function () {
  4898. this._done = true;
  4899. this._successCallback();
  4900. };
  4901. /**
  4902. * Helper function
  4903. */
  4904. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4905. if (offset === void 0) { offset = 0; }
  4906. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4907. loop.executeNext();
  4908. return loop;
  4909. };
  4910. /**
  4911. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4912. * @param iterations total number of iterations
  4913. * @param syncedIterations number of synchronous iterations in each async iteration.
  4914. * @param fn the function to call each iteration.
  4915. * @param callback a success call back that will be called when iterating stops.
  4916. * @param breakFunction a break condition (optional)
  4917. * @param timeout timeout settings for the setTimeout function. default - 0.
  4918. * @constructor
  4919. */
  4920. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4921. if (timeout === void 0) { timeout = 0; }
  4922. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4923. if (breakFunction && breakFunction())
  4924. loop.breakLoop();
  4925. else {
  4926. setTimeout(function () {
  4927. for (var i = 0; i < syncedIterations; ++i) {
  4928. var iteration = (loop.index * syncedIterations) + i;
  4929. if (iteration >= iterations)
  4930. break;
  4931. fn(iteration);
  4932. if (breakFunction && breakFunction()) {
  4933. loop.breakLoop();
  4934. break;
  4935. }
  4936. }
  4937. loop.executeNext();
  4938. }, timeout);
  4939. }
  4940. }, callback);
  4941. };
  4942. return AsyncLoop;
  4943. })();
  4944. BABYLON.AsyncLoop = AsyncLoop;
  4945. })(BABYLON || (BABYLON = {}));
  4946. //# sourceMappingURL=babylon.tools.js.map
  4947. var BABYLON;
  4948. (function (BABYLON) {
  4949. var _DepthCullingState = (function () {
  4950. function _DepthCullingState() {
  4951. this._isDepthTestDirty = false;
  4952. this._isDepthMaskDirty = false;
  4953. this._isDepthFuncDirty = false;
  4954. this._isCullFaceDirty = false;
  4955. this._isCullDirty = false;
  4956. this._isZOffsetDirty = false;
  4957. }
  4958. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4959. get: function () {
  4960. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4961. },
  4962. enumerable: true,
  4963. configurable: true
  4964. });
  4965. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4966. get: function () {
  4967. return this._zOffset;
  4968. },
  4969. set: function (value) {
  4970. if (this._zOffset === value) {
  4971. return;
  4972. }
  4973. this._zOffset = value;
  4974. this._isZOffsetDirty = true;
  4975. },
  4976. enumerable: true,
  4977. configurable: true
  4978. });
  4979. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4980. get: function () {
  4981. return this._cullFace;
  4982. },
  4983. set: function (value) {
  4984. if (this._cullFace === value) {
  4985. return;
  4986. }
  4987. this._cullFace = value;
  4988. this._isCullFaceDirty = true;
  4989. },
  4990. enumerable: true,
  4991. configurable: true
  4992. });
  4993. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4994. get: function () {
  4995. return this._cull;
  4996. },
  4997. set: function (value) {
  4998. if (this._cull === value) {
  4999. return;
  5000. }
  5001. this._cull = value;
  5002. this._isCullDirty = true;
  5003. },
  5004. enumerable: true,
  5005. configurable: true
  5006. });
  5007. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5008. get: function () {
  5009. return this._depthFunc;
  5010. },
  5011. set: function (value) {
  5012. if (this._depthFunc === value) {
  5013. return;
  5014. }
  5015. this._depthFunc = value;
  5016. this._isDepthFuncDirty = true;
  5017. },
  5018. enumerable: true,
  5019. configurable: true
  5020. });
  5021. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5022. get: function () {
  5023. return this._depthMask;
  5024. },
  5025. set: function (value) {
  5026. if (this._depthMask === value) {
  5027. return;
  5028. }
  5029. this._depthMask = value;
  5030. this._isDepthMaskDirty = true;
  5031. },
  5032. enumerable: true,
  5033. configurable: true
  5034. });
  5035. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5036. get: function () {
  5037. return this._depthTest;
  5038. },
  5039. set: function (value) {
  5040. if (this._depthTest === value) {
  5041. return;
  5042. }
  5043. this._depthTest = value;
  5044. this._isDepthTestDirty = true;
  5045. },
  5046. enumerable: true,
  5047. configurable: true
  5048. });
  5049. _DepthCullingState.prototype.reset = function () {
  5050. this._depthMask = true;
  5051. this._depthTest = true;
  5052. this._depthFunc = null;
  5053. this._cull = null;
  5054. this._cullFace = null;
  5055. this._zOffset = 0;
  5056. this._isDepthTestDirty = true;
  5057. this._isDepthMaskDirty = true;
  5058. this._isDepthFuncDirty = false;
  5059. this._isCullFaceDirty = false;
  5060. this._isCullDirty = false;
  5061. this._isZOffsetDirty = false;
  5062. };
  5063. _DepthCullingState.prototype.apply = function (gl) {
  5064. if (!this.isDirty) {
  5065. return;
  5066. }
  5067. // Cull
  5068. if (this._isCullDirty) {
  5069. if (this.cull) {
  5070. gl.enable(gl.CULL_FACE);
  5071. }
  5072. else {
  5073. gl.disable(gl.CULL_FACE);
  5074. }
  5075. this._isCullDirty = false;
  5076. }
  5077. // Cull face
  5078. if (this._isCullFaceDirty) {
  5079. gl.cullFace(this.cullFace);
  5080. this._isCullFaceDirty = false;
  5081. }
  5082. // Depth mask
  5083. if (this._isDepthMaskDirty) {
  5084. gl.depthMask(this.depthMask);
  5085. this._isDepthMaskDirty = false;
  5086. }
  5087. // Depth test
  5088. if (this._isDepthTestDirty) {
  5089. if (this.depthTest) {
  5090. gl.enable(gl.DEPTH_TEST);
  5091. }
  5092. else {
  5093. gl.disable(gl.DEPTH_TEST);
  5094. }
  5095. this._isDepthTestDirty = false;
  5096. }
  5097. // Depth func
  5098. if (this._isDepthFuncDirty) {
  5099. gl.depthFunc(this.depthFunc);
  5100. this._isDepthFuncDirty = false;
  5101. }
  5102. // zOffset
  5103. if (this._isZOffsetDirty) {
  5104. if (this.zOffset) {
  5105. gl.enable(gl.POLYGON_OFFSET_FILL);
  5106. gl.polygonOffset(this.zOffset, 0);
  5107. }
  5108. else {
  5109. gl.disable(gl.POLYGON_OFFSET_FILL);
  5110. }
  5111. this._isZOffsetDirty = false;
  5112. }
  5113. };
  5114. return _DepthCullingState;
  5115. })();
  5116. BABYLON._DepthCullingState = _DepthCullingState;
  5117. var _AlphaState = (function () {
  5118. function _AlphaState() {
  5119. this._isAlphaBlendDirty = false;
  5120. this._isBlendFunctionParametersDirty = false;
  5121. this._alphaBlend = false;
  5122. this._blendFunctionParameters = new Array(4);
  5123. }
  5124. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5125. get: function () {
  5126. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5127. },
  5128. enumerable: true,
  5129. configurable: true
  5130. });
  5131. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5132. get: function () {
  5133. return this._alphaBlend;
  5134. },
  5135. set: function (value) {
  5136. if (this._alphaBlend === value) {
  5137. return;
  5138. }
  5139. this._alphaBlend = value;
  5140. this._isAlphaBlendDirty = true;
  5141. },
  5142. enumerable: true,
  5143. configurable: true
  5144. });
  5145. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5146. if (this._blendFunctionParameters[0] === value0 &&
  5147. this._blendFunctionParameters[1] === value1 &&
  5148. this._blendFunctionParameters[2] === value2 &&
  5149. this._blendFunctionParameters[3] === value3) {
  5150. return;
  5151. }
  5152. this._blendFunctionParameters[0] = value0;
  5153. this._blendFunctionParameters[1] = value1;
  5154. this._blendFunctionParameters[2] = value2;
  5155. this._blendFunctionParameters[3] = value3;
  5156. this._isBlendFunctionParametersDirty = true;
  5157. };
  5158. _AlphaState.prototype.reset = function () {
  5159. this._alphaBlend = false;
  5160. this._blendFunctionParameters[0] = null;
  5161. this._blendFunctionParameters[1] = null;
  5162. this._blendFunctionParameters[2] = null;
  5163. this._blendFunctionParameters[3] = null;
  5164. this._isAlphaBlendDirty = true;
  5165. this._isBlendFunctionParametersDirty = false;
  5166. };
  5167. _AlphaState.prototype.apply = function (gl) {
  5168. if (!this.isDirty) {
  5169. return;
  5170. }
  5171. // Alpha blend
  5172. if (this._isAlphaBlendDirty) {
  5173. if (this._alphaBlend) {
  5174. gl.enable(gl.BLEND);
  5175. }
  5176. else {
  5177. gl.disable(gl.BLEND);
  5178. }
  5179. this._isAlphaBlendDirty = false;
  5180. }
  5181. // Alpha function
  5182. if (this._isBlendFunctionParametersDirty) {
  5183. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5184. this._isBlendFunctionParametersDirty = false;
  5185. }
  5186. };
  5187. return _AlphaState;
  5188. })();
  5189. BABYLON._AlphaState = _AlphaState;
  5190. var compileShader = function (gl, source, type, defines) {
  5191. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5192. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5193. gl.compileShader(shader);
  5194. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5195. throw new Error(gl.getShaderInfoLog(shader));
  5196. }
  5197. return shader;
  5198. };
  5199. var getWebGLTextureType = function (gl, type) {
  5200. var textureType = gl.UNSIGNED_BYTE;
  5201. if (type === Engine.TEXTURETYPE_FLOAT)
  5202. textureType = gl.FLOAT;
  5203. return textureType;
  5204. };
  5205. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5206. var magFilter = gl.NEAREST;
  5207. var minFilter = gl.NEAREST;
  5208. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5209. magFilter = gl.LINEAR;
  5210. if (generateMipMaps) {
  5211. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5212. }
  5213. else {
  5214. minFilter = gl.LINEAR;
  5215. }
  5216. }
  5217. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5218. magFilter = gl.LINEAR;
  5219. if (generateMipMaps) {
  5220. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5221. }
  5222. else {
  5223. minFilter = gl.LINEAR;
  5224. }
  5225. }
  5226. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5227. magFilter = gl.NEAREST;
  5228. if (generateMipMaps) {
  5229. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5230. }
  5231. else {
  5232. minFilter = gl.NEAREST;
  5233. }
  5234. }
  5235. return {
  5236. min: minFilter,
  5237. mag: magFilter
  5238. };
  5239. };
  5240. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5242. var engine = scene.getEngine();
  5243. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5244. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5245. gl.bindTexture(gl.TEXTURE_2D, texture);
  5246. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5247. texture._baseWidth = width;
  5248. texture._baseHeight = height;
  5249. texture._width = potWidth;
  5250. texture._height = potHeight;
  5251. texture.isReady = true;
  5252. processFunction(potWidth, potHeight);
  5253. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5256. if (!noMipmap && !isCompressed) {
  5257. gl.generateMipmap(gl.TEXTURE_2D);
  5258. }
  5259. gl.bindTexture(gl.TEXTURE_2D, null);
  5260. engine._activeTexturesCache = [];
  5261. scene._removePendingData(texture);
  5262. };
  5263. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5264. var onload = function () {
  5265. loadedImages[index] = img;
  5266. loadedImages._internalCount++;
  5267. scene._removePendingData(img);
  5268. if (loadedImages._internalCount === 6) {
  5269. onfinish(loadedImages);
  5270. }
  5271. };
  5272. var onerror = function () {
  5273. scene._removePendingData(img);
  5274. };
  5275. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5276. scene._addPendingData(img);
  5277. };
  5278. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5279. var loadedImages = [];
  5280. loadedImages._internalCount = 0;
  5281. for (var index = 0; index < 6; index++) {
  5282. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5283. }
  5284. };
  5285. var EngineCapabilities = (function () {
  5286. function EngineCapabilities() {
  5287. }
  5288. return EngineCapabilities;
  5289. })();
  5290. BABYLON.EngineCapabilities = EngineCapabilities;
  5291. /**
  5292. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5293. */
  5294. var Engine = (function () {
  5295. /**
  5296. * @constructor
  5297. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5298. * @param {boolean} [antialias] - enable antialias
  5299. * @param options - further options to be sent to the getContext function
  5300. */
  5301. function Engine(canvas, antialias, options) {
  5302. var _this = this;
  5303. // Public members
  5304. this.isFullscreen = false;
  5305. this.isPointerLock = false;
  5306. this.cullBackFaces = true;
  5307. this.renderEvenInBackground = true;
  5308. this.scenes = new Array();
  5309. this._windowIsBackground = false;
  5310. this._loadingDivBackgroundColor = "black";
  5311. this._drawCalls = 0;
  5312. this._renderingQueueLaunched = false;
  5313. this._activeRenderLoops = [];
  5314. // FPS
  5315. this.fpsRange = 60;
  5316. this.previousFramesDuration = [];
  5317. this.fps = 60;
  5318. this.deltaTime = 0;
  5319. // States
  5320. this._depthCullingState = new _DepthCullingState();
  5321. this._alphaState = new _AlphaState();
  5322. this._alphaMode = Engine.ALPHA_DISABLE;
  5323. // Cache
  5324. this._loadedTexturesCache = new Array();
  5325. this._activeTexturesCache = new Array();
  5326. this._compiledEffects = {};
  5327. this._uintIndicesCurrentlySet = false;
  5328. this._renderingCanvas = canvas;
  5329. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5330. options = options || {};
  5331. options.antialias = antialias;
  5332. // GL
  5333. try {
  5334. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5335. }
  5336. catch (e) {
  5337. throw new Error("WebGL not supported");
  5338. }
  5339. if (!this._gl) {
  5340. throw new Error("WebGL not supported");
  5341. }
  5342. this._onBlur = function () {
  5343. _this._windowIsBackground = true;
  5344. };
  5345. this._onFocus = function () {
  5346. _this._windowIsBackground = false;
  5347. };
  5348. window.addEventListener("blur", this._onBlur);
  5349. window.addEventListener("focus", this._onFocus);
  5350. // Viewport
  5351. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5352. this.resize();
  5353. // Caps
  5354. this._caps = new EngineCapabilities();
  5355. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5356. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5357. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5358. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5359. // Infos
  5360. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5361. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5362. if (rendererInfo != null) {
  5363. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5364. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5365. }
  5366. if (!this._glVendor) {
  5367. this._glVendor = "Unknown vendor";
  5368. }
  5369. if (!this._glRenderer) {
  5370. this._glRenderer = "Unknown renderer";
  5371. }
  5372. // Extensions
  5373. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5374. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5375. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5376. 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');
  5377. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5378. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5379. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5380. this._caps.highPrecisionShaderSupported = true;
  5381. if (this._gl.getShaderPrecisionFormat) {
  5382. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5383. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5384. }
  5385. // Depth buffer
  5386. this.setDepthBuffer(true);
  5387. this.setDepthFunctionToLessOrEqual();
  5388. this.setDepthWrite(true);
  5389. // Fullscreen
  5390. this._onFullscreenChange = function () {
  5391. if (document.fullscreen !== undefined) {
  5392. _this.isFullscreen = document.fullscreen;
  5393. }
  5394. else if (document.mozFullScreen !== undefined) {
  5395. _this.isFullscreen = document.mozFullScreen;
  5396. }
  5397. else if (document.webkitIsFullScreen !== undefined) {
  5398. _this.isFullscreen = document.webkitIsFullScreen;
  5399. }
  5400. else if (document.msIsFullScreen !== undefined) {
  5401. _this.isFullscreen = document.msIsFullScreen;
  5402. }
  5403. // Pointer lock
  5404. if (_this.isFullscreen && _this._pointerLockRequested) {
  5405. canvas.requestPointerLock = canvas.requestPointerLock ||
  5406. canvas.msRequestPointerLock ||
  5407. canvas.mozRequestPointerLock ||
  5408. canvas.webkitRequestPointerLock;
  5409. if (canvas.requestPointerLock) {
  5410. canvas.requestPointerLock();
  5411. }
  5412. }
  5413. };
  5414. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5415. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5416. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5417. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5418. // Pointer lock
  5419. this._onPointerLockChange = function () {
  5420. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5421. document.webkitPointerLockElement === canvas ||
  5422. document.msPointerLockElement === canvas ||
  5423. document.pointerLockElement === canvas);
  5424. };
  5425. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5426. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5427. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5428. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5429. if (!Engine.audioEngine) {
  5430. Engine.audioEngine = new BABYLON.AudioEngine();
  5431. }
  5432. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5433. }
  5434. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5435. get: function () {
  5436. return Engine._ALPHA_DISABLE;
  5437. },
  5438. enumerable: true,
  5439. configurable: true
  5440. });
  5441. Object.defineProperty(Engine, "ALPHA_ADD", {
  5442. get: function () {
  5443. return Engine._ALPHA_ADD;
  5444. },
  5445. enumerable: true,
  5446. configurable: true
  5447. });
  5448. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5449. get: function () {
  5450. return Engine._ALPHA_COMBINE;
  5451. },
  5452. enumerable: true,
  5453. configurable: true
  5454. });
  5455. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5456. get: function () {
  5457. return Engine._DELAYLOADSTATE_NONE;
  5458. },
  5459. enumerable: true,
  5460. configurable: true
  5461. });
  5462. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5463. get: function () {
  5464. return Engine._DELAYLOADSTATE_LOADED;
  5465. },
  5466. enumerable: true,
  5467. configurable: true
  5468. });
  5469. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5470. get: function () {
  5471. return Engine._DELAYLOADSTATE_LOADING;
  5472. },
  5473. enumerable: true,
  5474. configurable: true
  5475. });
  5476. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5477. get: function () {
  5478. return Engine._DELAYLOADSTATE_NOTLOADED;
  5479. },
  5480. enumerable: true,
  5481. configurable: true
  5482. });
  5483. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5484. get: function () {
  5485. return Engine._TEXTUREFORMAT_ALPHA;
  5486. },
  5487. enumerable: true,
  5488. configurable: true
  5489. });
  5490. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5491. get: function () {
  5492. return Engine._TEXTUREFORMAT_LUMINANCE;
  5493. },
  5494. enumerable: true,
  5495. configurable: true
  5496. });
  5497. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5498. get: function () {
  5499. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5500. },
  5501. enumerable: true,
  5502. configurable: true
  5503. });
  5504. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5505. get: function () {
  5506. return Engine._TEXTUREFORMAT_RGB;
  5507. },
  5508. enumerable: true,
  5509. configurable: true
  5510. });
  5511. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5512. get: function () {
  5513. return Engine._TEXTUREFORMAT_RGBA;
  5514. },
  5515. enumerable: true,
  5516. configurable: true
  5517. });
  5518. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5519. get: function () {
  5520. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5521. },
  5522. enumerable: true,
  5523. configurable: true
  5524. });
  5525. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5526. get: function () {
  5527. return Engine._TEXTURETYPE_FLOAT;
  5528. },
  5529. enumerable: true,
  5530. configurable: true
  5531. });
  5532. Object.defineProperty(Engine, "Version", {
  5533. get: function () {
  5534. return "2.1.0 beta";
  5535. },
  5536. enumerable: true,
  5537. configurable: true
  5538. });
  5539. Engine.prototype._prepareWorkingCanvas = function () {
  5540. if (this._workingCanvas) {
  5541. return;
  5542. }
  5543. this._workingCanvas = document.createElement("canvas");
  5544. this._workingContext = this._workingCanvas.getContext("2d");
  5545. };
  5546. Engine.prototype.getGlInfo = function () {
  5547. return {
  5548. vendor: this._glVendor,
  5549. renderer: this._glRenderer,
  5550. version: this._glVersion
  5551. };
  5552. };
  5553. Engine.prototype.getAspectRatio = function (camera) {
  5554. var viewport = camera.viewport;
  5555. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5556. };
  5557. Engine.prototype.getRenderWidth = function () {
  5558. if (this._currentRenderTarget) {
  5559. return this._currentRenderTarget._width;
  5560. }
  5561. return this._renderingCanvas.width;
  5562. };
  5563. Engine.prototype.getRenderHeight = function () {
  5564. if (this._currentRenderTarget) {
  5565. return this._currentRenderTarget._height;
  5566. }
  5567. return this._renderingCanvas.height;
  5568. };
  5569. Engine.prototype.getRenderingCanvas = function () {
  5570. return this._renderingCanvas;
  5571. };
  5572. Engine.prototype.getRenderingCanvasClientRect = function () {
  5573. return this._renderingCanvas.getBoundingClientRect();
  5574. };
  5575. Engine.prototype.setHardwareScalingLevel = function (level) {
  5576. this._hardwareScalingLevel = level;
  5577. this.resize();
  5578. };
  5579. Engine.prototype.getHardwareScalingLevel = function () {
  5580. return this._hardwareScalingLevel;
  5581. };
  5582. Engine.prototype.getLoadedTexturesCache = function () {
  5583. return this._loadedTexturesCache;
  5584. };
  5585. Engine.prototype.getCaps = function () {
  5586. return this._caps;
  5587. };
  5588. Object.defineProperty(Engine.prototype, "drawCalls", {
  5589. get: function () {
  5590. return this._drawCalls;
  5591. },
  5592. enumerable: true,
  5593. configurable: true
  5594. });
  5595. // Methods
  5596. Engine.prototype.resetDrawCalls = function () {
  5597. this._drawCalls = 0;
  5598. };
  5599. Engine.prototype.setDepthFunctionToGreater = function () {
  5600. this._depthCullingState.depthFunc = this._gl.GREATER;
  5601. };
  5602. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5603. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5604. };
  5605. Engine.prototype.setDepthFunctionToLess = function () {
  5606. this._depthCullingState.depthFunc = this._gl.LESS;
  5607. };
  5608. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5609. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5610. };
  5611. /**
  5612. * stop executing a render loop function and remove it from the execution array
  5613. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5614. */
  5615. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5616. if (!renderFunction) {
  5617. this._activeRenderLoops = [];
  5618. return;
  5619. }
  5620. var index = this._activeRenderLoops.indexOf(renderFunction);
  5621. if (index >= 0) {
  5622. this._activeRenderLoops.splice(index, 1);
  5623. }
  5624. };
  5625. Engine.prototype._renderLoop = function () {
  5626. var _this = this;
  5627. var shouldRender = true;
  5628. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5629. shouldRender = false;
  5630. }
  5631. if (shouldRender) {
  5632. // Start new frame
  5633. this.beginFrame();
  5634. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5635. var renderFunction = this._activeRenderLoops[index];
  5636. renderFunction();
  5637. }
  5638. // Present
  5639. this.endFrame();
  5640. }
  5641. if (this._activeRenderLoops.length > 0) {
  5642. // Register new frame
  5643. BABYLON.Tools.QueueNewFrame(function () {
  5644. _this._renderLoop();
  5645. });
  5646. }
  5647. else {
  5648. this._renderingQueueLaunched = false;
  5649. }
  5650. };
  5651. /**
  5652. * Register and execute a render loop. The engine can have more than one render function.
  5653. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5654. * @example
  5655. * engine.runRenderLoop(function () {
  5656. * scene.render()
  5657. * })
  5658. */
  5659. Engine.prototype.runRenderLoop = function (renderFunction) {
  5660. var _this = this;
  5661. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5662. return;
  5663. }
  5664. this._activeRenderLoops.push(renderFunction);
  5665. if (!this._renderingQueueLaunched) {
  5666. this._renderingQueueLaunched = true;
  5667. BABYLON.Tools.QueueNewFrame(function () {
  5668. _this._renderLoop();
  5669. });
  5670. }
  5671. };
  5672. /**
  5673. * Toggle full screen mode.
  5674. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5675. */
  5676. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5677. if (this.isFullscreen) {
  5678. BABYLON.Tools.ExitFullscreen();
  5679. }
  5680. else {
  5681. this._pointerLockRequested = requestPointerLock;
  5682. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5683. }
  5684. };
  5685. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5686. this.applyStates();
  5687. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5688. if (this._depthCullingState.depthMask) {
  5689. this._gl.clearDepth(1.0);
  5690. }
  5691. var mode = 0;
  5692. if (backBuffer)
  5693. mode |= this._gl.COLOR_BUFFER_BIT;
  5694. if (depthStencil && this._depthCullingState.depthMask)
  5695. mode |= this._gl.DEPTH_BUFFER_BIT;
  5696. this._gl.clear(mode);
  5697. };
  5698. /**
  5699. * Set the WebGL's viewport
  5700. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5701. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5702. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5703. */
  5704. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5705. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5706. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5707. var x = viewport.x || 0;
  5708. var y = viewport.y || 0;
  5709. this._cachedViewport = viewport;
  5710. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5711. };
  5712. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5713. this._cachedViewport = null;
  5714. this._gl.viewport(x, y, width, height);
  5715. };
  5716. Engine.prototype.beginFrame = function () {
  5717. this._measureFps();
  5718. };
  5719. Engine.prototype.endFrame = function () {
  5720. //this.flushFramebuffer();
  5721. };
  5722. /**
  5723. * resize the view according to the canvas' size.
  5724. * @example
  5725. * window.addEventListener("resize", function () {
  5726. * engine.resize();
  5727. * });
  5728. */
  5729. Engine.prototype.resize = function () {
  5730. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5731. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5732. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5733. };
  5734. /**
  5735. * force a specific size of the canvas
  5736. * @param {number} width - the new canvas' width
  5737. * @param {number} height - the new canvas' height
  5738. */
  5739. Engine.prototype.setSize = function (width, height) {
  5740. this._renderingCanvas.width = width;
  5741. this._renderingCanvas.height = height;
  5742. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5743. for (var index = 0; index < this.scenes.length; index++) {
  5744. var scene = this.scenes[index];
  5745. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5746. var cam = scene.cameras[camIndex];
  5747. cam._currentRenderId = 0;
  5748. }
  5749. }
  5750. };
  5751. Engine.prototype.bindFramebuffer = function (texture) {
  5752. this._currentRenderTarget = texture;
  5753. var gl = this._gl;
  5754. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5755. this._gl.viewport(0, 0, texture._width, texture._height);
  5756. this.wipeCaches();
  5757. };
  5758. Engine.prototype.unBindFramebuffer = function (texture) {
  5759. this._currentRenderTarget = null;
  5760. if (texture.generateMipMaps) {
  5761. var gl = this._gl;
  5762. gl.bindTexture(gl.TEXTURE_2D, texture);
  5763. gl.generateMipmap(gl.TEXTURE_2D);
  5764. gl.bindTexture(gl.TEXTURE_2D, null);
  5765. }
  5766. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5767. };
  5768. Engine.prototype.flushFramebuffer = function () {
  5769. this._gl.flush();
  5770. };
  5771. Engine.prototype.restoreDefaultFramebuffer = function () {
  5772. this._currentRenderTarget = null;
  5773. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5774. this.setViewport(this._cachedViewport);
  5775. this.wipeCaches();
  5776. };
  5777. // VBOs
  5778. Engine.prototype._resetVertexBufferBinding = function () {
  5779. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5780. this._cachedVertexBuffers = null;
  5781. };
  5782. Engine.prototype.createVertexBuffer = function (vertices) {
  5783. var vbo = this._gl.createBuffer();
  5784. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5785. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5786. this._resetVertexBufferBinding();
  5787. vbo.references = 1;
  5788. return vbo;
  5789. };
  5790. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5791. var vbo = this._gl.createBuffer();
  5792. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5793. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5794. this._resetVertexBufferBinding();
  5795. vbo.references = 1;
  5796. return vbo;
  5797. };
  5798. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5799. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5800. if (offset === undefined) {
  5801. offset = 0;
  5802. }
  5803. if (vertices instanceof Float32Array) {
  5804. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5805. }
  5806. else {
  5807. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5808. }
  5809. this._resetVertexBufferBinding();
  5810. };
  5811. Engine.prototype._resetIndexBufferBinding = function () {
  5812. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5813. this._cachedIndexBuffer = null;
  5814. };
  5815. Engine.prototype.createIndexBuffer = function (indices) {
  5816. var vbo = this._gl.createBuffer();
  5817. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5818. // Check for 32 bits indices
  5819. var arrayBuffer;
  5820. var need32Bits = false;
  5821. if (this._caps.uintIndices) {
  5822. for (var index = 0; index < indices.length; index++) {
  5823. if (indices[index] > 65535) {
  5824. need32Bits = true;
  5825. break;
  5826. }
  5827. }
  5828. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5829. }
  5830. else {
  5831. arrayBuffer = new Uint16Array(indices);
  5832. }
  5833. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5834. this._resetIndexBufferBinding();
  5835. vbo.references = 1;
  5836. vbo.is32Bits = need32Bits;
  5837. return vbo;
  5838. };
  5839. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5840. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5841. this._cachedVertexBuffers = vertexBuffer;
  5842. this._cachedEffectForVertexBuffers = effect;
  5843. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5844. var offset = 0;
  5845. for (var index = 0; index < vertexDeclaration.length; index++) {
  5846. var order = effect.getAttributeLocation(index);
  5847. if (order >= 0) {
  5848. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5849. }
  5850. offset += vertexDeclaration[index] * 4;
  5851. }
  5852. }
  5853. if (this._cachedIndexBuffer !== indexBuffer) {
  5854. this._cachedIndexBuffer = indexBuffer;
  5855. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5856. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5857. }
  5858. };
  5859. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5860. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5861. this._cachedVertexBuffers = vertexBuffers;
  5862. this._cachedEffectForVertexBuffers = effect;
  5863. var attributes = effect.getAttributesNames();
  5864. for (var index = 0; index < attributes.length; index++) {
  5865. var order = effect.getAttributeLocation(index);
  5866. if (order >= 0) {
  5867. var vertexBuffer = vertexBuffers[attributes[index]];
  5868. if (!vertexBuffer) {
  5869. continue;
  5870. }
  5871. var stride = vertexBuffer.getStrideSize();
  5872. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5873. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5874. }
  5875. }
  5876. }
  5877. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5878. this._cachedIndexBuffer = indexBuffer;
  5879. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5880. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5881. }
  5882. };
  5883. Engine.prototype._releaseBuffer = function (buffer) {
  5884. buffer.references--;
  5885. if (buffer.references === 0) {
  5886. this._gl.deleteBuffer(buffer);
  5887. return true;
  5888. }
  5889. return false;
  5890. };
  5891. Engine.prototype.createInstancesBuffer = function (capacity) {
  5892. var buffer = this._gl.createBuffer();
  5893. buffer.capacity = capacity;
  5894. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5895. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5896. return buffer;
  5897. };
  5898. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5899. this._gl.deleteBuffer(buffer);
  5900. };
  5901. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5902. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5903. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5904. for (var index = 0; index < 4; index++) {
  5905. var offsetLocation = offsetLocations[index];
  5906. this._gl.enableVertexAttribArray(offsetLocation);
  5907. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5908. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5909. }
  5910. };
  5911. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5912. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5913. for (var index = 0; index < 4; index++) {
  5914. var offsetLocation = offsetLocations[index];
  5915. this._gl.disableVertexAttribArray(offsetLocation);
  5916. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5917. }
  5918. };
  5919. Engine.prototype.applyStates = function () {
  5920. this._depthCullingState.apply(this._gl);
  5921. this._alphaState.apply(this._gl);
  5922. };
  5923. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5924. // Apply states
  5925. this.applyStates();
  5926. this._drawCalls++;
  5927. // Render
  5928. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5929. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5930. if (instancesCount) {
  5931. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5932. return;
  5933. }
  5934. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5935. };
  5936. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5937. // Apply states
  5938. this.applyStates();
  5939. this._drawCalls++;
  5940. if (instancesCount) {
  5941. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5942. return;
  5943. }
  5944. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5945. };
  5946. // Shaders
  5947. Engine.prototype._releaseEffect = function (effect) {
  5948. if (this._compiledEffects[effect._key]) {
  5949. delete this._compiledEffects[effect._key];
  5950. if (effect.getProgram()) {
  5951. this._gl.deleteProgram(effect.getProgram());
  5952. }
  5953. }
  5954. };
  5955. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5956. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5957. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5958. var name = vertex + "+" + fragment + "@" + defines;
  5959. if (this._compiledEffects[name]) {
  5960. return this._compiledEffects[name];
  5961. }
  5962. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5963. effect._key = name;
  5964. this._compiledEffects[name] = effect;
  5965. return effect;
  5966. };
  5967. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5968. if (uniformsNames === void 0) { uniformsNames = []; }
  5969. if (samplers === void 0) { samplers = []; }
  5970. if (defines === void 0) { defines = ""; }
  5971. return this.createEffect({
  5972. vertex: "particles",
  5973. fragmentElement: fragmentName
  5974. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5975. };
  5976. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5977. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5978. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5979. var shaderProgram = this._gl.createProgram();
  5980. this._gl.attachShader(shaderProgram, vertexShader);
  5981. this._gl.attachShader(shaderProgram, fragmentShader);
  5982. this._gl.linkProgram(shaderProgram);
  5983. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5984. if (!linked) {
  5985. var error = this._gl.getProgramInfoLog(shaderProgram);
  5986. if (error) {
  5987. throw new Error(error);
  5988. }
  5989. }
  5990. this._gl.deleteShader(vertexShader);
  5991. this._gl.deleteShader(fragmentShader);
  5992. return shaderProgram;
  5993. };
  5994. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5995. var results = [];
  5996. for (var index = 0; index < uniformsNames.length; index++) {
  5997. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5998. }
  5999. return results;
  6000. };
  6001. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6002. var results = [];
  6003. for (var index = 0; index < attributesNames.length; index++) {
  6004. try {
  6005. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6006. }
  6007. catch (e) {
  6008. results.push(-1);
  6009. }
  6010. }
  6011. return results;
  6012. };
  6013. Engine.prototype.enableEffect = function (effect) {
  6014. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6015. if (effect && effect.onBind) {
  6016. effect.onBind(effect);
  6017. }
  6018. return;
  6019. }
  6020. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6021. // Use program
  6022. this._gl.useProgram(effect.getProgram());
  6023. for (var i in this._vertexAttribArrays) {
  6024. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6025. continue;
  6026. }
  6027. this._vertexAttribArrays[i] = false;
  6028. this._gl.disableVertexAttribArray(i);
  6029. }
  6030. var attributesCount = effect.getAttributesCount();
  6031. for (var index = 0; index < attributesCount; index++) {
  6032. // Attributes
  6033. var order = effect.getAttributeLocation(index);
  6034. if (order >= 0) {
  6035. this._vertexAttribArrays[order] = true;
  6036. this._gl.enableVertexAttribArray(order);
  6037. }
  6038. }
  6039. this._currentEffect = effect;
  6040. if (effect.onBind) {
  6041. effect.onBind(effect);
  6042. }
  6043. };
  6044. Engine.prototype.setArray = function (uniform, array) {
  6045. if (!uniform)
  6046. return;
  6047. this._gl.uniform1fv(uniform, array);
  6048. };
  6049. Engine.prototype.setArray2 = function (uniform, array) {
  6050. if (!uniform || array.length % 2 !== 0)
  6051. return;
  6052. this._gl.uniform2fv(uniform, array);
  6053. };
  6054. Engine.prototype.setArray3 = function (uniform, array) {
  6055. if (!uniform || array.length % 3 !== 0)
  6056. return;
  6057. this._gl.uniform3fv(uniform, array);
  6058. };
  6059. Engine.prototype.setArray4 = function (uniform, array) {
  6060. if (!uniform || array.length % 4 !== 0)
  6061. return;
  6062. this._gl.uniform4fv(uniform, array);
  6063. };
  6064. Engine.prototype.setMatrices = function (uniform, matrices) {
  6065. if (!uniform)
  6066. return;
  6067. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6068. };
  6069. Engine.prototype.setMatrix = function (uniform, matrix) {
  6070. if (!uniform)
  6071. return;
  6072. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6073. };
  6074. Engine.prototype.setFloat = function (uniform, value) {
  6075. if (!uniform)
  6076. return;
  6077. this._gl.uniform1f(uniform, value);
  6078. };
  6079. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6080. if (!uniform)
  6081. return;
  6082. this._gl.uniform2f(uniform, x, y);
  6083. };
  6084. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6085. if (!uniform)
  6086. return;
  6087. this._gl.uniform3f(uniform, x, y, z);
  6088. };
  6089. Engine.prototype.setBool = function (uniform, bool) {
  6090. if (!uniform)
  6091. return;
  6092. this._gl.uniform1i(uniform, bool);
  6093. };
  6094. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6095. if (!uniform)
  6096. return;
  6097. this._gl.uniform4f(uniform, x, y, z, w);
  6098. };
  6099. Engine.prototype.setColor3 = function (uniform, color3) {
  6100. if (!uniform)
  6101. return;
  6102. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6103. };
  6104. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6105. if (!uniform)
  6106. return;
  6107. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6108. };
  6109. // States
  6110. Engine.prototype.setState = function (culling, zOffset, force) {
  6111. if (zOffset === void 0) { zOffset = 0; }
  6112. // Culling
  6113. if (this._depthCullingState.cull !== culling || force) {
  6114. if (culling) {
  6115. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6116. this._depthCullingState.cull = true;
  6117. }
  6118. else {
  6119. this._depthCullingState.cull = false;
  6120. }
  6121. }
  6122. // Z offset
  6123. this._depthCullingState.zOffset = zOffset;
  6124. };
  6125. Engine.prototype.setDepthBuffer = function (enable) {
  6126. this._depthCullingState.depthTest = enable;
  6127. };
  6128. Engine.prototype.getDepthWrite = function () {
  6129. return this._depthCullingState.depthMask;
  6130. };
  6131. Engine.prototype.setDepthWrite = function (enable) {
  6132. this._depthCullingState.depthMask = enable;
  6133. };
  6134. Engine.prototype.setColorWrite = function (enable) {
  6135. this._gl.colorMask(enable, enable, enable, enable);
  6136. };
  6137. Engine.prototype.setAlphaMode = function (mode) {
  6138. switch (mode) {
  6139. case Engine.ALPHA_DISABLE:
  6140. this.setDepthWrite(true);
  6141. this._alphaState.alphaBlend = false;
  6142. break;
  6143. case Engine.ALPHA_COMBINE:
  6144. this.setDepthWrite(false);
  6145. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6146. this._alphaState.alphaBlend = true;
  6147. break;
  6148. case Engine.ALPHA_ADD:
  6149. this.setDepthWrite(false);
  6150. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6151. this._alphaState.alphaBlend = true;
  6152. break;
  6153. }
  6154. this._alphaMode = mode;
  6155. };
  6156. Engine.prototype.getAlphaMode = function () {
  6157. return this._alphaMode;
  6158. };
  6159. Engine.prototype.setAlphaTesting = function (enable) {
  6160. this._alphaTest = enable;
  6161. };
  6162. Engine.prototype.getAlphaTesting = function () {
  6163. return this._alphaTest;
  6164. };
  6165. // Textures
  6166. Engine.prototype.wipeCaches = function () {
  6167. this._activeTexturesCache = [];
  6168. this._currentEffect = null;
  6169. this._depthCullingState.reset();
  6170. this._alphaState.reset();
  6171. this._cachedVertexBuffers = null;
  6172. this._cachedIndexBuffer = null;
  6173. this._cachedEffectForVertexBuffers = null;
  6174. };
  6175. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6176. var gl = this._gl;
  6177. gl.bindTexture(gl.TEXTURE_2D, texture);
  6178. var magFilter = gl.NEAREST;
  6179. var minFilter = gl.NEAREST;
  6180. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6181. magFilter = gl.LINEAR;
  6182. minFilter = gl.LINEAR;
  6183. }
  6184. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6185. magFilter = gl.LINEAR;
  6186. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6187. }
  6188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6190. gl.bindTexture(gl.TEXTURE_2D, null);
  6191. texture.samplingMode = samplingMode;
  6192. };
  6193. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6194. var _this = this;
  6195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6196. if (onLoad === void 0) { onLoad = null; }
  6197. if (onError === void 0) { onError = null; }
  6198. if (buffer === void 0) { buffer = null; }
  6199. var texture = this._gl.createTexture();
  6200. var extension;
  6201. var fromData = false;
  6202. if (url.substr(0, 5) === "data:") {
  6203. fromData = true;
  6204. }
  6205. if (!fromData)
  6206. extension = url.substr(url.length - 4, 4).toLowerCase();
  6207. else {
  6208. var oldUrl = url;
  6209. fromData = oldUrl.split(':');
  6210. url = oldUrl;
  6211. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6212. }
  6213. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6214. var isTGA = (extension === ".tga");
  6215. scene._addPendingData(texture);
  6216. texture.url = url;
  6217. texture.noMipmap = noMipmap;
  6218. texture.references = 1;
  6219. texture.samplingMode = samplingMode;
  6220. this._loadedTexturesCache.push(texture);
  6221. var onerror = function () {
  6222. scene._removePendingData(texture);
  6223. if (onError) {
  6224. onError();
  6225. }
  6226. };
  6227. if (isTGA) {
  6228. var callback = function (arrayBuffer) {
  6229. var data = new Uint8Array(arrayBuffer);
  6230. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6231. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6232. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6233. if (onLoad) {
  6234. onLoad();
  6235. }
  6236. }, samplingMode);
  6237. };
  6238. if (!(fromData instanceof Array))
  6239. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6240. callback(arrayBuffer);
  6241. }, onerror, scene.database, true);
  6242. else
  6243. callback(buffer);
  6244. }
  6245. else if (isDDS) {
  6246. callback = function (data) {
  6247. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6248. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6249. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6250. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6251. if (onLoad) {
  6252. onLoad();
  6253. }
  6254. }, samplingMode);
  6255. };
  6256. if (!(fromData instanceof Array))
  6257. BABYLON.Tools.LoadFile(url, function (data) {
  6258. callback(data);
  6259. }, onerror, scene.database, true);
  6260. else
  6261. callback(buffer);
  6262. }
  6263. else {
  6264. var onload = function (img) {
  6265. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6266. var isPot = (img.width === potWidth && img.height === potHeight);
  6267. if (!isPot) {
  6268. _this._prepareWorkingCanvas();
  6269. _this._workingCanvas.width = potWidth;
  6270. _this._workingCanvas.height = potHeight;
  6271. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6272. _this._workingContext.imageSmoothingEnabled = false;
  6273. _this._workingContext.mozImageSmoothingEnabled = false;
  6274. _this._workingContext.oImageSmoothingEnabled = false;
  6275. _this._workingContext.webkitImageSmoothingEnabled = false;
  6276. _this._workingContext.msImageSmoothingEnabled = false;
  6277. }
  6278. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6279. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6280. _this._workingContext.imageSmoothingEnabled = true;
  6281. _this._workingContext.mozImageSmoothingEnabled = true;
  6282. _this._workingContext.oImageSmoothingEnabled = true;
  6283. _this._workingContext.webkitImageSmoothingEnabled = true;
  6284. _this._workingContext.msImageSmoothingEnabled = true;
  6285. }
  6286. }
  6287. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6288. if (onLoad) {
  6289. onLoad();
  6290. }
  6291. }, samplingMode);
  6292. };
  6293. if (!(fromData instanceof Array))
  6294. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6295. else
  6296. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6297. }
  6298. return texture;
  6299. };
  6300. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6301. var texture = this._gl.createTexture();
  6302. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6303. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6304. // Format
  6305. var internalFormat = this._gl.RGBA;
  6306. switch (format) {
  6307. case Engine.TEXTUREFORMAT_ALPHA:
  6308. internalFormat = this._gl.ALPHA;
  6309. break;
  6310. case Engine.TEXTUREFORMAT_LUMINANCE:
  6311. internalFormat = this._gl.LUMINANCE;
  6312. break;
  6313. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6314. internalFormat = this._gl.LUMINANCE_ALPHA;
  6315. break;
  6316. case Engine.TEXTUREFORMAT_RGB:
  6317. internalFormat = this._gl.RGB;
  6318. break;
  6319. case Engine.TEXTUREFORMAT_RGBA:
  6320. internalFormat = this._gl.RGBA;
  6321. break;
  6322. }
  6323. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6324. if (generateMipMaps) {
  6325. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6326. }
  6327. // Filters
  6328. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6329. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6331. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6332. this._activeTexturesCache = [];
  6333. texture._baseWidth = width;
  6334. texture._baseHeight = height;
  6335. texture._width = width;
  6336. texture._height = height;
  6337. texture.isReady = true;
  6338. texture.references = 1;
  6339. texture.samplingMode = samplingMode;
  6340. this._loadedTexturesCache.push(texture);
  6341. return texture;
  6342. };
  6343. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6344. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6345. var texture = this._gl.createTexture();
  6346. texture._baseWidth = width;
  6347. texture._baseHeight = height;
  6348. if (forceExponantOfTwo) {
  6349. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6350. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6351. }
  6352. this._activeTexturesCache = [];
  6353. texture._width = width;
  6354. texture._height = height;
  6355. texture.isReady = false;
  6356. texture.generateMipMaps = generateMipMaps;
  6357. texture.references = 1;
  6358. texture.samplingMode = samplingMode;
  6359. this.updateTextureSamplingMode(samplingMode, texture);
  6360. this._loadedTexturesCache.push(texture);
  6361. return texture;
  6362. };
  6363. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6364. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6365. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6366. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6367. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6368. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6369. };
  6370. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6371. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6372. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6373. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6374. if (texture.generateMipMaps) {
  6375. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6376. }
  6377. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6378. this._activeTexturesCache = [];
  6379. texture.isReady = true;
  6380. };
  6381. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6382. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6383. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6384. // Testing video texture support
  6385. if (this._videoTextureSupported === undefined) {
  6386. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6387. if (this._gl.getError() !== 0) {
  6388. this._videoTextureSupported = false;
  6389. }
  6390. else {
  6391. this._videoTextureSupported = true;
  6392. }
  6393. }
  6394. // Copy video through the current working canvas if video texture is not supported
  6395. if (!this._videoTextureSupported) {
  6396. if (!texture._workingCanvas) {
  6397. texture._workingCanvas = document.createElement("canvas");
  6398. texture._workingContext = texture._workingCanvas.getContext("2d");
  6399. texture._workingCanvas.width = texture._width;
  6400. texture._workingCanvas.height = texture._height;
  6401. }
  6402. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6403. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6404. }
  6405. else {
  6406. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6407. }
  6408. if (texture.generateMipMaps) {
  6409. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6410. }
  6411. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6412. this._activeTexturesCache = [];
  6413. texture.isReady = true;
  6414. };
  6415. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6416. // old version had a "generateMipMaps" arg instead of options.
  6417. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6418. // in the same way, generateDepthBuffer is defaulted to true
  6419. var generateMipMaps = false;
  6420. var generateDepthBuffer = true;
  6421. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6422. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6423. if (options !== undefined) {
  6424. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6425. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6426. type = options.type === undefined ? type : options.type;
  6427. if (options.samplingMode !== undefined) {
  6428. samplingMode = options.samplingMode;
  6429. }
  6430. if (type === Engine.TEXTURETYPE_FLOAT) {
  6431. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6432. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6433. }
  6434. }
  6435. var gl = this._gl;
  6436. var texture = gl.createTexture();
  6437. gl.bindTexture(gl.TEXTURE_2D, texture);
  6438. var width = size.width || size;
  6439. var height = size.height || size;
  6440. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6441. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6442. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6443. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6444. }
  6445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6449. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6450. var depthBuffer;
  6451. // Create the depth buffer
  6452. if (generateDepthBuffer) {
  6453. depthBuffer = gl.createRenderbuffer();
  6454. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6455. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6456. }
  6457. // Create the framebuffer
  6458. var framebuffer = gl.createFramebuffer();
  6459. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6460. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6461. if (generateDepthBuffer) {
  6462. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6463. }
  6464. // Unbind
  6465. gl.bindTexture(gl.TEXTURE_2D, null);
  6466. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6467. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6468. texture._framebuffer = framebuffer;
  6469. if (generateDepthBuffer) {
  6470. texture._depthBuffer = depthBuffer;
  6471. }
  6472. texture._width = width;
  6473. texture._height = height;
  6474. texture.isReady = true;
  6475. texture.generateMipMaps = generateMipMaps;
  6476. texture.references = 1;
  6477. texture.samplingMode = samplingMode;
  6478. this._activeTexturesCache = [];
  6479. this._loadedTexturesCache.push(texture);
  6480. return texture;
  6481. };
  6482. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6483. var _this = this;
  6484. var gl = this._gl;
  6485. var texture = gl.createTexture();
  6486. texture.isCube = true;
  6487. texture.url = rootUrl;
  6488. texture.references = 1;
  6489. this._loadedTexturesCache.push(texture);
  6490. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6491. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6492. if (isDDS) {
  6493. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6494. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6495. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6496. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6497. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6498. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6499. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6500. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6501. }
  6502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6506. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6507. _this._activeTexturesCache = [];
  6508. texture._width = info.width;
  6509. texture._height = info.height;
  6510. texture.isReady = true;
  6511. }, null, null, true);
  6512. }
  6513. else {
  6514. cascadeLoad(rootUrl, scene, function (imgs) {
  6515. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6516. var height = width;
  6517. _this._prepareWorkingCanvas();
  6518. _this._workingCanvas.width = width;
  6519. _this._workingCanvas.height = height;
  6520. var faces = [
  6521. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6522. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6523. ];
  6524. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6525. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6526. for (var index = 0; index < faces.length; index++) {
  6527. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6528. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6529. }
  6530. if (!noMipmap) {
  6531. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6532. }
  6533. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6537. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6538. _this._activeTexturesCache = [];
  6539. texture._width = width;
  6540. texture._height = height;
  6541. texture.isReady = true;
  6542. }, extensions);
  6543. }
  6544. return texture;
  6545. };
  6546. Engine.prototype._releaseTexture = function (texture) {
  6547. var gl = this._gl;
  6548. if (texture._framebuffer) {
  6549. gl.deleteFramebuffer(texture._framebuffer);
  6550. }
  6551. if (texture._depthBuffer) {
  6552. gl.deleteRenderbuffer(texture._depthBuffer);
  6553. }
  6554. gl.deleteTexture(texture);
  6555. // Unbind channels
  6556. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6557. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6558. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6559. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6560. this._activeTexturesCache[channel] = null;
  6561. }
  6562. var index = this._loadedTexturesCache.indexOf(texture);
  6563. if (index !== -1) {
  6564. this._loadedTexturesCache.splice(index, 1);
  6565. }
  6566. };
  6567. Engine.prototype.bindSamplers = function (effect) {
  6568. this._gl.useProgram(effect.getProgram());
  6569. var samplers = effect.getSamplers();
  6570. for (var index = 0; index < samplers.length; index++) {
  6571. var uniform = effect.getUniform(samplers[index]);
  6572. this._gl.uniform1i(uniform, index);
  6573. }
  6574. this._currentEffect = null;
  6575. };
  6576. Engine.prototype._bindTexture = function (channel, texture) {
  6577. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6578. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6579. this._activeTexturesCache[channel] = null;
  6580. };
  6581. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6582. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6583. };
  6584. Engine.prototype.setTexture = function (channel, texture) {
  6585. if (channel < 0) {
  6586. return;
  6587. }
  6588. // Not ready?
  6589. if (!texture || !texture.isReady()) {
  6590. if (this._activeTexturesCache[channel] != null) {
  6591. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6592. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6593. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6594. this._activeTexturesCache[channel] = null;
  6595. }
  6596. return;
  6597. }
  6598. // Video
  6599. if (texture instanceof BABYLON.VideoTexture) {
  6600. if (texture.update()) {
  6601. this._activeTexturesCache[channel] = null;
  6602. }
  6603. }
  6604. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6605. texture.delayLoad();
  6606. return;
  6607. }
  6608. if (this._activeTexturesCache[channel] === texture) {
  6609. return;
  6610. }
  6611. this._activeTexturesCache[channel] = texture;
  6612. var internalTexture = texture.getInternalTexture();
  6613. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6614. if (internalTexture.isCube) {
  6615. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6616. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6617. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6618. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6619. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6620. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6621. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6622. }
  6623. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6624. }
  6625. else {
  6626. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6627. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6628. internalTexture._cachedWrapU = texture.wrapU;
  6629. switch (texture.wrapU) {
  6630. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6631. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6632. break;
  6633. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6634. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6635. break;
  6636. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6637. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6638. break;
  6639. }
  6640. }
  6641. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6642. internalTexture._cachedWrapV = texture.wrapV;
  6643. switch (texture.wrapV) {
  6644. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6645. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6646. break;
  6647. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6648. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6649. break;
  6650. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6651. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6652. break;
  6653. }
  6654. }
  6655. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6656. }
  6657. };
  6658. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6659. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6660. var value = texture.anisotropicFilteringLevel;
  6661. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6662. value = 1;
  6663. }
  6664. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6665. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6666. texture._cachedAnisotropicFilteringLevel = value;
  6667. }
  6668. };
  6669. Engine.prototype.readPixels = function (x, y, width, height) {
  6670. var data = new Uint8Array(height * width * 4);
  6671. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6672. return data;
  6673. };
  6674. // Dispose
  6675. Engine.prototype.dispose = function () {
  6676. this.hideLoadingUI();
  6677. this.stopRenderLoop();
  6678. // Release scenes
  6679. while (this.scenes.length) {
  6680. this.scenes[0].dispose();
  6681. }
  6682. // Release audio engine
  6683. Engine.audioEngine.dispose();
  6684. // Release effects
  6685. for (var name in this._compiledEffects) {
  6686. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6687. }
  6688. // Unbind
  6689. for (var i in this._vertexAttribArrays) {
  6690. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6691. continue;
  6692. }
  6693. this._gl.disableVertexAttribArray(i);
  6694. }
  6695. // Events
  6696. window.removeEventListener("blur", this._onBlur);
  6697. window.removeEventListener("focus", this._onFocus);
  6698. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6699. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6700. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6701. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6702. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6703. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6704. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6705. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6706. };
  6707. // Loading screen
  6708. Engine.prototype.displayLoadingUI = function () {
  6709. var _this = this;
  6710. this._loadingDiv = document.createElement("div");
  6711. this._loadingDiv.style.opacity = "0";
  6712. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6713. // Loading text
  6714. this._loadingTextDiv = document.createElement("div");
  6715. this._loadingTextDiv.style.position = "absolute";
  6716. this._loadingTextDiv.style.left = "0";
  6717. this._loadingTextDiv.style.top = "50%";
  6718. this._loadingTextDiv.style.marginTop = "80px";
  6719. this._loadingTextDiv.style.width = "100%";
  6720. this._loadingTextDiv.style.height = "20px";
  6721. this._loadingTextDiv.style.fontFamily = "Arial";
  6722. this._loadingTextDiv.style.fontSize = "14px";
  6723. this._loadingTextDiv.style.color = "white";
  6724. this._loadingTextDiv.style.textAlign = "center";
  6725. this._loadingTextDiv.innerHTML = "Loading";
  6726. this._loadingDiv.appendChild(this._loadingTextDiv);
  6727. // Loading img
  6728. var imgBack = new Image();
  6729. 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==";
  6730. imgBack.style.position = "absolute";
  6731. imgBack.style.left = "50%";
  6732. imgBack.style.top = "50%";
  6733. imgBack.style.marginLeft = "-50px";
  6734. imgBack.style.marginTop = "-50px";
  6735. imgBack.style.transition = "transform 1.0s ease";
  6736. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6737. var deg = 360;
  6738. var onTransitionEnd = function () {
  6739. deg += 360;
  6740. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6741. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6742. };
  6743. imgBack.addEventListener("transitionend", onTransitionEnd);
  6744. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6745. this._loadingDiv.appendChild(imgBack);
  6746. // front image
  6747. var imgFront = new Image();
  6748. 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=";
  6749. imgFront.style.position = "absolute";
  6750. imgFront.style.left = "50%";
  6751. imgFront.style.top = "50%";
  6752. imgFront.style.marginLeft = "-50px";
  6753. imgFront.style.marginTop = "-50px";
  6754. this._loadingDiv.appendChild(imgFront);
  6755. // Resize
  6756. this._resizeLoadingUI = function () {
  6757. var canvasRect = _this.getRenderingCanvasClientRect();
  6758. _this._loadingDiv.style.position = "absolute";
  6759. _this._loadingDiv.style.left = canvasRect.left + "px";
  6760. _this._loadingDiv.style.top = canvasRect.top + "px";
  6761. _this._loadingDiv.style.width = canvasRect.width + "px";
  6762. _this._loadingDiv.style.height = canvasRect.height + "px";
  6763. };
  6764. this._resizeLoadingUI();
  6765. window.addEventListener("resize", this._resizeLoadingUI);
  6766. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6767. document.body.appendChild(this._loadingDiv);
  6768. setTimeout(function () {
  6769. _this._loadingDiv.style.opacity = "1";
  6770. imgBack.style.transform = "rotateZ(360deg)";
  6771. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6772. }, 0);
  6773. };
  6774. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6775. set: function (text) {
  6776. if (!this._loadingDiv) {
  6777. return;
  6778. }
  6779. this._loadingTextDiv.innerHTML = text;
  6780. },
  6781. enumerable: true,
  6782. configurable: true
  6783. });
  6784. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6785. get: function () {
  6786. return this._loadingDivBackgroundColor;
  6787. },
  6788. set: function (color) {
  6789. this._loadingDivBackgroundColor = color;
  6790. if (!this._loadingDiv) {
  6791. return;
  6792. }
  6793. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6794. },
  6795. enumerable: true,
  6796. configurable: true
  6797. });
  6798. Engine.prototype.hideLoadingUI = function () {
  6799. var _this = this;
  6800. if (!this._loadingDiv) {
  6801. return;
  6802. }
  6803. var onTransitionEnd = function () {
  6804. if (!_this._loadingDiv) {
  6805. return;
  6806. }
  6807. document.body.removeChild(_this._loadingDiv);
  6808. window.removeEventListener("resize", _this._resizeLoadingUI);
  6809. _this._loadingDiv = null;
  6810. };
  6811. this._loadingDiv.style.opacity = "0";
  6812. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6813. };
  6814. // FPS
  6815. Engine.prototype.getFps = function () {
  6816. return this.fps;
  6817. };
  6818. Engine.prototype.getDeltaTime = function () {
  6819. return this.deltaTime;
  6820. };
  6821. Engine.prototype._measureFps = function () {
  6822. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6823. var length = this.previousFramesDuration.length;
  6824. if (length >= 2) {
  6825. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6826. }
  6827. if (length >= this.fpsRange) {
  6828. if (length > this.fpsRange) {
  6829. this.previousFramesDuration.splice(0, 1);
  6830. length = this.previousFramesDuration.length;
  6831. }
  6832. var sum = 0;
  6833. for (var id = 0; id < length - 1; id++) {
  6834. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6835. }
  6836. this.fps = 1000.0 / (sum / (length - 1));
  6837. }
  6838. };
  6839. // Statics
  6840. Engine.isSupported = function () {
  6841. try {
  6842. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6843. if (navigator.isCocoonJS) {
  6844. return true;
  6845. }
  6846. var tempcanvas = document.createElement("canvas");
  6847. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6848. return gl != null && !!window.WebGLRenderingContext;
  6849. }
  6850. catch (e) {
  6851. return false;
  6852. }
  6853. };
  6854. // Const statics
  6855. Engine._ALPHA_DISABLE = 0;
  6856. Engine._ALPHA_ADD = 1;
  6857. Engine._ALPHA_COMBINE = 2;
  6858. Engine._DELAYLOADSTATE_NONE = 0;
  6859. Engine._DELAYLOADSTATE_LOADED = 1;
  6860. Engine._DELAYLOADSTATE_LOADING = 2;
  6861. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6862. Engine._TEXTUREFORMAT_ALPHA = 0;
  6863. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6864. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6865. Engine._TEXTUREFORMAT_RGB = 4;
  6866. Engine._TEXTUREFORMAT_RGBA = 4;
  6867. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6868. Engine._TEXTURETYPE_FLOAT = 1;
  6869. // Updatable statics so stick with vars here
  6870. Engine.Epsilon = 0.001;
  6871. Engine.CollisionsEpsilon = 0.001;
  6872. Engine.CodeRepository = "Babylon/";
  6873. Engine.ShadersRepository = "Babylon/Shaders/";
  6874. return Engine;
  6875. })();
  6876. BABYLON.Engine = Engine;
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.engine.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. /**
  6882. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6883. */
  6884. var Node = (function () {
  6885. /**
  6886. * @constructor
  6887. * @param {string} name - the name and id to be given to this node
  6888. * @param {BABYLON.Scene} the scene this node will be added to
  6889. */
  6890. function Node(name, scene) {
  6891. this.state = "";
  6892. this.animations = new Array();
  6893. this._childrenFlag = -1;
  6894. this._isEnabled = true;
  6895. this._isReady = true;
  6896. this._currentRenderId = -1;
  6897. this._parentRenderId = -1;
  6898. this.name = name;
  6899. this.id = name;
  6900. this._scene = scene;
  6901. this._initCache();
  6902. }
  6903. Node.prototype.getScene = function () {
  6904. return this._scene;
  6905. };
  6906. Node.prototype.getEngine = function () {
  6907. return this._scene.getEngine();
  6908. };
  6909. // override it in derived class
  6910. Node.prototype.getWorldMatrix = function () {
  6911. return BABYLON.Matrix.Identity();
  6912. };
  6913. // override it in derived class if you add new variables to the cache
  6914. // and call the parent class method
  6915. Node.prototype._initCache = function () {
  6916. this._cache = {};
  6917. this._cache.parent = undefined;
  6918. };
  6919. Node.prototype.updateCache = function (force) {
  6920. if (!force && this.isSynchronized())
  6921. return;
  6922. this._cache.parent = this.parent;
  6923. this._updateCache();
  6924. };
  6925. // override it in derived class if you add new variables to the cache
  6926. // and call the parent class method if !ignoreParentClass
  6927. Node.prototype._updateCache = function (ignoreParentClass) {
  6928. };
  6929. // override it in derived class if you add new variables to the cache
  6930. Node.prototype._isSynchronized = function () {
  6931. return true;
  6932. };
  6933. Node.prototype._markSyncedWithParent = function () {
  6934. this._parentRenderId = this.parent._currentRenderId;
  6935. };
  6936. Node.prototype.isSynchronizedWithParent = function () {
  6937. if (!this.parent) {
  6938. return true;
  6939. }
  6940. if (this._parentRenderId !== this.parent._currentRenderId) {
  6941. return false;
  6942. }
  6943. return this.parent.isSynchronized();
  6944. };
  6945. Node.prototype.isSynchronized = function (updateCache) {
  6946. var check = this.hasNewParent();
  6947. check = check || !this.isSynchronizedWithParent();
  6948. check = check || !this._isSynchronized();
  6949. if (updateCache)
  6950. this.updateCache(true);
  6951. return !check;
  6952. };
  6953. Node.prototype.hasNewParent = function (update) {
  6954. if (this._cache.parent === this.parent)
  6955. return false;
  6956. if (update)
  6957. this._cache.parent = this.parent;
  6958. return true;
  6959. };
  6960. /**
  6961. * Is this node ready to be used/rendered
  6962. * @return {boolean} is it ready
  6963. */
  6964. Node.prototype.isReady = function () {
  6965. return this._isReady;
  6966. };
  6967. /**
  6968. * Is this node enabled.
  6969. * If the node has a parent and is enabled, the parent will be inspected as well.
  6970. * @return {boolean} whether this node (and its parent) is enabled.
  6971. * @see setEnabled
  6972. */
  6973. Node.prototype.isEnabled = function () {
  6974. if (!this._isEnabled) {
  6975. return false;
  6976. }
  6977. if (this.parent) {
  6978. return this.parent.isEnabled();
  6979. }
  6980. return true;
  6981. };
  6982. /**
  6983. * Set the enabled state of this node.
  6984. * @param {boolean} value - the new enabled state
  6985. * @see isEnabled
  6986. */
  6987. Node.prototype.setEnabled = function (value) {
  6988. this._isEnabled = value;
  6989. };
  6990. /**
  6991. * Is this node a descendant of the given node.
  6992. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6993. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6994. * @see parent
  6995. */
  6996. Node.prototype.isDescendantOf = function (ancestor) {
  6997. if (this.parent) {
  6998. if (this.parent === ancestor) {
  6999. return true;
  7000. }
  7001. return this.parent.isDescendantOf(ancestor);
  7002. }
  7003. return false;
  7004. };
  7005. Node.prototype._getDescendants = function (list, results) {
  7006. for (var index = 0; index < list.length; index++) {
  7007. var item = list[index];
  7008. if (item.isDescendantOf(this)) {
  7009. results.push(item);
  7010. }
  7011. }
  7012. };
  7013. /**
  7014. * Will return all nodes that have this node as parent.
  7015. * @return {BABYLON.Node[]} all children nodes of all types.
  7016. */
  7017. Node.prototype.getDescendants = function () {
  7018. var results = [];
  7019. this._getDescendants(this._scene.meshes, results);
  7020. this._getDescendants(this._scene.lights, results);
  7021. this._getDescendants(this._scene.cameras, results);
  7022. return results;
  7023. };
  7024. Node.prototype._setReady = function (state) {
  7025. if (state == this._isReady) {
  7026. return;
  7027. }
  7028. if (!state) {
  7029. this._isReady = false;
  7030. return;
  7031. }
  7032. this._isReady = true;
  7033. if (this.onReady) {
  7034. this.onReady(this);
  7035. }
  7036. };
  7037. return Node;
  7038. })();
  7039. BABYLON.Node = Node;
  7040. })(BABYLON || (BABYLON = {}));
  7041. //# sourceMappingURL=babylon.node.js.map
  7042. var BABYLON;
  7043. (function (BABYLON) {
  7044. var FilesInput = (function () {
  7045. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7046. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7047. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7048. this._engine = p_engine;
  7049. this._canvas = p_canvas;
  7050. this._currentScene = p_scene;
  7051. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7052. this._progressCallback = p_progressCallback;
  7053. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7054. this._textureLoadingCallback = p_textureLoadingCallback;
  7055. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7056. }
  7057. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7058. var _this = this;
  7059. if (p_elementToMonitor) {
  7060. this._elementToMonitor = p_elementToMonitor;
  7061. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7062. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7063. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7064. }
  7065. };
  7066. FilesInput.prototype.renderFunction = function () {
  7067. if (this._additionnalRenderLoopLogicCallback) {
  7068. this._additionnalRenderLoopLogicCallback();
  7069. }
  7070. if (this._currentScene) {
  7071. if (this._textureLoadingCallback) {
  7072. var remaining = this._currentScene.getWaitingItemsCount();
  7073. if (remaining > 0) {
  7074. this._textureLoadingCallback(remaining);
  7075. }
  7076. }
  7077. this._currentScene.render();
  7078. }
  7079. };
  7080. FilesInput.prototype.drag = function (e) {
  7081. e.stopPropagation();
  7082. e.preventDefault();
  7083. };
  7084. FilesInput.prototype.drop = function (eventDrop) {
  7085. eventDrop.stopPropagation();
  7086. eventDrop.preventDefault();
  7087. this.loadFiles(eventDrop);
  7088. };
  7089. FilesInput.prototype.loadFiles = function (event) {
  7090. if (this._startingProcessingFilesCallback)
  7091. this._startingProcessingFilesCallback();
  7092. // Handling data transfer via drag'n'drop
  7093. if (event && event.dataTransfer && event.dataTransfer.files) {
  7094. this._filesToLoad = event.dataTransfer.files;
  7095. }
  7096. // Handling files from input files
  7097. if (event && event.target && event.target.files) {
  7098. this._filesToLoad = event.target.files;
  7099. }
  7100. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7101. for (var i = 0; i < this._filesToLoad.length; i++) {
  7102. switch (this._filesToLoad[i].type) {
  7103. case "image/jpeg":
  7104. case "image/png":
  7105. case "image/bmp":
  7106. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7107. break;
  7108. case "image/targa":
  7109. case "image/vnd.ms-dds":
  7110. case "audio/wav":
  7111. case "audio/x-wav":
  7112. case "audio/mp3":
  7113. case "audio/mpeg":
  7114. case "audio/mpeg3":
  7115. case "audio/x-mpeg-3":
  7116. case "audio/ogg":
  7117. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7118. break;
  7119. default:
  7120. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7121. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7122. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7123. this._sceneFileToLoad = this._filesToLoad[i];
  7124. }
  7125. break;
  7126. }
  7127. }
  7128. this.reload();
  7129. }
  7130. };
  7131. FilesInput.prototype.reload = function () {
  7132. var _this = this;
  7133. var that = this;
  7134. // If a ".babylon" file has been provided
  7135. if (this._sceneFileToLoad) {
  7136. if (this._currentScene) {
  7137. this._engine.stopRenderLoop();
  7138. this._currentScene.dispose();
  7139. }
  7140. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7141. that._currentScene = newScene;
  7142. // Wait for textures and shaders to be ready
  7143. that._currentScene.executeWhenReady(function () {
  7144. // Attach camera to canvas inputs
  7145. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7146. that._currentScene.createDefaultCameraOrLight();
  7147. }
  7148. that._currentScene.activeCamera.attachControl(that._canvas);
  7149. if (that._sceneLoadedCallback) {
  7150. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7151. }
  7152. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7153. });
  7154. }, function (progress) {
  7155. if (_this._progressCallback) {
  7156. _this._progressCallback(progress);
  7157. }
  7158. });
  7159. }
  7160. else {
  7161. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7162. }
  7163. };
  7164. FilesInput.FilesTextures = new Array();
  7165. FilesInput.FilesToLoad = new Array();
  7166. return FilesInput;
  7167. })();
  7168. BABYLON.FilesInput = FilesInput;
  7169. })(BABYLON || (BABYLON = {}));
  7170. //# sourceMappingURL=babylon.filesInput.js.map
  7171. var BABYLON;
  7172. (function (BABYLON) {
  7173. var IntersectionInfo = (function () {
  7174. function IntersectionInfo(bu, bv, distance) {
  7175. this.bu = bu;
  7176. this.bv = bv;
  7177. this.distance = distance;
  7178. this.faceId = 0;
  7179. this.subMeshId = 0;
  7180. }
  7181. return IntersectionInfo;
  7182. })();
  7183. BABYLON.IntersectionInfo = IntersectionInfo;
  7184. var PickingInfo = (function () {
  7185. function PickingInfo() {
  7186. this.hit = false;
  7187. this.distance = 0;
  7188. this.pickedPoint = null;
  7189. this.pickedMesh = null;
  7190. this.bu = 0;
  7191. this.bv = 0;
  7192. this.faceId = -1;
  7193. this.subMeshId = 0;
  7194. }
  7195. // Methods
  7196. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7197. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7198. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7199. return null;
  7200. }
  7201. var indices = this.pickedMesh.getIndices();
  7202. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7203. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7204. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7205. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7206. normal0 = normal0.scale(this.bu);
  7207. normal1 = normal1.scale(this.bv);
  7208. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7209. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7210. if (useWorldCoordinates) {
  7211. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7212. }
  7213. return result;
  7214. };
  7215. PickingInfo.prototype.getTextureCoordinates = function () {
  7216. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7217. return null;
  7218. }
  7219. var indices = this.pickedMesh.getIndices();
  7220. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7221. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7222. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7223. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7224. uv0 = uv0.scale(this.bu);
  7225. uv1 = uv1.scale(this.bv);
  7226. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7227. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7228. };
  7229. return PickingInfo;
  7230. })();
  7231. BABYLON.PickingInfo = PickingInfo;
  7232. })(BABYLON || (BABYLON = {}));
  7233. //# sourceMappingURL=babylon.pickingInfo.js.map
  7234. var BABYLON;
  7235. (function (BABYLON) {
  7236. var BoundingSphere = (function () {
  7237. function BoundingSphere(minimum, maximum) {
  7238. this.minimum = minimum;
  7239. this.maximum = maximum;
  7240. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7241. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7242. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7243. this.radius = distance * 0.5;
  7244. this.centerWorld = BABYLON.Vector3.Zero();
  7245. this._update(BABYLON.Matrix.Identity());
  7246. }
  7247. // Methods
  7248. BoundingSphere.prototype._update = function (world) {
  7249. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7250. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7251. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7252. };
  7253. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7254. for (var i = 0; i < 6; i++) {
  7255. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7256. return false;
  7257. }
  7258. return true;
  7259. };
  7260. BoundingSphere.prototype.intersectsPoint = function (point) {
  7261. var x = this.centerWorld.x - point.x;
  7262. var y = this.centerWorld.y - point.y;
  7263. var z = this.centerWorld.z - point.z;
  7264. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7265. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7266. return false;
  7267. return true;
  7268. };
  7269. // Statics
  7270. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7271. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7272. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7273. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7274. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7275. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7276. return false;
  7277. return true;
  7278. };
  7279. return BoundingSphere;
  7280. })();
  7281. BABYLON.BoundingSphere = BoundingSphere;
  7282. })(BABYLON || (BABYLON = {}));
  7283. //# sourceMappingURL=babylon.boundingSphere.js.map
  7284. var BABYLON;
  7285. (function (BABYLON) {
  7286. var BoundingBox = (function () {
  7287. function BoundingBox(minimum, maximum) {
  7288. this.minimum = minimum;
  7289. this.maximum = maximum;
  7290. this.vectors = new Array();
  7291. this.vectorsWorld = new Array();
  7292. // Bounding vectors
  7293. this.vectors.push(this.minimum.clone());
  7294. this.vectors.push(this.maximum.clone());
  7295. this.vectors.push(this.minimum.clone());
  7296. this.vectors[2].x = this.maximum.x;
  7297. this.vectors.push(this.minimum.clone());
  7298. this.vectors[3].y = this.maximum.y;
  7299. this.vectors.push(this.minimum.clone());
  7300. this.vectors[4].z = this.maximum.z;
  7301. this.vectors.push(this.maximum.clone());
  7302. this.vectors[5].z = this.minimum.z;
  7303. this.vectors.push(this.maximum.clone());
  7304. this.vectors[6].x = this.minimum.x;
  7305. this.vectors.push(this.maximum.clone());
  7306. this.vectors[7].y = this.minimum.y;
  7307. // OBB
  7308. this.center = this.maximum.add(this.minimum).scale(0.5);
  7309. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7310. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7311. // World
  7312. for (var index = 0; index < this.vectors.length; index++) {
  7313. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7314. }
  7315. this.minimumWorld = BABYLON.Vector3.Zero();
  7316. this.maximumWorld = BABYLON.Vector3.Zero();
  7317. this._update(BABYLON.Matrix.Identity());
  7318. }
  7319. // Methods
  7320. BoundingBox.prototype.getWorldMatrix = function () {
  7321. return this._worldMatrix;
  7322. };
  7323. BoundingBox.prototype._update = function (world) {
  7324. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7325. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7326. for (var index = 0; index < this.vectors.length; index++) {
  7327. var v = this.vectorsWorld[index];
  7328. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7329. if (v.x < this.minimumWorld.x)
  7330. this.minimumWorld.x = v.x;
  7331. if (v.y < this.minimumWorld.y)
  7332. this.minimumWorld.y = v.y;
  7333. if (v.z < this.minimumWorld.z)
  7334. this.minimumWorld.z = v.z;
  7335. if (v.x > this.maximumWorld.x)
  7336. this.maximumWorld.x = v.x;
  7337. if (v.y > this.maximumWorld.y)
  7338. this.maximumWorld.y = v.y;
  7339. if (v.z > this.maximumWorld.z)
  7340. this.maximumWorld.z = v.z;
  7341. }
  7342. // OBB
  7343. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7344. this.center.scaleInPlace(0.5);
  7345. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7346. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7347. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7348. this._worldMatrix = world;
  7349. };
  7350. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7351. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7352. };
  7353. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7354. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7355. };
  7356. BoundingBox.prototype.intersectsPoint = function (point) {
  7357. var delta = -BABYLON.Engine.Epsilon;
  7358. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7359. return false;
  7360. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7361. return false;
  7362. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7363. return false;
  7364. return true;
  7365. };
  7366. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7367. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7368. };
  7369. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7370. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7371. return false;
  7372. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7373. return false;
  7374. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7375. return false;
  7376. return true;
  7377. };
  7378. // Statics
  7379. BoundingBox.Intersects = function (box0, box1) {
  7380. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7381. return false;
  7382. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7383. return false;
  7384. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7385. return false;
  7386. return true;
  7387. };
  7388. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7389. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7390. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7391. return (num <= (sphereRadius * sphereRadius));
  7392. };
  7393. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7394. for (var p = 0; p < 6; p++) {
  7395. for (var i = 0; i < 8; i++) {
  7396. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7397. return false;
  7398. }
  7399. }
  7400. }
  7401. return true;
  7402. };
  7403. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7404. for (var p = 0; p < 6; p++) {
  7405. var inCount = 8;
  7406. for (var i = 0; i < 8; i++) {
  7407. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7408. --inCount;
  7409. }
  7410. else {
  7411. break;
  7412. }
  7413. }
  7414. if (inCount === 0)
  7415. return false;
  7416. }
  7417. return true;
  7418. };
  7419. return BoundingBox;
  7420. })();
  7421. BABYLON.BoundingBox = BoundingBox;
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.boundingBox.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var computeBoxExtents = function (axis, box) {
  7427. var p = BABYLON.Vector3.Dot(box.center, axis);
  7428. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7429. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7430. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7431. var r = r0 + r1 + r2;
  7432. return {
  7433. min: p - r,
  7434. max: p + r
  7435. };
  7436. };
  7437. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7438. var axisOverlap = function (axis, box0, box1) {
  7439. var result0 = computeBoxExtents(axis, box0);
  7440. var result1 = computeBoxExtents(axis, box1);
  7441. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7442. };
  7443. var BoundingInfo = (function () {
  7444. function BoundingInfo(minimum, maximum) {
  7445. this.minimum = minimum;
  7446. this.maximum = maximum;
  7447. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7448. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7449. }
  7450. // Methods
  7451. BoundingInfo.prototype._update = function (world) {
  7452. this.boundingBox._update(world);
  7453. this.boundingSphere._update(world);
  7454. };
  7455. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7456. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7457. return false;
  7458. return this.boundingBox.isInFrustum(frustumPlanes);
  7459. };
  7460. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7461. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7462. };
  7463. BoundingInfo.prototype._checkCollision = function (collider) {
  7464. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7465. };
  7466. BoundingInfo.prototype.intersectsPoint = function (point) {
  7467. if (!this.boundingSphere.centerWorld) {
  7468. return false;
  7469. }
  7470. if (!this.boundingSphere.intersectsPoint(point)) {
  7471. return false;
  7472. }
  7473. if (!this.boundingBox.intersectsPoint(point)) {
  7474. return false;
  7475. }
  7476. return true;
  7477. };
  7478. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7479. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7480. return false;
  7481. }
  7482. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7483. return false;
  7484. }
  7485. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7486. return false;
  7487. }
  7488. if (!precise) {
  7489. return true;
  7490. }
  7491. var box0 = this.boundingBox;
  7492. var box1 = boundingInfo.boundingBox;
  7493. if (!axisOverlap(box0.directions[0], box0, box1))
  7494. return false;
  7495. if (!axisOverlap(box0.directions[1], box0, box1))
  7496. return false;
  7497. if (!axisOverlap(box0.directions[2], box0, box1))
  7498. return false;
  7499. if (!axisOverlap(box1.directions[0], box0, box1))
  7500. return false;
  7501. if (!axisOverlap(box1.directions[1], box0, box1))
  7502. return false;
  7503. if (!axisOverlap(box1.directions[2], box0, box1))
  7504. return false;
  7505. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7506. return false;
  7507. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7508. return false;
  7509. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7510. return false;
  7511. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7512. return false;
  7513. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7514. return false;
  7515. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7516. return false;
  7517. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7518. return false;
  7519. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7520. return false;
  7521. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7522. return false;
  7523. return true;
  7524. };
  7525. return BoundingInfo;
  7526. })();
  7527. BABYLON.BoundingInfo = BoundingInfo;
  7528. })(BABYLON || (BABYLON = {}));
  7529. //# sourceMappingURL=babylon.boundingInfo.js.map
  7530. var __extends = (this && this.__extends) || function (d, b) {
  7531. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7532. function __() { this.constructor = d; }
  7533. __.prototype = b.prototype;
  7534. d.prototype = new __();
  7535. };
  7536. var BABYLON;
  7537. (function (BABYLON) {
  7538. var AbstractMesh = (function (_super) {
  7539. __extends(AbstractMesh, _super);
  7540. function AbstractMesh(name, scene) {
  7541. var _this = this;
  7542. _super.call(this, name, scene);
  7543. // Properties
  7544. this.definedFacingForward = true; // orientation for POV movement & rotation
  7545. this.position = new BABYLON.Vector3(0, 0, 0);
  7546. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7547. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7548. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7549. this.visibility = 1.0;
  7550. this.alphaIndex = Number.MAX_VALUE;
  7551. this.infiniteDistance = false;
  7552. this.isVisible = true;
  7553. this.isPickable = true;
  7554. this.showBoundingBox = false;
  7555. this.showSubMeshesBoundingBox = false;
  7556. this.onDispose = null;
  7557. this.checkCollisions = false;
  7558. this.isBlocker = false;
  7559. this.renderingGroupId = 0;
  7560. this.receiveShadows = false;
  7561. this.renderOutline = false;
  7562. this.outlineColor = BABYLON.Color3.Red();
  7563. this.outlineWidth = 0.02;
  7564. this.renderOverlay = false;
  7565. this.overlayColor = BABYLON.Color3.Red();
  7566. this.overlayAlpha = 0.5;
  7567. this.hasVertexAlpha = false;
  7568. this.useVertexColors = true;
  7569. this.applyFog = true;
  7570. this.useOctreeForRenderingSelection = true;
  7571. this.useOctreeForPicking = true;
  7572. this.useOctreeForCollisions = true;
  7573. this.layerMask = 0x0FFFFFFF;
  7574. this.alwaysSelectAsActiveMesh = false;
  7575. // Physics
  7576. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7577. // Collisions
  7578. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7579. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7580. this._collider = new BABYLON.Collider();
  7581. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7582. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7583. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7584. // Cache
  7585. this._localScaling = BABYLON.Matrix.Zero();
  7586. this._localRotation = BABYLON.Matrix.Zero();
  7587. this._localTranslation = BABYLON.Matrix.Zero();
  7588. this._localBillboard = BABYLON.Matrix.Zero();
  7589. this._localPivotScaling = BABYLON.Matrix.Zero();
  7590. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7591. this._localWorld = BABYLON.Matrix.Zero();
  7592. this._worldMatrix = BABYLON.Matrix.Zero();
  7593. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7594. this._absolutePosition = BABYLON.Vector3.Zero();
  7595. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7596. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7597. this._isDirty = false;
  7598. this._pivotMatrix = BABYLON.Matrix.Identity();
  7599. this._isDisposed = false;
  7600. this._renderId = 0;
  7601. this._intersectionsInProgress = new Array();
  7602. this._onAfterWorldMatrixUpdate = new Array();
  7603. this._isWorldMatrixFrozen = false;
  7604. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7605. if (collidedMesh === void 0) { collidedMesh = null; }
  7606. //TODO move this to the collision coordinator!
  7607. if (_this.getScene().workerCollisions)
  7608. newPosition.multiplyInPlace(_this._collider.radius);
  7609. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7610. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7611. _this.position.addInPlace(_this._diffPositionForCollisions);
  7612. }
  7613. };
  7614. scene.addMesh(this);
  7615. }
  7616. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7617. get: function () {
  7618. return AbstractMesh._BILLBOARDMODE_NONE;
  7619. },
  7620. enumerable: true,
  7621. configurable: true
  7622. });
  7623. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7624. get: function () {
  7625. return AbstractMesh._BILLBOARDMODE_X;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7631. get: function () {
  7632. return AbstractMesh._BILLBOARDMODE_Y;
  7633. },
  7634. enumerable: true,
  7635. configurable: true
  7636. });
  7637. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7638. get: function () {
  7639. return AbstractMesh._BILLBOARDMODE_Z;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7645. get: function () {
  7646. return AbstractMesh._BILLBOARDMODE_ALL;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7652. // Methods
  7653. get: function () {
  7654. return false;
  7655. },
  7656. enumerable: true,
  7657. configurable: true
  7658. });
  7659. AbstractMesh.prototype.getLOD = function (camera) {
  7660. return this;
  7661. };
  7662. AbstractMesh.prototype.getTotalVertices = function () {
  7663. return 0;
  7664. };
  7665. AbstractMesh.prototype.getIndices = function () {
  7666. return null;
  7667. };
  7668. AbstractMesh.prototype.getVerticesData = function (kind) {
  7669. return null;
  7670. };
  7671. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7672. return false;
  7673. };
  7674. AbstractMesh.prototype.getBoundingInfo = function () {
  7675. if (this._masterMesh) {
  7676. return this._masterMesh.getBoundingInfo();
  7677. }
  7678. if (!this._boundingInfo) {
  7679. this._updateBoundingInfo();
  7680. }
  7681. return this._boundingInfo;
  7682. };
  7683. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7684. get: function () {
  7685. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7686. },
  7687. enumerable: true,
  7688. configurable: true
  7689. });
  7690. AbstractMesh.prototype._preActivate = function () {
  7691. };
  7692. AbstractMesh.prototype._activate = function (renderId) {
  7693. this._renderId = renderId;
  7694. };
  7695. AbstractMesh.prototype.getWorldMatrix = function () {
  7696. if (this._masterMesh) {
  7697. return this._masterMesh.getWorldMatrix();
  7698. }
  7699. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7700. this.computeWorldMatrix();
  7701. }
  7702. return this._worldMatrix;
  7703. };
  7704. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7705. get: function () {
  7706. return this._worldMatrix;
  7707. },
  7708. enumerable: true,
  7709. configurable: true
  7710. });
  7711. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7712. get: function () {
  7713. return this._absolutePosition;
  7714. },
  7715. enumerable: true,
  7716. configurable: true
  7717. });
  7718. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7719. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7720. this.computeWorldMatrix(true);
  7721. this._isWorldMatrixFrozen = true;
  7722. };
  7723. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7724. this._isWorldMatrixFrozen = false;
  7725. this.computeWorldMatrix(true);
  7726. };
  7727. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7728. get: function () {
  7729. return this._isWorldMatrixFrozen;
  7730. },
  7731. enumerable: true,
  7732. configurable: true
  7733. });
  7734. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7735. axis.normalize();
  7736. if (!this.rotationQuaternion) {
  7737. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7738. this.rotation = BABYLON.Vector3.Zero();
  7739. }
  7740. if (!space || space === BABYLON.Space.LOCAL) {
  7741. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7742. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7743. }
  7744. else {
  7745. if (this.parent) {
  7746. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7747. invertParentWorldMatrix.invert();
  7748. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7749. }
  7750. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7751. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7752. }
  7753. };
  7754. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7755. var displacementVector = axis.scale(distance);
  7756. if (!space || space === BABYLON.Space.LOCAL) {
  7757. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7758. this.setPositionWithLocalVector(tempV3);
  7759. }
  7760. else {
  7761. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7762. }
  7763. };
  7764. AbstractMesh.prototype.getAbsolutePosition = function () {
  7765. this.computeWorldMatrix();
  7766. return this._absolutePosition;
  7767. };
  7768. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7769. if (!absolutePosition) {
  7770. return;
  7771. }
  7772. var absolutePositionX;
  7773. var absolutePositionY;
  7774. var absolutePositionZ;
  7775. if (absolutePosition.x === undefined) {
  7776. if (arguments.length < 3) {
  7777. return;
  7778. }
  7779. absolutePositionX = arguments[0];
  7780. absolutePositionY = arguments[1];
  7781. absolutePositionZ = arguments[2];
  7782. }
  7783. else {
  7784. absolutePositionX = absolutePosition.x;
  7785. absolutePositionY = absolutePosition.y;
  7786. absolutePositionZ = absolutePosition.z;
  7787. }
  7788. if (this.parent) {
  7789. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7790. invertParentWorldMatrix.invert();
  7791. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7792. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7793. }
  7794. else {
  7795. this.position.x = absolutePositionX;
  7796. this.position.y = absolutePositionY;
  7797. this.position.z = absolutePositionZ;
  7798. }
  7799. };
  7800. // ================================== Point of View Movement =================================
  7801. /**
  7802. * Perform relative position change from the point of view of behind the front of the mesh.
  7803. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7804. * Supports definition of mesh facing forward or backward.
  7805. * @param {number} amountRight
  7806. * @param {number} amountUp
  7807. * @param {number} amountForward
  7808. */
  7809. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7810. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7811. };
  7812. /**
  7813. * Calculate relative position change from the point of view of behind the front of the mesh.
  7814. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7815. * Supports definition of mesh facing forward or backward.
  7816. * @param {number} amountRight
  7817. * @param {number} amountUp
  7818. * @param {number} amountForward
  7819. */
  7820. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7821. var rotMatrix = new BABYLON.Matrix();
  7822. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7823. rotQuaternion.toRotationMatrix(rotMatrix);
  7824. var translationDelta = BABYLON.Vector3.Zero();
  7825. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7826. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7827. return translationDelta;
  7828. };
  7829. // ================================== Point of View Rotation =================================
  7830. /**
  7831. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7832. * Supports definition of mesh facing forward or backward.
  7833. * @param {number} flipBack
  7834. * @param {number} twirlClockwise
  7835. * @param {number} tiltRight
  7836. */
  7837. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7838. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7839. };
  7840. /**
  7841. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7842. * Supports definition of mesh facing forward or backward.
  7843. * @param {number} flipBack
  7844. * @param {number} twirlClockwise
  7845. * @param {number} tiltRight
  7846. */
  7847. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7848. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7849. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7850. };
  7851. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7852. this._pivotMatrix = matrix;
  7853. this._cache.pivotMatrixUpdated = true;
  7854. };
  7855. AbstractMesh.prototype.getPivotMatrix = function () {
  7856. return this._pivotMatrix;
  7857. };
  7858. AbstractMesh.prototype._isSynchronized = function () {
  7859. if (this._isDirty) {
  7860. return false;
  7861. }
  7862. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7863. return false;
  7864. if (this._cache.pivotMatrixUpdated) {
  7865. return false;
  7866. }
  7867. if (this.infiniteDistance) {
  7868. return false;
  7869. }
  7870. if (!this._cache.position.equals(this.position))
  7871. return false;
  7872. if (this.rotationQuaternion) {
  7873. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7874. return false;
  7875. }
  7876. else {
  7877. if (!this._cache.rotation.equals(this.rotation))
  7878. return false;
  7879. }
  7880. if (!this._cache.scaling.equals(this.scaling))
  7881. return false;
  7882. return true;
  7883. };
  7884. AbstractMesh.prototype._initCache = function () {
  7885. _super.prototype._initCache.call(this);
  7886. this._cache.localMatrixUpdated = false;
  7887. this._cache.position = BABYLON.Vector3.Zero();
  7888. this._cache.scaling = BABYLON.Vector3.Zero();
  7889. this._cache.rotation = BABYLON.Vector3.Zero();
  7890. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7891. };
  7892. AbstractMesh.prototype.markAsDirty = function (property) {
  7893. if (property === "rotation") {
  7894. this.rotationQuaternion = null;
  7895. }
  7896. this._currentRenderId = Number.MAX_VALUE;
  7897. this._isDirty = true;
  7898. };
  7899. AbstractMesh.prototype._updateBoundingInfo = function () {
  7900. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7901. this._boundingInfo._update(this.worldMatrixFromCache);
  7902. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7903. };
  7904. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7905. if (!this.subMeshes) {
  7906. return;
  7907. }
  7908. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7909. var subMesh = this.subMeshes[subIndex];
  7910. subMesh.updateBoundingInfo(matrix);
  7911. }
  7912. };
  7913. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7914. if (this._isWorldMatrixFrozen) {
  7915. return this._worldMatrix;
  7916. }
  7917. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7918. return this._worldMatrix;
  7919. }
  7920. this._cache.position.copyFrom(this.position);
  7921. this._cache.scaling.copyFrom(this.scaling);
  7922. this._cache.pivotMatrixUpdated = false;
  7923. this._currentRenderId = this.getScene().getRenderId();
  7924. this._isDirty = false;
  7925. // Scaling
  7926. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7927. // Rotation
  7928. if (this.rotationQuaternion) {
  7929. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7930. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7931. }
  7932. else {
  7933. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7934. this._cache.rotation.copyFrom(this.rotation);
  7935. }
  7936. // Translation
  7937. if (this.infiniteDistance && !this.parent) {
  7938. var camera = this.getScene().activeCamera;
  7939. var cameraWorldMatrix = camera.getWorldMatrix();
  7940. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7941. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7942. }
  7943. else {
  7944. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7945. }
  7946. // Composing transformations
  7947. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7948. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7949. // Billboarding
  7950. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7951. var localPosition = this.position.clone();
  7952. var zero = this.getScene().activeCamera.globalPosition.clone();
  7953. if (this.parent && this.parent.position) {
  7954. localPosition.addInPlace(this.parent.position);
  7955. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7956. }
  7957. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7958. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7959. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7960. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7961. zero.y = localPosition.y + 0.001;
  7962. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7963. zero.z = localPosition.z + 0.001;
  7964. }
  7965. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7966. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7967. this._localBillboard.invert();
  7968. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7969. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7970. }
  7971. // Local world
  7972. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7973. // Parent
  7974. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7975. this._markSyncedWithParent();
  7976. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7977. }
  7978. else {
  7979. this._worldMatrix.copyFrom(this._localWorld);
  7980. }
  7981. // Bounding info
  7982. this._updateBoundingInfo();
  7983. // Absolute position
  7984. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7985. // Callbacks
  7986. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7987. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7988. }
  7989. return this._worldMatrix;
  7990. };
  7991. /**
  7992. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7993. * @param func: callback function to add
  7994. */
  7995. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7996. this._onAfterWorldMatrixUpdate.push(func);
  7997. };
  7998. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7999. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8000. if (index > -1) {
  8001. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8002. }
  8003. };
  8004. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8005. this.computeWorldMatrix();
  8006. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8007. };
  8008. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8009. this.computeWorldMatrix();
  8010. var invLocalWorldMatrix = this._localWorld.clone();
  8011. invLocalWorldMatrix.invert();
  8012. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8013. };
  8014. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8015. this.computeWorldMatrix(true);
  8016. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8017. };
  8018. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8019. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8020. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8021. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8022. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8023. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8024. /// <returns>Mesh oriented towards targetMesh</returns>
  8025. yawCor = yawCor || 0; // default to zero if undefined
  8026. pitchCor = pitchCor || 0;
  8027. rollCor = rollCor || 0;
  8028. var dv = targetPoint.subtract(this.position);
  8029. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8030. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8031. var pitch = Math.atan2(dv.y, len);
  8032. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8033. };
  8034. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8035. return this._boundingInfo.isInFrustum(frustumPlanes);
  8036. };
  8037. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8038. if (!camera) {
  8039. camera = this.getScene().activeCamera;
  8040. }
  8041. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8042. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8043. return false;
  8044. }
  8045. return true;
  8046. };
  8047. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8048. if (!this._boundingInfo || !mesh._boundingInfo) {
  8049. return false;
  8050. }
  8051. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8052. };
  8053. AbstractMesh.prototype.intersectsPoint = function (point) {
  8054. if (!this._boundingInfo) {
  8055. return false;
  8056. }
  8057. return this._boundingInfo.intersectsPoint(point);
  8058. };
  8059. // Physics
  8060. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8061. var physicsEngine = this.getScene().getPhysicsEngine();
  8062. if (!physicsEngine) {
  8063. return;
  8064. }
  8065. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8066. if (impostor.impostor) {
  8067. // Old API
  8068. options = impostor;
  8069. impostor = impostor.impostor;
  8070. }
  8071. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8072. physicsEngine._unregisterMesh(this);
  8073. return;
  8074. }
  8075. if (!options) {
  8076. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8077. }
  8078. else {
  8079. if (!options.mass && options.mass !== 0)
  8080. options.mass = 0;
  8081. if (!options.friction && options.friction !== 0)
  8082. options.friction = 0.2;
  8083. if (!options.restitution && options.restitution !== 0)
  8084. options.restitution = 0.2;
  8085. }
  8086. this._physicImpostor = impostor;
  8087. this._physicsMass = options.mass;
  8088. this._physicsFriction = options.friction;
  8089. this._physicRestitution = options.restitution;
  8090. return physicsEngine._registerMesh(this, impostor, options);
  8091. };
  8092. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8093. if (!this._physicImpostor) {
  8094. return BABYLON.PhysicsEngine.NoImpostor;
  8095. }
  8096. return this._physicImpostor;
  8097. };
  8098. AbstractMesh.prototype.getPhysicsMass = function () {
  8099. if (!this._physicsMass) {
  8100. return 0;
  8101. }
  8102. return this._physicsMass;
  8103. };
  8104. AbstractMesh.prototype.getPhysicsFriction = function () {
  8105. if (!this._physicsFriction) {
  8106. return 0;
  8107. }
  8108. return this._physicsFriction;
  8109. };
  8110. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8111. if (!this._physicRestitution) {
  8112. return 0;
  8113. }
  8114. return this._physicRestitution;
  8115. };
  8116. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8117. if (!camera) {
  8118. camera = this.getScene().activeCamera;
  8119. }
  8120. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8121. };
  8122. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8123. if (!camera) {
  8124. camera = this.getScene().activeCamera;
  8125. }
  8126. return this.absolutePosition.subtract(camera.position).length();
  8127. };
  8128. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8129. if (!this._physicImpostor) {
  8130. return;
  8131. }
  8132. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8133. };
  8134. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8135. if (!this._physicImpostor) {
  8136. return;
  8137. }
  8138. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8139. };
  8140. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8141. if (!this._physicImpostor) {
  8142. return;
  8143. }
  8144. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8145. };
  8146. // Collisions
  8147. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8148. var globalPosition = this.getAbsolutePosition();
  8149. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8150. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8151. this._collider.radius = this.ellipsoid;
  8152. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8153. };
  8154. // Submeshes octree
  8155. /**
  8156. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8157. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8158. */
  8159. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8160. if (maxCapacity === void 0) { maxCapacity = 64; }
  8161. if (maxDepth === void 0) { maxDepth = 2; }
  8162. if (!this._submeshesOctree) {
  8163. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8164. }
  8165. this.computeWorldMatrix(true);
  8166. // Update octree
  8167. var bbox = this.getBoundingInfo().boundingBox;
  8168. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8169. return this._submeshesOctree;
  8170. };
  8171. // Collisions
  8172. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8173. this._generatePointsArray();
  8174. // Transformation
  8175. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8176. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8177. subMesh._lastColliderWorldVertices = [];
  8178. subMesh._trianglePlanes = [];
  8179. var start = subMesh.verticesStart;
  8180. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8181. for (var i = start; i < end; i++) {
  8182. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8183. }
  8184. }
  8185. // Collide
  8186. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8187. if (collider.collisionFound) {
  8188. collider.collidedMesh = this;
  8189. }
  8190. };
  8191. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8192. var subMeshes;
  8193. var len;
  8194. // Octrees
  8195. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8196. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8197. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8198. len = intersections.length;
  8199. subMeshes = intersections.data;
  8200. }
  8201. else {
  8202. subMeshes = this.subMeshes;
  8203. len = subMeshes.length;
  8204. }
  8205. for (var index = 0; index < len; index++) {
  8206. var subMesh = subMeshes[index];
  8207. // Bounding test
  8208. if (len > 1 && !subMesh._checkCollision(collider))
  8209. continue;
  8210. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8211. }
  8212. };
  8213. AbstractMesh.prototype._checkCollision = function (collider) {
  8214. // Bounding box test
  8215. if (!this._boundingInfo._checkCollision(collider))
  8216. return;
  8217. // Transformation matrix
  8218. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8219. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8220. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8221. };
  8222. // Picking
  8223. AbstractMesh.prototype._generatePointsArray = function () {
  8224. return false;
  8225. };
  8226. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8227. var pickingInfo = new BABYLON.PickingInfo();
  8228. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8229. return pickingInfo;
  8230. }
  8231. if (!this._generatePointsArray()) {
  8232. return pickingInfo;
  8233. }
  8234. var intersectInfo = null;
  8235. // Octrees
  8236. var subMeshes;
  8237. var len;
  8238. if (this._submeshesOctree && this.useOctreeForPicking) {
  8239. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8240. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8241. len = intersections.length;
  8242. subMeshes = intersections.data;
  8243. }
  8244. else {
  8245. subMeshes = this.subMeshes;
  8246. len = subMeshes.length;
  8247. }
  8248. for (var index = 0; index < len; index++) {
  8249. var subMesh = subMeshes[index];
  8250. // Bounding test
  8251. if (len > 1 && !subMesh.canIntersects(ray))
  8252. continue;
  8253. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8254. if (currentIntersectInfo) {
  8255. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8256. intersectInfo = currentIntersectInfo;
  8257. intersectInfo.subMeshId = index;
  8258. if (fastCheck) {
  8259. break;
  8260. }
  8261. }
  8262. }
  8263. }
  8264. if (intersectInfo) {
  8265. // Get picked point
  8266. var world = this.getWorldMatrix();
  8267. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8268. var direction = ray.direction.clone();
  8269. direction = direction.scale(intersectInfo.distance);
  8270. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8271. var pickedPoint = worldOrigin.add(worldDirection);
  8272. // Return result
  8273. pickingInfo.hit = true;
  8274. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8275. pickingInfo.pickedPoint = pickedPoint;
  8276. pickingInfo.pickedMesh = this;
  8277. pickingInfo.bu = intersectInfo.bu;
  8278. pickingInfo.bv = intersectInfo.bv;
  8279. pickingInfo.faceId = intersectInfo.faceId;
  8280. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8281. return pickingInfo;
  8282. }
  8283. return pickingInfo;
  8284. };
  8285. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8286. return null;
  8287. };
  8288. AbstractMesh.prototype.releaseSubMeshes = function () {
  8289. if (this.subMeshes) {
  8290. while (this.subMeshes.length) {
  8291. this.subMeshes[0].dispose();
  8292. }
  8293. }
  8294. else {
  8295. this.subMeshes = new Array();
  8296. }
  8297. };
  8298. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8299. var index;
  8300. // Physics
  8301. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8302. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8303. }
  8304. // Intersections in progress
  8305. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8306. var other = this._intersectionsInProgress[index];
  8307. var pos = other._intersectionsInProgress.indexOf(this);
  8308. other._intersectionsInProgress.splice(pos, 1);
  8309. }
  8310. this._intersectionsInProgress = [];
  8311. // SubMeshes
  8312. this.releaseSubMeshes();
  8313. // Remove from scene
  8314. this.getScene().removeMesh(this);
  8315. if (!doNotRecurse) {
  8316. // Particles
  8317. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8318. if (this.getScene().particleSystems[index].emitter === this) {
  8319. this.getScene().particleSystems[index].dispose();
  8320. index--;
  8321. }
  8322. }
  8323. // Children
  8324. var objects = this.getScene().meshes.slice(0);
  8325. for (index = 0; index < objects.length; index++) {
  8326. if (objects[index].parent === this) {
  8327. objects[index].dispose();
  8328. }
  8329. }
  8330. }
  8331. else {
  8332. for (index = 0; index < this.getScene().meshes.length; index++) {
  8333. var obj = this.getScene().meshes[index];
  8334. if (obj.parent === this) {
  8335. obj.parent = null;
  8336. obj.computeWorldMatrix(true);
  8337. }
  8338. }
  8339. }
  8340. this._onAfterWorldMatrixUpdate = [];
  8341. this._isDisposed = true;
  8342. // Callback
  8343. if (this.onDispose) {
  8344. this.onDispose();
  8345. }
  8346. };
  8347. // Statics
  8348. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8349. AbstractMesh._BILLBOARDMODE_X = 1;
  8350. AbstractMesh._BILLBOARDMODE_Y = 2;
  8351. AbstractMesh._BILLBOARDMODE_Z = 4;
  8352. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8353. return AbstractMesh;
  8354. })(BABYLON.Node);
  8355. BABYLON.AbstractMesh = AbstractMesh;
  8356. })(BABYLON || (BABYLON = {}));
  8357. //# sourceMappingURL=babylon.abstractMesh.js.map
  8358. var __extends = (this && this.__extends) || function (d, b) {
  8359. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8360. function __() { this.constructor = d; }
  8361. __.prototype = b.prototype;
  8362. d.prototype = new __();
  8363. };
  8364. var BABYLON;
  8365. (function (BABYLON) {
  8366. var Light = (function (_super) {
  8367. __extends(Light, _super);
  8368. function Light(name, scene) {
  8369. _super.call(this, name, scene);
  8370. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8371. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8372. this.intensity = 1.0;
  8373. this.range = Number.MAX_VALUE;
  8374. this.includeOnlyWithLayerMask = 0;
  8375. this.includedOnlyMeshes = new Array();
  8376. this.excludedMeshes = new Array();
  8377. this.excludeWithLayerMask = 0;
  8378. this._excludedMeshesIds = new Array();
  8379. this._includedOnlyMeshesIds = new Array();
  8380. scene.addLight(this);
  8381. }
  8382. Light.prototype.getShadowGenerator = function () {
  8383. return this._shadowGenerator;
  8384. };
  8385. Light.prototype.getAbsolutePosition = function () {
  8386. return BABYLON.Vector3.Zero();
  8387. };
  8388. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8389. };
  8390. Light.prototype._getWorldMatrix = function () {
  8391. return BABYLON.Matrix.Identity();
  8392. };
  8393. Light.prototype.canAffectMesh = function (mesh) {
  8394. if (!mesh) {
  8395. return true;
  8396. }
  8397. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8398. return false;
  8399. }
  8400. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8401. return false;
  8402. }
  8403. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8404. return false;
  8405. }
  8406. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8407. return false;
  8408. }
  8409. return true;
  8410. };
  8411. Light.prototype.getWorldMatrix = function () {
  8412. this._currentRenderId = this.getScene().getRenderId();
  8413. var worldMatrix = this._getWorldMatrix();
  8414. if (this.parent && this.parent.getWorldMatrix) {
  8415. if (!this._parentedWorldMatrix) {
  8416. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8417. }
  8418. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8419. this._markSyncedWithParent();
  8420. return this._parentedWorldMatrix;
  8421. }
  8422. return worldMatrix;
  8423. };
  8424. Light.prototype.dispose = function () {
  8425. if (this._shadowGenerator) {
  8426. this._shadowGenerator.dispose();
  8427. this._shadowGenerator = null;
  8428. }
  8429. // Remove from scene
  8430. this.getScene().removeLight(this);
  8431. };
  8432. return Light;
  8433. })(BABYLON.Node);
  8434. BABYLON.Light = Light;
  8435. })(BABYLON || (BABYLON = {}));
  8436. //# sourceMappingURL=babylon.light.js.map
  8437. var __extends = (this && this.__extends) || function (d, b) {
  8438. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8439. function __() { this.constructor = d; }
  8440. __.prototype = b.prototype;
  8441. d.prototype = new __();
  8442. };
  8443. var BABYLON;
  8444. (function (BABYLON) {
  8445. var PointLight = (function (_super) {
  8446. __extends(PointLight, _super);
  8447. function PointLight(name, position, scene) {
  8448. _super.call(this, name, scene);
  8449. this.position = position;
  8450. }
  8451. PointLight.prototype.getAbsolutePosition = function () {
  8452. return this._transformedPosition ? this._transformedPosition : this.position;
  8453. };
  8454. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8455. if (this.parent && this.parent.getWorldMatrix) {
  8456. if (!this._transformedPosition) {
  8457. this._transformedPosition = BABYLON.Vector3.Zero();
  8458. }
  8459. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8460. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8461. return;
  8462. }
  8463. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8464. };
  8465. PointLight.prototype.getShadowGenerator = function () {
  8466. return null;
  8467. };
  8468. PointLight.prototype._getWorldMatrix = function () {
  8469. if (!this._worldMatrix) {
  8470. this._worldMatrix = BABYLON.Matrix.Identity();
  8471. }
  8472. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8473. return this._worldMatrix;
  8474. };
  8475. return PointLight;
  8476. })(BABYLON.Light);
  8477. BABYLON.PointLight = PointLight;
  8478. })(BABYLON || (BABYLON = {}));
  8479. //# sourceMappingURL=babylon.pointLight.js.map
  8480. var __extends = (this && this.__extends) || function (d, b) {
  8481. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8482. function __() { this.constructor = d; }
  8483. __.prototype = b.prototype;
  8484. d.prototype = new __();
  8485. };
  8486. var BABYLON;
  8487. (function (BABYLON) {
  8488. var SpotLight = (function (_super) {
  8489. __extends(SpotLight, _super);
  8490. function SpotLight(name, position, direction, angle, exponent, scene) {
  8491. _super.call(this, name, scene);
  8492. this.position = position;
  8493. this.direction = direction;
  8494. this.angle = angle;
  8495. this.exponent = exponent;
  8496. }
  8497. SpotLight.prototype.getAbsolutePosition = function () {
  8498. return this.transformedPosition ? this.transformedPosition : this.position;
  8499. };
  8500. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8501. var activeCamera = this.getScene().activeCamera;
  8502. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8503. };
  8504. SpotLight.prototype.supportsVSM = function () {
  8505. return true;
  8506. };
  8507. SpotLight.prototype.needRefreshPerFrame = function () {
  8508. return false;
  8509. };
  8510. SpotLight.prototype.setDirectionToTarget = function (target) {
  8511. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8512. return this.direction;
  8513. };
  8514. SpotLight.prototype.computeTransformedPosition = function () {
  8515. if (this.parent && this.parent.getWorldMatrix) {
  8516. if (!this.transformedPosition) {
  8517. this.transformedPosition = BABYLON.Vector3.Zero();
  8518. }
  8519. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8520. return true;
  8521. }
  8522. return false;
  8523. };
  8524. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8525. var normalizeDirection;
  8526. if (this.parent && this.parent.getWorldMatrix) {
  8527. if (!this._transformedDirection) {
  8528. this._transformedDirection = BABYLON.Vector3.Zero();
  8529. }
  8530. this.computeTransformedPosition();
  8531. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8532. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8533. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8534. }
  8535. else {
  8536. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8537. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8538. }
  8539. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8540. };
  8541. SpotLight.prototype._getWorldMatrix = function () {
  8542. if (!this._worldMatrix) {
  8543. this._worldMatrix = BABYLON.Matrix.Identity();
  8544. }
  8545. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8546. return this._worldMatrix;
  8547. };
  8548. return SpotLight;
  8549. })(BABYLON.Light);
  8550. BABYLON.SpotLight = SpotLight;
  8551. })(BABYLON || (BABYLON = {}));
  8552. //# sourceMappingURL=babylon.spotLight.js.map
  8553. var __extends = (this && this.__extends) || function (d, b) {
  8554. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8555. function __() { this.constructor = d; }
  8556. __.prototype = b.prototype;
  8557. d.prototype = new __();
  8558. };
  8559. var BABYLON;
  8560. (function (BABYLON) {
  8561. var HemisphericLight = (function (_super) {
  8562. __extends(HemisphericLight, _super);
  8563. function HemisphericLight(name, direction, scene) {
  8564. _super.call(this, name, scene);
  8565. this.direction = direction;
  8566. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8567. }
  8568. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8569. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8570. return this.direction;
  8571. };
  8572. HemisphericLight.prototype.getShadowGenerator = function () {
  8573. return null;
  8574. };
  8575. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8576. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8577. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8578. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8579. };
  8580. HemisphericLight.prototype._getWorldMatrix = function () {
  8581. if (!this._worldMatrix) {
  8582. this._worldMatrix = BABYLON.Matrix.Identity();
  8583. }
  8584. return this._worldMatrix;
  8585. };
  8586. return HemisphericLight;
  8587. })(BABYLON.Light);
  8588. BABYLON.HemisphericLight = HemisphericLight;
  8589. })(BABYLON || (BABYLON = {}));
  8590. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8591. var __extends = (this && this.__extends) || function (d, b) {
  8592. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8593. function __() { this.constructor = d; }
  8594. __.prototype = b.prototype;
  8595. d.prototype = new __();
  8596. };
  8597. var BABYLON;
  8598. (function (BABYLON) {
  8599. var DirectionalLight = (function (_super) {
  8600. __extends(DirectionalLight, _super);
  8601. function DirectionalLight(name, direction, scene) {
  8602. _super.call(this, name, scene);
  8603. this.direction = direction;
  8604. this.shadowOrthoScale = 0.5;
  8605. this.position = direction.scale(-1);
  8606. }
  8607. DirectionalLight.prototype.getAbsolutePosition = function () {
  8608. return this.transformedPosition ? this.transformedPosition : this.position;
  8609. };
  8610. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8611. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8612. return this.direction;
  8613. };
  8614. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8615. var orthoLeft = Number.MAX_VALUE;
  8616. var orthoRight = Number.MIN_VALUE;
  8617. var orthoTop = Number.MIN_VALUE;
  8618. var orthoBottom = Number.MAX_VALUE;
  8619. var tempVector3 = BABYLON.Vector3.Zero();
  8620. var activeCamera = this.getScene().activeCamera;
  8621. // Check extends
  8622. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8623. var mesh = renderList[meshIndex];
  8624. if (!mesh) {
  8625. continue;
  8626. }
  8627. var boundingInfo = mesh.getBoundingInfo();
  8628. if (!boundingInfo) {
  8629. continue;
  8630. }
  8631. var boundingBox = boundingInfo.boundingBox;
  8632. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8633. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8634. if (tempVector3.x < orthoLeft)
  8635. orthoLeft = tempVector3.x;
  8636. if (tempVector3.y < orthoBottom)
  8637. orthoBottom = tempVector3.y;
  8638. if (tempVector3.x > orthoRight)
  8639. orthoRight = tempVector3.x;
  8640. if (tempVector3.y > orthoTop)
  8641. orthoTop = tempVector3.y;
  8642. }
  8643. }
  8644. var xOffset = orthoRight - orthoLeft;
  8645. var yOffset = orthoTop - orthoBottom;
  8646. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8647. };
  8648. DirectionalLight.prototype.supportsVSM = function () {
  8649. return true;
  8650. };
  8651. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8652. return true;
  8653. };
  8654. DirectionalLight.prototype.computeTransformedPosition = function () {
  8655. if (this.parent && this.parent.getWorldMatrix) {
  8656. if (!this.transformedPosition) {
  8657. this.transformedPosition = BABYLON.Vector3.Zero();
  8658. }
  8659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8660. return true;
  8661. }
  8662. return false;
  8663. };
  8664. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8665. if (this.parent && this.parent.getWorldMatrix) {
  8666. if (!this._transformedDirection) {
  8667. this._transformedDirection = BABYLON.Vector3.Zero();
  8668. }
  8669. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8670. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8671. return;
  8672. }
  8673. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8674. };
  8675. DirectionalLight.prototype._getWorldMatrix = function () {
  8676. if (!this._worldMatrix) {
  8677. this._worldMatrix = BABYLON.Matrix.Identity();
  8678. }
  8679. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8680. return this._worldMatrix;
  8681. };
  8682. return DirectionalLight;
  8683. })(BABYLON.Light);
  8684. BABYLON.DirectionalLight = DirectionalLight;
  8685. })(BABYLON || (BABYLON = {}));
  8686. //# sourceMappingURL=babylon.directionalLight.js.map
  8687. var BABYLON;
  8688. (function (BABYLON) {
  8689. var ShadowGenerator = (function () {
  8690. function ShadowGenerator(mapSize, light) {
  8691. var _this = this;
  8692. // Members
  8693. this._filter = ShadowGenerator.FILTER_NONE;
  8694. this.blurScale = 2;
  8695. this._blurBoxOffset = 0;
  8696. this._bias = 0.00005;
  8697. this._darkness = 0;
  8698. this._transparencyShadow = false;
  8699. this._viewMatrix = BABYLON.Matrix.Zero();
  8700. this._projectionMatrix = BABYLON.Matrix.Zero();
  8701. this._transformMatrix = BABYLON.Matrix.Zero();
  8702. this._worldViewProjection = BABYLON.Matrix.Zero();
  8703. this._light = light;
  8704. this._scene = light.getScene();
  8705. this._mapSize = mapSize;
  8706. light._shadowGenerator = this;
  8707. // Render target
  8708. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8709. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8710. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8711. this._shadowMap.anisotropicFilteringLevel = 1;
  8712. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8713. this._shadowMap.renderParticles = false;
  8714. this._shadowMap.onAfterUnbind = function () {
  8715. if (!_this.useBlurVarianceShadowMap) {
  8716. return;
  8717. }
  8718. if (!_this._shadowMap2) {
  8719. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8720. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8721. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8722. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8723. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8724. _this._downSamplePostprocess.onApply = function (effect) {
  8725. effect.setTexture("textureSampler", _this._shadowMap);
  8726. };
  8727. _this.blurBoxOffset = 1;
  8728. }
  8729. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8730. };
  8731. // Custom render function
  8732. var renderSubMesh = function (subMesh) {
  8733. var mesh = subMesh.getRenderingMesh();
  8734. var scene = _this._scene;
  8735. var engine = scene.getEngine();
  8736. // Culling
  8737. engine.setState(subMesh.getMaterial().backFaceCulling);
  8738. // Managing instances
  8739. var batch = mesh._getInstancesRenderList(subMesh._id);
  8740. if (batch.mustReturn) {
  8741. return;
  8742. }
  8743. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8744. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8745. engine.enableEffect(_this._effect);
  8746. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8747. var material = subMesh.getMaterial();
  8748. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8749. // Alpha test
  8750. if (material && material.needAlphaTesting()) {
  8751. var alphaTexture = material.getAlphaTestTexture();
  8752. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8753. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8754. }
  8755. // Bones
  8756. if (mesh.useBones) {
  8757. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8758. }
  8759. // Draw
  8760. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8761. }
  8762. else {
  8763. // Need to reset refresh rate of the shadowMap
  8764. _this._shadowMap.resetRefreshCounter();
  8765. }
  8766. };
  8767. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8768. var index;
  8769. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8770. renderSubMesh(opaqueSubMeshes.data[index]);
  8771. }
  8772. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8773. renderSubMesh(alphaTestSubMeshes.data[index]);
  8774. }
  8775. if (_this._transparencyShadow) {
  8776. for (index = 0; index < transparentSubMeshes.length; index++) {
  8777. renderSubMesh(transparentSubMeshes.data[index]);
  8778. }
  8779. }
  8780. };
  8781. this._shadowMap.onClear = function (engine) {
  8782. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8783. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8784. }
  8785. else {
  8786. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8787. }
  8788. };
  8789. }
  8790. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8791. // Static
  8792. get: function () {
  8793. return ShadowGenerator._FILTER_NONE;
  8794. },
  8795. enumerable: true,
  8796. configurable: true
  8797. });
  8798. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8799. get: function () {
  8800. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8801. },
  8802. enumerable: true,
  8803. configurable: true
  8804. });
  8805. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8806. get: function () {
  8807. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8808. },
  8809. enumerable: true,
  8810. configurable: true
  8811. });
  8812. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8813. get: function () {
  8814. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8815. },
  8816. enumerable: true,
  8817. configurable: true
  8818. });
  8819. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8820. get: function () {
  8821. return this._bias;
  8822. },
  8823. set: function (bias) {
  8824. this._bias = bias;
  8825. },
  8826. enumerable: true,
  8827. configurable: true
  8828. });
  8829. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8830. get: function () {
  8831. return this._blurBoxOffset;
  8832. },
  8833. set: function (value) {
  8834. var _this = this;
  8835. if (this._blurBoxOffset === value) {
  8836. return;
  8837. }
  8838. this._blurBoxOffset = value;
  8839. if (this._boxBlurPostprocess) {
  8840. this._boxBlurPostprocess.dispose();
  8841. }
  8842. 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);
  8843. this._boxBlurPostprocess.onApply = function (effect) {
  8844. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8845. };
  8846. },
  8847. enumerable: true,
  8848. configurable: true
  8849. });
  8850. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8851. get: function () {
  8852. return this._filter;
  8853. },
  8854. set: function (value) {
  8855. if (this._filter === value) {
  8856. return;
  8857. }
  8858. this._filter = value;
  8859. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8860. this._shadowMap.anisotropicFilteringLevel = 16;
  8861. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8862. }
  8863. else {
  8864. this._shadowMap.anisotropicFilteringLevel = 1;
  8865. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8866. }
  8867. },
  8868. enumerable: true,
  8869. configurable: true
  8870. });
  8871. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8872. get: function () {
  8873. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8874. },
  8875. set: function (value) {
  8876. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8877. },
  8878. enumerable: true,
  8879. configurable: true
  8880. });
  8881. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8882. get: function () {
  8883. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8884. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8885. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8886. },
  8887. set: function (value) {
  8888. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8889. },
  8890. enumerable: true,
  8891. configurable: true
  8892. });
  8893. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8894. get: function () {
  8895. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8896. },
  8897. set: function (value) {
  8898. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8899. },
  8900. enumerable: true,
  8901. configurable: true
  8902. });
  8903. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8904. var defines = [];
  8905. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8906. defines.push("#define VSM");
  8907. }
  8908. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8909. var mesh = subMesh.getMesh();
  8910. var material = subMesh.getMaterial();
  8911. // Alpha test
  8912. if (material && material.needAlphaTesting()) {
  8913. defines.push("#define ALPHATEST");
  8914. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8915. attribs.push(BABYLON.VertexBuffer.UVKind);
  8916. defines.push("#define UV1");
  8917. }
  8918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8919. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8920. defines.push("#define UV2");
  8921. }
  8922. }
  8923. // Bones
  8924. if (mesh.useBones) {
  8925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8927. defines.push("#define BONES");
  8928. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8929. }
  8930. // Instances
  8931. if (useInstances) {
  8932. defines.push("#define INSTANCES");
  8933. attribs.push("world0");
  8934. attribs.push("world1");
  8935. attribs.push("world2");
  8936. attribs.push("world3");
  8937. }
  8938. // Get correct effect
  8939. var join = defines.join("\n");
  8940. if (this._cachedDefines !== join) {
  8941. this._cachedDefines = join;
  8942. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8943. }
  8944. return this._effect.isReady();
  8945. };
  8946. ShadowGenerator.prototype.getShadowMap = function () {
  8947. return this._shadowMap;
  8948. };
  8949. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8950. if (this._shadowMap2) {
  8951. return this._shadowMap2;
  8952. }
  8953. return this._shadowMap;
  8954. };
  8955. ShadowGenerator.prototype.getLight = function () {
  8956. return this._light;
  8957. };
  8958. // Methods
  8959. ShadowGenerator.prototype.getTransformMatrix = function () {
  8960. var scene = this._scene;
  8961. if (this._currentRenderID === scene.getRenderId()) {
  8962. return this._transformMatrix;
  8963. }
  8964. this._currentRenderID = scene.getRenderId();
  8965. var lightPosition = this._light.position;
  8966. var lightDirection = this._light.direction;
  8967. if (this._light.computeTransformedPosition()) {
  8968. lightPosition = this._light.transformedPosition;
  8969. }
  8970. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8971. this._cachedPosition = lightPosition.clone();
  8972. this._cachedDirection = lightDirection.clone();
  8973. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8974. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8975. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8976. }
  8977. return this._transformMatrix;
  8978. };
  8979. ShadowGenerator.prototype.getDarkness = function () {
  8980. return this._darkness;
  8981. };
  8982. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8983. if (darkness >= 1.0)
  8984. this._darkness = 1.0;
  8985. else if (darkness <= 0.0)
  8986. this._darkness = 0.0;
  8987. else
  8988. this._darkness = darkness;
  8989. };
  8990. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8991. this._transparencyShadow = hasShadow;
  8992. };
  8993. ShadowGenerator.prototype._packHalf = function (depth) {
  8994. var scale = depth * 255.0;
  8995. var fract = scale - Math.floor(scale);
  8996. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8997. };
  8998. ShadowGenerator.prototype.dispose = function () {
  8999. this._shadowMap.dispose();
  9000. if (this._shadowMap2) {
  9001. this._shadowMap2.dispose();
  9002. }
  9003. if (this._downSamplePostprocess) {
  9004. this._downSamplePostprocess.dispose();
  9005. }
  9006. if (this._boxBlurPostprocess) {
  9007. this._boxBlurPostprocess.dispose();
  9008. }
  9009. };
  9010. ShadowGenerator._FILTER_NONE = 0;
  9011. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9012. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9013. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9014. return ShadowGenerator;
  9015. })();
  9016. BABYLON.ShadowGenerator = ShadowGenerator;
  9017. })(BABYLON || (BABYLON = {}));
  9018. //# sourceMappingURL=babylon.shadowGenerator.js.map
  9019. var BABYLON;
  9020. (function (BABYLON) {
  9021. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9022. if (boxMin.x > sphereCenter.x + sphereRadius)
  9023. return false;
  9024. if (sphereCenter.x - sphereRadius > boxMax.x)
  9025. return false;
  9026. if (boxMin.y > sphereCenter.y + sphereRadius)
  9027. return false;
  9028. if (sphereCenter.y - sphereRadius > boxMax.y)
  9029. return false;
  9030. if (boxMin.z > sphereCenter.z + sphereRadius)
  9031. return false;
  9032. if (sphereCenter.z - sphereRadius > boxMax.z)
  9033. return false;
  9034. return true;
  9035. };
  9036. var getLowestRoot = function (a, b, c, maxR) {
  9037. var determinant = b * b - 4.0 * a * c;
  9038. var result = { root: 0, found: false };
  9039. if (determinant < 0)
  9040. return result;
  9041. var sqrtD = Math.sqrt(determinant);
  9042. var r1 = (-b - sqrtD) / (2.0 * a);
  9043. var r2 = (-b + sqrtD) / (2.0 * a);
  9044. if (r1 > r2) {
  9045. var temp = r2;
  9046. r2 = r1;
  9047. r1 = temp;
  9048. }
  9049. if (r1 > 0 && r1 < maxR) {
  9050. result.root = r1;
  9051. result.found = true;
  9052. return result;
  9053. }
  9054. if (r2 > 0 && r2 < maxR) {
  9055. result.root = r2;
  9056. result.found = true;
  9057. return result;
  9058. }
  9059. return result;
  9060. };
  9061. var Collider = (function () {
  9062. function Collider() {
  9063. this.radius = new BABYLON.Vector3(1, 1, 1);
  9064. this.retry = 0;
  9065. this.basePointWorld = BABYLON.Vector3.Zero();
  9066. this.velocityWorld = BABYLON.Vector3.Zero();
  9067. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9068. this._collisionPoint = BABYLON.Vector3.Zero();
  9069. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9070. this._tempVector = BABYLON.Vector3.Zero();
  9071. this._tempVector2 = BABYLON.Vector3.Zero();
  9072. this._tempVector3 = BABYLON.Vector3.Zero();
  9073. this._tempVector4 = BABYLON.Vector3.Zero();
  9074. this._edge = BABYLON.Vector3.Zero();
  9075. this._baseToVertex = BABYLON.Vector3.Zero();
  9076. this._destinationPoint = BABYLON.Vector3.Zero();
  9077. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9078. this._displacementVector = BABYLON.Vector3.Zero();
  9079. }
  9080. // Methods
  9081. Collider.prototype._initialize = function (source, dir, e) {
  9082. this.velocity = dir;
  9083. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9084. this.basePoint = source;
  9085. source.multiplyToRef(this.radius, this.basePointWorld);
  9086. dir.multiplyToRef(this.radius, this.velocityWorld);
  9087. this.velocityWorldLength = this.velocityWorld.length();
  9088. this.epsilon = e;
  9089. this.collisionFound = false;
  9090. };
  9091. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9092. pa.subtractToRef(point, this._tempVector);
  9093. pb.subtractToRef(point, this._tempVector2);
  9094. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9095. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9096. if (d < 0)
  9097. return false;
  9098. pc.subtractToRef(point, this._tempVector3);
  9099. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9100. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9101. if (d < 0)
  9102. return false;
  9103. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9104. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9105. return d >= 0;
  9106. };
  9107. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9108. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9109. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9110. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9111. return false;
  9112. }
  9113. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9114. return false;
  9115. return true;
  9116. };
  9117. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9118. var t0;
  9119. var embeddedInPlane = false;
  9120. //defensive programming, actually not needed.
  9121. if (!trianglePlaneArray) {
  9122. trianglePlaneArray = [];
  9123. }
  9124. if (!trianglePlaneArray[faceIndex]) {
  9125. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9126. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9127. }
  9128. var trianglePlane = trianglePlaneArray[faceIndex];
  9129. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9130. return;
  9131. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9132. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9133. if (normalDotVelocity == 0) {
  9134. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9135. return;
  9136. embeddedInPlane = true;
  9137. t0 = 0;
  9138. }
  9139. else {
  9140. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9141. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9142. if (t0 > t1) {
  9143. var temp = t1;
  9144. t1 = t0;
  9145. t0 = temp;
  9146. }
  9147. if (t0 > 1.0 || t1 < 0.0)
  9148. return;
  9149. if (t0 < 0)
  9150. t0 = 0;
  9151. if (t0 > 1.0)
  9152. t0 = 1.0;
  9153. }
  9154. this._collisionPoint.copyFromFloats(0, 0, 0);
  9155. var found = false;
  9156. var t = 1.0;
  9157. if (!embeddedInPlane) {
  9158. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9159. this.velocity.scaleToRef(t0, this._tempVector);
  9160. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9161. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9162. found = true;
  9163. t = t0;
  9164. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9165. }
  9166. }
  9167. if (!found) {
  9168. var velocitySquaredLength = this.velocity.lengthSquared();
  9169. var a = velocitySquaredLength;
  9170. this.basePoint.subtractToRef(p1, this._tempVector);
  9171. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9172. var c = this._tempVector.lengthSquared() - 1.0;
  9173. var lowestRoot = getLowestRoot(a, b, c, t);
  9174. if (lowestRoot.found) {
  9175. t = lowestRoot.root;
  9176. found = true;
  9177. this._collisionPoint.copyFrom(p1);
  9178. }
  9179. this.basePoint.subtractToRef(p2, this._tempVector);
  9180. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9181. c = this._tempVector.lengthSquared() - 1.0;
  9182. lowestRoot = getLowestRoot(a, b, c, t);
  9183. if (lowestRoot.found) {
  9184. t = lowestRoot.root;
  9185. found = true;
  9186. this._collisionPoint.copyFrom(p2);
  9187. }
  9188. this.basePoint.subtractToRef(p3, this._tempVector);
  9189. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9190. c = this._tempVector.lengthSquared() - 1.0;
  9191. lowestRoot = getLowestRoot(a, b, c, t);
  9192. if (lowestRoot.found) {
  9193. t = lowestRoot.root;
  9194. found = true;
  9195. this._collisionPoint.copyFrom(p3);
  9196. }
  9197. p2.subtractToRef(p1, this._edge);
  9198. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9199. var edgeSquaredLength = this._edge.lengthSquared();
  9200. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9201. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9202. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9203. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9204. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9205. lowestRoot = getLowestRoot(a, b, c, t);
  9206. if (lowestRoot.found) {
  9207. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9208. if (f >= 0.0 && f <= 1.0) {
  9209. t = lowestRoot.root;
  9210. found = true;
  9211. this._edge.scaleInPlace(f);
  9212. p1.addToRef(this._edge, this._collisionPoint);
  9213. }
  9214. }
  9215. p3.subtractToRef(p2, this._edge);
  9216. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9217. edgeSquaredLength = this._edge.lengthSquared();
  9218. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9219. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9220. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9221. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9222. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9223. lowestRoot = getLowestRoot(a, b, c, t);
  9224. if (lowestRoot.found) {
  9225. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9226. if (f >= 0.0 && f <= 1.0) {
  9227. t = lowestRoot.root;
  9228. found = true;
  9229. this._edge.scaleInPlace(f);
  9230. p2.addToRef(this._edge, this._collisionPoint);
  9231. }
  9232. }
  9233. p1.subtractToRef(p3, this._edge);
  9234. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9235. edgeSquaredLength = this._edge.lengthSquared();
  9236. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9237. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9238. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9239. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9240. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9241. lowestRoot = getLowestRoot(a, b, c, t);
  9242. if (lowestRoot.found) {
  9243. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9244. if (f >= 0.0 && f <= 1.0) {
  9245. t = lowestRoot.root;
  9246. found = true;
  9247. this._edge.scaleInPlace(f);
  9248. p3.addToRef(this._edge, this._collisionPoint);
  9249. }
  9250. }
  9251. }
  9252. if (found) {
  9253. var distToCollision = t * this.velocity.length();
  9254. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9255. if (!this.intersectionPoint) {
  9256. this.intersectionPoint = this._collisionPoint.clone();
  9257. }
  9258. else {
  9259. this.intersectionPoint.copyFrom(this._collisionPoint);
  9260. }
  9261. this.nearestDistance = distToCollision;
  9262. this.collisionFound = true;
  9263. }
  9264. }
  9265. };
  9266. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9267. for (var i = indexStart; i < indexEnd; i += 3) {
  9268. var p1 = pts[indices[i] - decal];
  9269. var p2 = pts[indices[i + 1] - decal];
  9270. var p3 = pts[indices[i + 2] - decal];
  9271. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9272. }
  9273. };
  9274. Collider.prototype._getResponse = function (pos, vel) {
  9275. pos.addToRef(vel, this._destinationPoint);
  9276. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9277. this.basePoint.addToRef(vel, pos);
  9278. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9279. this._slidePlaneNormal.normalize();
  9280. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9281. pos.addInPlace(this._displacementVector);
  9282. this.intersectionPoint.addInPlace(this._displacementVector);
  9283. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9284. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9285. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9286. };
  9287. return Collider;
  9288. })();
  9289. BABYLON.Collider = Collider;
  9290. })(BABYLON || (BABYLON = {}));
  9291. //# sourceMappingURL=babylon.collider.js.map
  9292. var BABYLON;
  9293. (function (BABYLON) {
  9294. //WebWorker code will be inserted to this variable.
  9295. BABYLON.CollisionWorker = "";
  9296. (function (WorkerTaskType) {
  9297. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9298. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9299. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9300. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9301. var WorkerTaskType = BABYLON.WorkerTaskType;
  9302. (function (WorkerReplyType) {
  9303. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9304. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9305. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9306. var WorkerReplyType = BABYLON.WorkerReplyType;
  9307. var CollisionCoordinatorWorker = (function () {
  9308. function CollisionCoordinatorWorker() {
  9309. var _this = this;
  9310. this._scaledPosition = BABYLON.Vector3.Zero();
  9311. this._scaledVelocity = BABYLON.Vector3.Zero();
  9312. this.onMeshUpdated = function (mesh) {
  9313. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9314. };
  9315. this.onGeometryUpdated = function (geometry) {
  9316. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9317. };
  9318. this._afterRender = function () {
  9319. if (!_this._init)
  9320. return;
  9321. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9322. return;
  9323. }
  9324. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9325. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9326. if (_this._runningUpdated > 4) {
  9327. return;
  9328. }
  9329. ++_this._runningUpdated;
  9330. var payload = {
  9331. updatedMeshes: _this._addUpdateMeshesList,
  9332. updatedGeometries: _this._addUpdateGeometriesList,
  9333. removedGeometries: _this._toRemoveGeometryArray,
  9334. removedMeshes: _this._toRemoveMeshesArray
  9335. };
  9336. var message = {
  9337. payload: payload,
  9338. taskType: WorkerTaskType.UPDATE
  9339. };
  9340. var serializable = [];
  9341. for (var id in payload.updatedGeometries) {
  9342. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9343. //prepare transferables
  9344. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9345. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9346. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9347. }
  9348. }
  9349. _this._worker.postMessage(message, serializable);
  9350. _this._addUpdateMeshesList = {};
  9351. _this._addUpdateGeometriesList = {};
  9352. _this._toRemoveGeometryArray = [];
  9353. _this._toRemoveMeshesArray = [];
  9354. };
  9355. this._onMessageFromWorker = function (e) {
  9356. var returnData = e.data;
  9357. if (returnData.error != WorkerReplyType.SUCCESS) {
  9358. //TODO what errors can be returned from the worker?
  9359. BABYLON.Tools.Warn("error returned from worker!");
  9360. return;
  9361. }
  9362. switch (returnData.taskType) {
  9363. case WorkerTaskType.INIT:
  9364. _this._init = true;
  9365. //Update the worked with ALL of the scene's current state
  9366. _this._scene.meshes.forEach(function (mesh) {
  9367. _this.onMeshAdded(mesh);
  9368. });
  9369. _this._scene.getGeometries().forEach(function (geometry) {
  9370. _this.onGeometryAdded(geometry);
  9371. });
  9372. break;
  9373. case WorkerTaskType.UPDATE:
  9374. _this._runningUpdated--;
  9375. break;
  9376. case WorkerTaskType.COLLIDE:
  9377. _this._runningCollisionTask = false;
  9378. var returnPayload = returnData.payload;
  9379. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9380. return;
  9381. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9382. //cleanup
  9383. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9384. break;
  9385. }
  9386. };
  9387. this._collisionsCallbackArray = [];
  9388. this._init = false;
  9389. this._runningUpdated = 0;
  9390. this._runningCollisionTask = false;
  9391. this._addUpdateMeshesList = {};
  9392. this._addUpdateGeometriesList = {};
  9393. this._toRemoveGeometryArray = [];
  9394. this._toRemoveMeshesArray = [];
  9395. }
  9396. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9397. if (!this._init)
  9398. return;
  9399. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9400. return;
  9401. position.divideToRef(collider.radius, this._scaledPosition);
  9402. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9403. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9404. var payload = {
  9405. collider: {
  9406. position: this._scaledPosition.asArray(),
  9407. velocity: this._scaledVelocity.asArray(),
  9408. radius: collider.radius.asArray()
  9409. },
  9410. collisionId: collisionIndex,
  9411. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9412. maximumRetry: maximumRetry
  9413. };
  9414. var message = {
  9415. payload: payload,
  9416. taskType: WorkerTaskType.COLLIDE
  9417. };
  9418. this._worker.postMessage(message);
  9419. };
  9420. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9421. this._scene = scene;
  9422. this._scene.registerAfterRender(this._afterRender);
  9423. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9424. this._worker = new Worker(workerUrl);
  9425. this._worker.onmessage = this._onMessageFromWorker;
  9426. var message = {
  9427. payload: {},
  9428. taskType: WorkerTaskType.INIT
  9429. };
  9430. this._worker.postMessage(message);
  9431. };
  9432. CollisionCoordinatorWorker.prototype.destroy = function () {
  9433. this._scene.unregisterAfterRender(this._afterRender);
  9434. this._worker.terminate();
  9435. };
  9436. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9437. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9438. this.onMeshUpdated(mesh);
  9439. };
  9440. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9441. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9442. };
  9443. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9444. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9445. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9446. this.onGeometryUpdated(geometry);
  9447. };
  9448. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9449. this._toRemoveGeometryArray.push(geometry.id);
  9450. };
  9451. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9452. var submeshes = [];
  9453. if (mesh.subMeshes) {
  9454. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9455. return {
  9456. position: idx,
  9457. verticesStart: sm.verticesStart,
  9458. verticesCount: sm.verticesCount,
  9459. indexStart: sm.indexStart,
  9460. indexCount: sm.indexCount,
  9461. hasMaterial: !!sm.getMaterial(),
  9462. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9463. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9464. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9465. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9466. };
  9467. });
  9468. }
  9469. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9470. return {
  9471. uniqueId: mesh.uniqueId,
  9472. id: mesh.id,
  9473. name: mesh.name,
  9474. geometryId: geometryId,
  9475. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9476. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9477. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9478. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9479. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9480. subMeshes: submeshes,
  9481. checkCollisions: mesh.checkCollisions
  9482. };
  9483. };
  9484. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9485. return {
  9486. id: geometry.id,
  9487. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9488. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9489. indices: new Int32Array(geometry.getIndices() || []),
  9490. };
  9491. };
  9492. return CollisionCoordinatorWorker;
  9493. })();
  9494. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9495. var CollisionCoordinatorLegacy = (function () {
  9496. function CollisionCoordinatorLegacy() {
  9497. this._scaledPosition = BABYLON.Vector3.Zero();
  9498. this._scaledVelocity = BABYLON.Vector3.Zero();
  9499. this._finalPosition = BABYLON.Vector3.Zero();
  9500. }
  9501. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9502. position.divideToRef(collider.radius, this._scaledPosition);
  9503. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9504. collider.collidedMesh = null;
  9505. collider.retry = 0;
  9506. collider.initialVelocity = this._scaledVelocity;
  9507. collider.initialPosition = this._scaledPosition;
  9508. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9509. this._finalPosition.multiplyInPlace(collider.radius);
  9510. //run the callback
  9511. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9512. };
  9513. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9514. this._scene = scene;
  9515. };
  9516. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9517. //Legacy need no destruction method.
  9518. };
  9519. //No update in legacy mode
  9520. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9521. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9522. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9523. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9524. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9525. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9526. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9527. if (excludedMesh === void 0) { excludedMesh = null; }
  9528. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9529. if (collider.retry >= maximumRetry) {
  9530. finalPosition.copyFrom(position);
  9531. return;
  9532. }
  9533. collider._initialize(position, velocity, closeDistance);
  9534. // Check all meshes
  9535. for (var index = 0; index < this._scene.meshes.length; index++) {
  9536. var mesh = this._scene.meshes[index];
  9537. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9538. mesh._checkCollision(collider);
  9539. }
  9540. }
  9541. if (!collider.collisionFound) {
  9542. position.addToRef(velocity, finalPosition);
  9543. return;
  9544. }
  9545. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9546. collider._getResponse(position, velocity);
  9547. }
  9548. if (velocity.length() <= closeDistance) {
  9549. finalPosition.copyFrom(position);
  9550. return;
  9551. }
  9552. collider.retry++;
  9553. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9554. };
  9555. return CollisionCoordinatorLegacy;
  9556. })();
  9557. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9558. })(BABYLON || (BABYLON = {}));
  9559. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9560. var __extends = (this && this.__extends) || function (d, b) {
  9561. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9562. function __() { this.constructor = d; }
  9563. __.prototype = b.prototype;
  9564. d.prototype = new __();
  9565. };
  9566. var BABYLON;
  9567. (function (BABYLON) {
  9568. var VRCameraMetrics = (function () {
  9569. function VRCameraMetrics() {
  9570. this.compensateDistorsion = true;
  9571. }
  9572. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9573. get: function () {
  9574. return this.hResolution / (2 * this.vResolution);
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9580. get: function () {
  9581. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9582. },
  9583. enumerable: true,
  9584. configurable: true
  9585. });
  9586. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9587. get: function () {
  9588. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9589. var h = (4 * meters) / this.hScreenSize;
  9590. return BABYLON.Matrix.Translation(h, 0, 0);
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9596. get: function () {
  9597. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9598. var h = (4 * meters) / this.hScreenSize;
  9599. return BABYLON.Matrix.Translation(-h, 0, 0);
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9605. get: function () {
  9606. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9612. get: function () {
  9613. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9614. },
  9615. enumerable: true,
  9616. configurable: true
  9617. });
  9618. VRCameraMetrics.GetDefault = function () {
  9619. var result = new VRCameraMetrics();
  9620. result.hResolution = 1280;
  9621. result.vResolution = 800;
  9622. result.hScreenSize = 0.149759993;
  9623. result.vScreenSize = 0.0935999975;
  9624. result.vScreenCenter = 0.0467999987,
  9625. result.eyeToScreenDistance = 0.0410000011;
  9626. result.lensSeparationDistance = 0.0635000020;
  9627. result.interpupillaryDistance = 0.0640000030;
  9628. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9629. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9630. result.postProcessScaleFactor = 1.714605507808412;
  9631. result.lensCenterOffset = 0.151976421;
  9632. return result;
  9633. };
  9634. return VRCameraMetrics;
  9635. })();
  9636. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9637. var Camera = (function (_super) {
  9638. __extends(Camera, _super);
  9639. function Camera(name, position, scene) {
  9640. _super.call(this, name, scene);
  9641. this.position = position;
  9642. // Members
  9643. this.upVector = BABYLON.Vector3.Up();
  9644. this.orthoLeft = null;
  9645. this.orthoRight = null;
  9646. this.orthoBottom = null;
  9647. this.orthoTop = null;
  9648. this.fov = 0.8;
  9649. this.minZ = 1.0;
  9650. this.maxZ = 10000.0;
  9651. this.inertia = 0.9;
  9652. this.mode = Camera.PERSPECTIVE_CAMERA;
  9653. this.isIntermediate = false;
  9654. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9655. this.layerMask = 0x0FFFFFFF;
  9656. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9657. // Subcamera members
  9658. this.subCameras = new Array();
  9659. this._subCameraMode = Camera.SUB_CAMERA_MODE_NONE;
  9660. // Cache
  9661. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9662. this._projectionMatrix = new BABYLON.Matrix();
  9663. this._postProcesses = new Array();
  9664. this._postProcessesTakenIndices = [];
  9665. this._activeMeshes = new BABYLON.SmartArray(256);
  9666. this._globalPosition = BABYLON.Vector3.Zero();
  9667. scene.addCamera(this);
  9668. if (!scene.activeCamera) {
  9669. scene.activeCamera = this;
  9670. }
  9671. }
  9672. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9673. get: function () {
  9674. return Camera._PERSPECTIVE_CAMERA;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9680. get: function () {
  9681. return Camera._ORTHOGRAPHIC_CAMERA;
  9682. },
  9683. enumerable: true,
  9684. configurable: true
  9685. });
  9686. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9687. get: function () {
  9688. return Camera._FOVMODE_VERTICAL_FIXED;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9694. get: function () {
  9695. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Object.defineProperty(Camera, "SUB_CAMERA_MODE_NONE", {
  9701. get: function () {
  9702. return Camera._SUB_CAMERA_MODE_NONE;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Object.defineProperty(Camera, "SUB_CAMERA_MODE_ANAGLYPH", {
  9708. get: function () {
  9709. return Camera._SUB_CAMERA_MODE_ANAGLYPH;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(Camera, "SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC", {
  9715. get: function () {
  9716. return Camera._SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC;
  9717. },
  9718. enumerable: true,
  9719. configurable: true
  9720. });
  9721. Object.defineProperty(Camera, "SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC", {
  9722. get: function () {
  9723. return Camera._SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VR", {
  9729. get: function () {
  9730. return Camera._SUB_CAMERA_MODE_VR;
  9731. },
  9732. enumerable: true,
  9733. configurable: true
  9734. });
  9735. Object.defineProperty(Camera, "SUB_CAMERAID_A", {
  9736. get: function () {
  9737. return Camera._SUB_CAMERAID_A;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(Camera, "SUB_CAMERAID_B", {
  9743. get: function () {
  9744. return Camera._SUB_CAMERAID_B;
  9745. },
  9746. enumerable: true,
  9747. configurable: true
  9748. });
  9749. Object.defineProperty(Camera.prototype, "globalPosition", {
  9750. get: function () {
  9751. return this._globalPosition;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Camera.prototype.getActiveMeshes = function () {
  9757. return this._activeMeshes;
  9758. };
  9759. Camera.prototype.isActiveMesh = function (mesh) {
  9760. return (this._activeMeshes.indexOf(mesh) !== -1);
  9761. };
  9762. //Cache
  9763. Camera.prototype._initCache = function () {
  9764. _super.prototype._initCache.call(this);
  9765. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9766. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9767. this._cache.mode = undefined;
  9768. this._cache.minZ = undefined;
  9769. this._cache.maxZ = undefined;
  9770. this._cache.fov = undefined;
  9771. this._cache.aspectRatio = undefined;
  9772. this._cache.orthoLeft = undefined;
  9773. this._cache.orthoRight = undefined;
  9774. this._cache.orthoBottom = undefined;
  9775. this._cache.orthoTop = undefined;
  9776. this._cache.renderWidth = undefined;
  9777. this._cache.renderHeight = undefined;
  9778. };
  9779. Camera.prototype._updateCache = function (ignoreParentClass) {
  9780. if (!ignoreParentClass) {
  9781. _super.prototype._updateCache.call(this);
  9782. }
  9783. var engine = this.getEngine();
  9784. this._cache.position.copyFrom(this.position);
  9785. this._cache.upVector.copyFrom(this.upVector);
  9786. this._cache.mode = this.mode;
  9787. this._cache.minZ = this.minZ;
  9788. this._cache.maxZ = this.maxZ;
  9789. this._cache.fov = this.fov;
  9790. this._cache.aspectRatio = engine.getAspectRatio(this);
  9791. this._cache.orthoLeft = this.orthoLeft;
  9792. this._cache.orthoRight = this.orthoRight;
  9793. this._cache.orthoBottom = this.orthoBottom;
  9794. this._cache.orthoTop = this.orthoTop;
  9795. this._cache.renderWidth = engine.getRenderWidth();
  9796. this._cache.renderHeight = engine.getRenderHeight();
  9797. };
  9798. Camera.prototype._updateFromScene = function () {
  9799. this.updateCache();
  9800. this._update();
  9801. };
  9802. // Synchronized
  9803. Camera.prototype._isSynchronized = function () {
  9804. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9805. };
  9806. Camera.prototype._isSynchronizedViewMatrix = function () {
  9807. if (!_super.prototype._isSynchronized.call(this))
  9808. return false;
  9809. return this._cache.position.equals(this.position)
  9810. && this._cache.upVector.equals(this.upVector)
  9811. && this.isSynchronizedWithParent();
  9812. };
  9813. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9814. var check = this._cache.mode === this.mode
  9815. && this._cache.minZ === this.minZ
  9816. && this._cache.maxZ === this.maxZ;
  9817. if (!check) {
  9818. return false;
  9819. }
  9820. var engine = this.getEngine();
  9821. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9822. check = this._cache.fov === this.fov
  9823. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9824. }
  9825. else {
  9826. check = this._cache.orthoLeft === this.orthoLeft
  9827. && this._cache.orthoRight === this.orthoRight
  9828. && this._cache.orthoBottom === this.orthoBottom
  9829. && this._cache.orthoTop === this.orthoTop
  9830. && this._cache.renderWidth === engine.getRenderWidth()
  9831. && this._cache.renderHeight === engine.getRenderHeight();
  9832. }
  9833. return check;
  9834. };
  9835. // Controls
  9836. Camera.prototype.attachControl = function (element) {
  9837. };
  9838. Camera.prototype.detachControl = function (element) {
  9839. };
  9840. Camera.prototype._update = function () {
  9841. this._checkInputs();
  9842. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9843. this._updateSubCameras();
  9844. }
  9845. };
  9846. Camera.prototype._checkInputs = function () {
  9847. };
  9848. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9849. if (insertAt === void 0) { insertAt = null; }
  9850. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9851. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9852. return 0;
  9853. }
  9854. if (insertAt == null || insertAt < 0) {
  9855. this._postProcesses.push(postProcess);
  9856. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9857. return this._postProcesses.length - 1;
  9858. }
  9859. var add = 0;
  9860. if (this._postProcesses[insertAt]) {
  9861. var start = this._postProcesses.length - 1;
  9862. for (var i = start; i >= insertAt + 1; --i) {
  9863. this._postProcesses[i + 1] = this._postProcesses[i];
  9864. }
  9865. add = 1;
  9866. }
  9867. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9868. if (this._postProcessesTakenIndices[i] < insertAt) {
  9869. continue;
  9870. }
  9871. start = this._postProcessesTakenIndices.length - 1;
  9872. for (var j = start; j >= i; --j) {
  9873. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9874. }
  9875. this._postProcessesTakenIndices[i] = insertAt;
  9876. break;
  9877. }
  9878. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9879. this._postProcessesTakenIndices.push(insertAt);
  9880. }
  9881. var result = insertAt + add;
  9882. this._postProcesses[result] = postProcess;
  9883. return result;
  9884. };
  9885. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9886. if (atIndices === void 0) { atIndices = null; }
  9887. var result = [];
  9888. if (!atIndices) {
  9889. var length = this._postProcesses.length;
  9890. for (var i = 0; i < length; i++) {
  9891. if (this._postProcesses[i] !== postProcess) {
  9892. continue;
  9893. }
  9894. delete this._postProcesses[i];
  9895. var index = this._postProcessesTakenIndices.indexOf(i);
  9896. this._postProcessesTakenIndices.splice(index, 1);
  9897. }
  9898. }
  9899. else {
  9900. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9901. for (i = 0; i < atIndices.length; i++) {
  9902. var foundPostProcess = this._postProcesses[atIndices[i]];
  9903. if (foundPostProcess !== postProcess) {
  9904. result.push(i);
  9905. continue;
  9906. }
  9907. delete this._postProcesses[atIndices[i]];
  9908. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9909. this._postProcessesTakenIndices.splice(index, 1);
  9910. }
  9911. }
  9912. return result;
  9913. };
  9914. Camera.prototype.getWorldMatrix = function () {
  9915. if (!this._worldMatrix) {
  9916. this._worldMatrix = BABYLON.Matrix.Identity();
  9917. }
  9918. var viewMatrix = this.getViewMatrix();
  9919. viewMatrix.invertToRef(this._worldMatrix);
  9920. return this._worldMatrix;
  9921. };
  9922. Camera.prototype._getViewMatrix = function () {
  9923. return BABYLON.Matrix.Identity();
  9924. };
  9925. Camera.prototype.getViewMatrix = function (force) {
  9926. this._computedViewMatrix = this._computeViewMatrix(force);
  9927. if (!force && this._isSynchronizedViewMatrix()) {
  9928. return this._computedViewMatrix;
  9929. }
  9930. if (!this.parent || !this.parent.getWorldMatrix) {
  9931. this._globalPosition.copyFrom(this.position);
  9932. }
  9933. else {
  9934. if (!this._worldMatrix) {
  9935. this._worldMatrix = BABYLON.Matrix.Identity();
  9936. }
  9937. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9938. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9939. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9940. this._computedViewMatrix.invert();
  9941. this._markSyncedWithParent();
  9942. }
  9943. this._currentRenderId = this.getScene().getRenderId();
  9944. return this._computedViewMatrix;
  9945. };
  9946. Camera.prototype._computeViewMatrix = function (force) {
  9947. if (!force && this._isSynchronizedViewMatrix()) {
  9948. return this._computedViewMatrix;
  9949. }
  9950. this._computedViewMatrix = this._getViewMatrix();
  9951. this._currentRenderId = this.getScene().getRenderId();
  9952. return this._computedViewMatrix;
  9953. };
  9954. Camera.prototype.getProjectionMatrix = function (force) {
  9955. if (!force && this._isSynchronizedProjectionMatrix()) {
  9956. return this._projectionMatrix;
  9957. }
  9958. var engine = this.getEngine();
  9959. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9960. if (this.minZ <= 0) {
  9961. this.minZ = 0.1;
  9962. }
  9963. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9964. return this._projectionMatrix;
  9965. }
  9966. var halfWidth = engine.getRenderWidth() / 2.0;
  9967. var halfHeight = engine.getRenderHeight() / 2.0;
  9968. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9969. return this._projectionMatrix;
  9970. };
  9971. Camera.prototype.dispose = function () {
  9972. // Remove from scene
  9973. this.getScene().removeCamera(this);
  9974. while (this.subCameras.length > 0) {
  9975. this.subCameras.pop().dispose();
  9976. }
  9977. // Postprocesses
  9978. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9979. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9980. }
  9981. };
  9982. // ---- 3D cameras section ----
  9983. Camera.prototype.setSubCameraMode = function (mode, halfSpace, metrics) {
  9984. if (halfSpace === void 0) { halfSpace = 0; }
  9985. while (this.subCameras.length > 0) {
  9986. this.subCameras.pop().dispose();
  9987. }
  9988. this._subCameraMode = mode;
  9989. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  9990. var camA = this.getSubCamera(this.name + "_A", true);
  9991. var camB = this.getSubCamera(this.name + "_B", false);
  9992. var postProcessA;
  9993. var postProcessB;
  9994. switch (this._subCameraMode) {
  9995. case Camera.SUB_CAMERA_MODE_ANAGLYPH:
  9996. postProcessA = new BABYLON.PassPostProcess(this.name + "_leftTexture", 1.0, camA);
  9997. camA.isIntermediate = true;
  9998. postProcessB = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, camB);
  9999. postProcessB.onApply = function (effect) {
  10000. effect.setTextureFromPostProcess("leftSampler", postProcessA);
  10001. };
  10002. break;
  10003. case Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC:
  10004. case Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC:
  10005. var isStereoscopicHoriz = this._subCameraMode === Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC;
  10006. postProcessA = new BABYLON.PassPostProcess("passthru", 1.0, camA);
  10007. camA.isIntermediate = true;
  10008. postProcessB = new BABYLON.StereoscopicInterlacePostProcess("st_interlace", camB, postProcessA, isStereoscopicHoriz);
  10009. break;
  10010. case Camera.SUB_CAMERA_MODE_VR:
  10011. metrics = metrics || VRCameraMetrics.GetDefault();
  10012. camA._vrMetrics = metrics;
  10013. camA.viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10014. camA._vrWorkMatrix = new BABYLON.Matrix();
  10015. camA._vrHMatrix = metrics.leftHMatrix;
  10016. camA._vrPreViewMatrix = metrics.leftPreViewMatrix;
  10017. camA.getProjectionMatrix = camA._getVRProjectionMatrix;
  10018. if (metrics.compensateDistorsion) {
  10019. postProcessA = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Left", camA, false, metrics);
  10020. }
  10021. camB._vrMetrics = camA._vrMetrics;
  10022. camB.viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10023. camB._vrWorkMatrix = new BABYLON.Matrix();
  10024. camB._vrHMatrix = metrics.rightHMatrix;
  10025. camB._vrPreViewMatrix = metrics.rightPreViewMatrix;
  10026. camB.getProjectionMatrix = camB._getVRProjectionMatrix;
  10027. if (metrics.compensateDistorsion) {
  10028. postProcessB = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Right", camB, true, metrics);
  10029. }
  10030. }
  10031. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  10032. this.subCameras.push(camA);
  10033. this.subCameras.push(camB);
  10034. }
  10035. this._update();
  10036. };
  10037. Camera.prototype._getVRProjectionMatrix = function () {
  10038. BABYLON.Matrix.PerspectiveFovLHToRef(this._vrMetrics.aspectRatioFov, this._vrMetrics.aspectRatio, this.minZ, this.maxZ, this._vrWorkMatrix);
  10039. this._vrWorkMatrix.multiplyToRef(this._vrHMatrix, this._projectionMatrix);
  10040. return this._projectionMatrix;
  10041. };
  10042. Camera.prototype.setSubCamHalfSpace = function (halfSpace) {
  10043. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  10044. };
  10045. /**
  10046. * May needs to be overridden by children so sub has required properties to be copied
  10047. */
  10048. Camera.prototype.getSubCamera = function (name, isA) {
  10049. return null;
  10050. };
  10051. /**
  10052. * May needs to be overridden by children
  10053. */
  10054. Camera.prototype._updateSubCameras = function () {
  10055. var camA = this.subCameras[Camera.SUB_CAMERAID_A];
  10056. var camB = this.subCameras[Camera.SUB_CAMERAID_B];
  10057. camA.minZ = camB.minZ = this.minZ;
  10058. camA.maxZ = camB.maxZ = this.maxZ;
  10059. camA.fov = camB.fov = this.fov;
  10060. // only update viewport, when ANAGLYPH
  10061. if (this._subCameraMode === Camera.SUB_CAMERA_MODE_ANAGLYPH) {
  10062. camA.viewport = camB.viewport = this.viewport;
  10063. }
  10064. };
  10065. // Statics
  10066. Camera._PERSPECTIVE_CAMERA = 0;
  10067. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10068. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10069. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10070. Camera._SUB_CAMERA_MODE_NONE = 0;
  10071. Camera._SUB_CAMERA_MODE_ANAGLYPH = 1;
  10072. Camera._SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC = 2;
  10073. Camera._SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC = 3;
  10074. Camera._SUB_CAMERA_MODE_VR = 4;
  10075. Camera._SUB_CAMERAID_A = 0;
  10076. Camera._SUB_CAMERAID_B = 1;
  10077. return Camera;
  10078. })(BABYLON.Node);
  10079. BABYLON.Camera = Camera;
  10080. })(BABYLON || (BABYLON = {}));
  10081. //# sourceMappingURL=babylon.camera.js.map
  10082. var __extends = (this && this.__extends) || function (d, b) {
  10083. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10084. function __() { this.constructor = d; }
  10085. __.prototype = b.prototype;
  10086. d.prototype = new __();
  10087. };
  10088. var BABYLON;
  10089. (function (BABYLON) {
  10090. var TargetCamera = (function (_super) {
  10091. __extends(TargetCamera, _super);
  10092. function TargetCamera(name, position, scene) {
  10093. _super.call(this, name, position, scene);
  10094. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10095. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10096. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10097. this.speed = 2.0;
  10098. this.noRotationConstraint = false;
  10099. this.lockedTarget = null;
  10100. this._currentTarget = BABYLON.Vector3.Zero();
  10101. this._viewMatrix = BABYLON.Matrix.Zero();
  10102. this._camMatrix = BABYLON.Matrix.Zero();
  10103. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10104. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10105. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10106. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10107. this._lookAtTemp = BABYLON.Matrix.Zero();
  10108. this._tempMatrix = BABYLON.Matrix.Zero();
  10109. }
  10110. TargetCamera.prototype._getLockedTargetPosition = function () {
  10111. if (!this.lockedTarget) {
  10112. return null;
  10113. }
  10114. return this.lockedTarget.position || this.lockedTarget;
  10115. };
  10116. // Cache
  10117. TargetCamera.prototype._initCache = function () {
  10118. _super.prototype._initCache.call(this);
  10119. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10120. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10121. };
  10122. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10123. if (!ignoreParentClass) {
  10124. _super.prototype._updateCache.call(this);
  10125. }
  10126. var lockedTargetPosition = this._getLockedTargetPosition();
  10127. if (!lockedTargetPosition) {
  10128. this._cache.lockedTarget = null;
  10129. }
  10130. else {
  10131. if (!this._cache.lockedTarget) {
  10132. this._cache.lockedTarget = lockedTargetPosition.clone();
  10133. }
  10134. else {
  10135. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10136. }
  10137. }
  10138. this._cache.rotation.copyFrom(this.rotation);
  10139. };
  10140. // Synchronized
  10141. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10142. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10143. return false;
  10144. }
  10145. var lockedTargetPosition = this._getLockedTargetPosition();
  10146. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10147. && this._cache.rotation.equals(this.rotation);
  10148. };
  10149. // Methods
  10150. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10151. var engine = this.getEngine();
  10152. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10153. };
  10154. // Target
  10155. TargetCamera.prototype.setTarget = function (target) {
  10156. this.upVector.normalize();
  10157. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10158. this._camMatrix.invert();
  10159. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10160. var vDir = target.subtract(this.position);
  10161. if (vDir.x >= 0.0) {
  10162. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10163. }
  10164. else {
  10165. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10166. }
  10167. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10168. if (isNaN(this.rotation.x)) {
  10169. this.rotation.x = 0;
  10170. }
  10171. if (isNaN(this.rotation.y)) {
  10172. this.rotation.y = 0;
  10173. }
  10174. if (isNaN(this.rotation.z)) {
  10175. this.rotation.z = 0;
  10176. }
  10177. };
  10178. TargetCamera.prototype.getTarget = function () {
  10179. return this._currentTarget;
  10180. };
  10181. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10182. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10183. };
  10184. TargetCamera.prototype._updatePosition = function () {
  10185. this.position.addInPlace(this.cameraDirection);
  10186. };
  10187. TargetCamera.prototype._checkInputs = function () {
  10188. var needToMove = this._decideIfNeedsToMove();
  10189. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10190. // Move
  10191. if (needToMove) {
  10192. this._updatePosition();
  10193. }
  10194. // Rotate
  10195. if (needToRotate) {
  10196. this.rotation.x += this.cameraRotation.x;
  10197. this.rotation.y += this.cameraRotation.y;
  10198. if (!this.noRotationConstraint) {
  10199. var limit = (Math.PI / 2) * 0.95;
  10200. if (this.rotation.x > limit)
  10201. this.rotation.x = limit;
  10202. if (this.rotation.x < -limit)
  10203. this.rotation.x = -limit;
  10204. }
  10205. }
  10206. // Inertia
  10207. if (needToMove) {
  10208. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10209. this.cameraDirection.x = 0;
  10210. }
  10211. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10212. this.cameraDirection.y = 0;
  10213. }
  10214. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10215. this.cameraDirection.z = 0;
  10216. }
  10217. this.cameraDirection.scaleInPlace(this.inertia);
  10218. }
  10219. if (needToRotate) {
  10220. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10221. this.cameraRotation.x = 0;
  10222. }
  10223. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10224. this.cameraRotation.y = 0;
  10225. }
  10226. this.cameraRotation.scaleInPlace(this.inertia);
  10227. }
  10228. _super.prototype._checkInputs.call(this);
  10229. };
  10230. TargetCamera.prototype._getViewMatrix = function () {
  10231. if (!this.lockedTarget) {
  10232. // Compute
  10233. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10234. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10235. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10236. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10237. this._lookAtTemp.invert();
  10238. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10239. }
  10240. else {
  10241. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10242. }
  10243. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10244. // Computing target and final matrix
  10245. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10246. }
  10247. else {
  10248. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10249. }
  10250. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10251. return this._viewMatrix;
  10252. };
  10253. TargetCamera.prototype._getVRViewMatrix = function () {
  10254. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10255. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10256. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._vrActualUp);
  10257. // Computing target and final matrix
  10258. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10259. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._vrActualUp, this._vrWorkMatrix);
  10260. this._vrWorkMatrix.multiplyToRef(this._vrPreViewMatrix, this._viewMatrix);
  10261. return this._viewMatrix;
  10262. };
  10263. /**
  10264. * @override
  10265. * needs to be overridden, so sub has required properties to be copied
  10266. */
  10267. TargetCamera.prototype.getSubCamera = function (name, isA) {
  10268. var subCamera = new BABYLON.TargetCamera(name, this.position.clone(), this.getScene());
  10269. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10270. subCamera._vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10271. subCamera._getViewMatrix = subCamera._getVRViewMatrix;
  10272. }
  10273. return subCamera;
  10274. };
  10275. /**
  10276. * @override
  10277. * needs to be overridden, adding copy of position, and rotation for VR, or target for rest
  10278. */
  10279. TargetCamera.prototype._updateSubCameras = function () {
  10280. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  10281. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  10282. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10283. camA.rotation.x = camB.rotation.x = this.rotation.x;
  10284. camA.rotation.y = camB.rotation.y = this.rotation.y;
  10285. camA.rotation.z = camB.rotation.z = this.rotation.z;
  10286. camA.position.copyFrom(this.position);
  10287. camB.position.copyFrom(this.position);
  10288. }
  10289. else {
  10290. camA.setTarget(this.getTarget());
  10291. camB.setTarget(this.getTarget());
  10292. this._getSubCamPosition(-this._subCamHalfSpace, camA.position);
  10293. this._getSubCamPosition(this._subCamHalfSpace, camB.position);
  10294. }
  10295. _super.prototype._updateSubCameras.call(this);
  10296. };
  10297. TargetCamera.prototype._getSubCamPosition = function (halfSpace, result) {
  10298. if (!this._subCamTransformMatrix) {
  10299. this._subCamTransformMatrix = new BABYLON.Matrix();
  10300. }
  10301. var target = this.getTarget();
  10302. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._subCamTransformMatrix);
  10303. this._subCamTransformMatrix = this._subCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10304. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._subCamTransformMatrix, result);
  10305. };
  10306. return TargetCamera;
  10307. })(BABYLON.Camera);
  10308. BABYLON.TargetCamera = TargetCamera;
  10309. })(BABYLON || (BABYLON = {}));
  10310. //# sourceMappingURL=babylon.targetCamera.js.map
  10311. var __extends = (this && this.__extends) || function (d, b) {
  10312. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10313. function __() { this.constructor = d; }
  10314. __.prototype = b.prototype;
  10315. d.prototype = new __();
  10316. };
  10317. var BABYLON;
  10318. (function (BABYLON) {
  10319. var FreeCamera = (function (_super) {
  10320. __extends(FreeCamera, _super);
  10321. function FreeCamera(name, position, scene) {
  10322. var _this = this;
  10323. _super.call(this, name, position, scene);
  10324. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10325. this.keysUp = [38];
  10326. this.keysDown = [40];
  10327. this.keysLeft = [37];
  10328. this.keysRight = [39];
  10329. this.checkCollisions = false;
  10330. this.applyGravity = false;
  10331. this.angularSensibility = 2000.0;
  10332. this._keys = [];
  10333. this._collider = new BABYLON.Collider();
  10334. this._needMoveForGravity = false;
  10335. this._oldPosition = BABYLON.Vector3.Zero();
  10336. this._diffPosition = BABYLON.Vector3.Zero();
  10337. this._newPosition = BABYLON.Vector3.Zero();
  10338. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10339. if (collidedMesh === void 0) { collidedMesh = null; }
  10340. //TODO move this to the collision coordinator!
  10341. if (_this.getScene().workerCollisions)
  10342. newPosition.multiplyInPlace(_this._collider.radius);
  10343. var updatePosition = function (newPos) {
  10344. _this._newPosition.copyFrom(newPos);
  10345. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10346. var oldPosition = _this.position.clone();
  10347. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10348. _this.position.addInPlace(_this._diffPosition);
  10349. if (_this.onCollide && collidedMesh) {
  10350. _this.onCollide(collidedMesh);
  10351. }
  10352. }
  10353. };
  10354. updatePosition(newPosition);
  10355. };
  10356. }
  10357. // Controls
  10358. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10359. var _this = this;
  10360. var previousPosition;
  10361. var engine = this.getEngine();
  10362. if (this._attachedElement) {
  10363. return;
  10364. }
  10365. this._attachedElement = element;
  10366. if (this._onMouseDown === undefined) {
  10367. this._onMouseDown = function (evt) {
  10368. previousPosition = {
  10369. x: evt.clientX,
  10370. y: evt.clientY
  10371. };
  10372. if (!noPreventDefault) {
  10373. evt.preventDefault();
  10374. }
  10375. };
  10376. this._onMouseUp = function (evt) {
  10377. previousPosition = null;
  10378. if (!noPreventDefault) {
  10379. evt.preventDefault();
  10380. }
  10381. };
  10382. this._onMouseOut = function (evt) {
  10383. previousPosition = null;
  10384. _this._keys = [];
  10385. if (!noPreventDefault) {
  10386. evt.preventDefault();
  10387. }
  10388. };
  10389. this._onMouseMove = function (evt) {
  10390. if (!previousPosition && !engine.isPointerLock) {
  10391. return;
  10392. }
  10393. var offsetX;
  10394. var offsetY;
  10395. if (!engine.isPointerLock) {
  10396. offsetX = evt.clientX - previousPosition.x;
  10397. offsetY = evt.clientY - previousPosition.y;
  10398. }
  10399. else {
  10400. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10401. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10402. }
  10403. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10404. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10405. previousPosition = {
  10406. x: evt.clientX,
  10407. y: evt.clientY
  10408. };
  10409. if (!noPreventDefault) {
  10410. evt.preventDefault();
  10411. }
  10412. };
  10413. this._onKeyDown = function (evt) {
  10414. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10415. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10416. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10417. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10418. var index = _this._keys.indexOf(evt.keyCode);
  10419. if (index === -1) {
  10420. _this._keys.push(evt.keyCode);
  10421. }
  10422. if (!noPreventDefault) {
  10423. evt.preventDefault();
  10424. }
  10425. }
  10426. };
  10427. this._onKeyUp = function (evt) {
  10428. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10429. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10430. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10431. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10432. var index = _this._keys.indexOf(evt.keyCode);
  10433. if (index >= 0) {
  10434. _this._keys.splice(index, 1);
  10435. }
  10436. if (!noPreventDefault) {
  10437. evt.preventDefault();
  10438. }
  10439. }
  10440. };
  10441. this._onLostFocus = function () {
  10442. _this._keys = [];
  10443. };
  10444. this._reset = function () {
  10445. _this._keys = [];
  10446. previousPosition = null;
  10447. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10448. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10449. };
  10450. }
  10451. element.addEventListener("mousedown", this._onMouseDown, false);
  10452. element.addEventListener("mouseup", this._onMouseUp, false);
  10453. element.addEventListener("mouseout", this._onMouseOut, false);
  10454. element.addEventListener("mousemove", this._onMouseMove, false);
  10455. BABYLON.Tools.RegisterTopRootEvents([
  10456. { name: "keydown", handler: this._onKeyDown },
  10457. { name: "keyup", handler: this._onKeyUp },
  10458. { name: "blur", handler: this._onLostFocus }
  10459. ]);
  10460. };
  10461. FreeCamera.prototype.detachControl = function (element) {
  10462. if (this._attachedElement != element) {
  10463. return;
  10464. }
  10465. element.removeEventListener("mousedown", this._onMouseDown);
  10466. element.removeEventListener("mouseup", this._onMouseUp);
  10467. element.removeEventListener("mouseout", this._onMouseOut);
  10468. element.removeEventListener("mousemove", this._onMouseMove);
  10469. BABYLON.Tools.UnregisterTopRootEvents([
  10470. { name: "keydown", handler: this._onKeyDown },
  10471. { name: "keyup", handler: this._onKeyUp },
  10472. { name: "blur", handler: this._onLostFocus }
  10473. ]);
  10474. this._attachedElement = null;
  10475. if (this._reset) {
  10476. this._reset();
  10477. }
  10478. };
  10479. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10480. var globalPosition;
  10481. if (this.parent) {
  10482. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10483. }
  10484. else {
  10485. globalPosition = this.position;
  10486. }
  10487. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10488. this._collider.radius = this.ellipsoid;
  10489. //add gravity to the velocity to prevent the dual-collision checking
  10490. if (this.applyGravity) {
  10491. velocity.addInPlace(this.getScene().gravity);
  10492. }
  10493. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10494. };
  10495. FreeCamera.prototype._checkInputs = function () {
  10496. if (!this._localDirection) {
  10497. this._localDirection = BABYLON.Vector3.Zero();
  10498. this._transformedDirection = BABYLON.Vector3.Zero();
  10499. }
  10500. // Keyboard
  10501. for (var index = 0; index < this._keys.length; index++) {
  10502. var keyCode = this._keys[index];
  10503. var speed = this._computeLocalCameraSpeed();
  10504. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10505. this._localDirection.copyFromFloats(-speed, 0, 0);
  10506. }
  10507. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10508. this._localDirection.copyFromFloats(0, 0, speed);
  10509. }
  10510. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10511. this._localDirection.copyFromFloats(speed, 0, 0);
  10512. }
  10513. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10514. this._localDirection.copyFromFloats(0, 0, -speed);
  10515. }
  10516. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10517. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10518. this.cameraDirection.addInPlace(this._transformedDirection);
  10519. }
  10520. _super.prototype._checkInputs.call(this);
  10521. };
  10522. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10523. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10524. };
  10525. FreeCamera.prototype._updatePosition = function () {
  10526. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10527. this._collideWithWorld(this.cameraDirection);
  10528. }
  10529. else {
  10530. this.position.addInPlace(this.cameraDirection);
  10531. }
  10532. };
  10533. return FreeCamera;
  10534. })(BABYLON.TargetCamera);
  10535. BABYLON.FreeCamera = FreeCamera;
  10536. })(BABYLON || (BABYLON = {}));
  10537. //# sourceMappingURL=babylon.freeCamera.js.map
  10538. var __extends = (this && this.__extends) || function (d, b) {
  10539. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10540. function __() { this.constructor = d; }
  10541. __.prototype = b.prototype;
  10542. d.prototype = new __();
  10543. };
  10544. var BABYLON;
  10545. (function (BABYLON) {
  10546. var FollowCamera = (function (_super) {
  10547. __extends(FollowCamera, _super);
  10548. function FollowCamera(name, position, scene) {
  10549. _super.call(this, name, position, scene);
  10550. this.radius = 12;
  10551. this.rotationOffset = 0;
  10552. this.heightOffset = 4;
  10553. this.cameraAcceleration = 0.05;
  10554. this.maxCameraSpeed = 20;
  10555. }
  10556. FollowCamera.prototype.getRadians = function (degrees) {
  10557. return degrees * Math.PI / 180;
  10558. };
  10559. FollowCamera.prototype.follow = function (cameraTarget) {
  10560. if (!cameraTarget)
  10561. return;
  10562. var yRotation;
  10563. if (cameraTarget.rotationQuaternion) {
  10564. var rotMatrix = new BABYLON.Matrix();
  10565. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10566. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10567. }
  10568. else {
  10569. yRotation = cameraTarget.rotation.y;
  10570. }
  10571. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10572. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10573. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10574. var dx = targetX - this.position.x;
  10575. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10576. var dz = (targetZ) - this.position.z;
  10577. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10578. var vy = dy * this.cameraAcceleration;
  10579. var vz = dz * this.cameraAcceleration * 2;
  10580. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10581. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10582. }
  10583. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10584. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10585. }
  10586. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10587. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10588. }
  10589. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10590. this.setTarget(cameraTarget.position);
  10591. };
  10592. FollowCamera.prototype._checkInputs = function () {
  10593. _super.prototype._checkInputs.call(this);
  10594. this.follow(this.target);
  10595. };
  10596. return FollowCamera;
  10597. })(BABYLON.TargetCamera);
  10598. BABYLON.FollowCamera = FollowCamera;
  10599. })(BABYLON || (BABYLON = {}));
  10600. //# sourceMappingURL=babylon.followCamera.js.map
  10601. var __extends = (this && this.__extends) || function (d, b) {
  10602. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10603. function __() { this.constructor = d; }
  10604. __.prototype = b.prototype;
  10605. d.prototype = new __();
  10606. };
  10607. var BABYLON;
  10608. (function (BABYLON) {
  10609. // We're mainly based on the logic defined into the FreeCamera code
  10610. var TouchCamera = (function (_super) {
  10611. __extends(TouchCamera, _super);
  10612. function TouchCamera(name, position, scene) {
  10613. _super.call(this, name, position, scene);
  10614. this._offsetX = null;
  10615. this._offsetY = null;
  10616. this._pointerCount = 0;
  10617. this._pointerPressed = [];
  10618. this.angularSensibility = 200000.0;
  10619. this.moveSensibility = 500.0;
  10620. }
  10621. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10622. var _this = this;
  10623. var previousPosition;
  10624. if (this._attachedCanvas) {
  10625. return;
  10626. }
  10627. this._attachedCanvas = canvas;
  10628. if (this._onPointerDown === undefined) {
  10629. this._onPointerDown = function (evt) {
  10630. if (!noPreventDefault) {
  10631. evt.preventDefault();
  10632. }
  10633. _this._pointerPressed.push(evt.pointerId);
  10634. if (_this._pointerPressed.length !== 1) {
  10635. return;
  10636. }
  10637. previousPosition = {
  10638. x: evt.clientX,
  10639. y: evt.clientY
  10640. };
  10641. };
  10642. this._onPointerUp = function (evt) {
  10643. if (!noPreventDefault) {
  10644. evt.preventDefault();
  10645. }
  10646. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10647. if (index === -1) {
  10648. return;
  10649. }
  10650. _this._pointerPressed.splice(index, 1);
  10651. if (index != 0) {
  10652. return;
  10653. }
  10654. previousPosition = null;
  10655. _this._offsetX = null;
  10656. _this._offsetY = null;
  10657. };
  10658. this._onPointerMove = function (evt) {
  10659. if (!noPreventDefault) {
  10660. evt.preventDefault();
  10661. }
  10662. if (!previousPosition) {
  10663. return;
  10664. }
  10665. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10666. if (index != 0) {
  10667. return;
  10668. }
  10669. _this._offsetX = evt.clientX - previousPosition.x;
  10670. _this._offsetY = -(evt.clientY - previousPosition.y);
  10671. };
  10672. this._onLostFocus = function () {
  10673. _this._offsetX = null;
  10674. _this._offsetY = null;
  10675. };
  10676. }
  10677. canvas.addEventListener("pointerdown", this._onPointerDown);
  10678. canvas.addEventListener("pointerup", this._onPointerUp);
  10679. canvas.addEventListener("pointerout", this._onPointerUp);
  10680. canvas.addEventListener("pointermove", this._onPointerMove);
  10681. BABYLON.Tools.RegisterTopRootEvents([
  10682. { name: "blur", handler: this._onLostFocus }
  10683. ]);
  10684. };
  10685. TouchCamera.prototype.detachControl = function (canvas) {
  10686. if (this._attachedCanvas != canvas) {
  10687. return;
  10688. }
  10689. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10690. canvas.removeEventListener("pointerup", this._onPointerUp);
  10691. canvas.removeEventListener("pointerout", this._onPointerUp);
  10692. canvas.removeEventListener("pointermove", this._onPointerMove);
  10693. BABYLON.Tools.UnregisterTopRootEvents([
  10694. { name: "blur", handler: this._onLostFocus }
  10695. ]);
  10696. this._attachedCanvas = null;
  10697. };
  10698. TouchCamera.prototype._checkInputs = function () {
  10699. if (!this._offsetX) {
  10700. return;
  10701. }
  10702. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10703. if (this._pointerPressed.length > 1) {
  10704. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10705. }
  10706. else {
  10707. var speed = this._computeLocalCameraSpeed();
  10708. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10709. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10710. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10711. }
  10712. _super.prototype._checkInputs.call(this);
  10713. };
  10714. return TouchCamera;
  10715. })(BABYLON.FreeCamera);
  10716. BABYLON.TouchCamera = TouchCamera;
  10717. })(BABYLON || (BABYLON = {}));
  10718. //# sourceMappingURL=babylon.touchCamera.js.map
  10719. var __extends = (this && this.__extends) || function (d, b) {
  10720. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10721. function __() { this.constructor = d; }
  10722. __.prototype = b.prototype;
  10723. d.prototype = new __();
  10724. };
  10725. var BABYLON;
  10726. (function (BABYLON) {
  10727. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10728. var ArcRotateCamera = (function (_super) {
  10729. __extends(ArcRotateCamera, _super);
  10730. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10731. var _this = this;
  10732. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10733. this.alpha = alpha;
  10734. this.beta = beta;
  10735. this.radius = radius;
  10736. this.target = target;
  10737. this.inertialAlphaOffset = 0;
  10738. this.inertialBetaOffset = 0;
  10739. this.inertialRadiusOffset = 0;
  10740. this.lowerAlphaLimit = null;
  10741. this.upperAlphaLimit = null;
  10742. this.lowerBetaLimit = 0.01;
  10743. this.upperBetaLimit = Math.PI;
  10744. this.lowerRadiusLimit = null;
  10745. this.upperRadiusLimit = null;
  10746. this.angularSensibility = 1000.0;
  10747. this.wheelPrecision = 3.0;
  10748. this.pinchPrecision = 2.0;
  10749. this.keysUp = [38];
  10750. this.keysDown = [40];
  10751. this.keysLeft = [37];
  10752. this.keysRight = [39];
  10753. this.zoomOnFactor = 1;
  10754. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10755. this.pinchInwards = true;
  10756. this.allowUpsideDown = true;
  10757. this._keys = [];
  10758. this._viewMatrix = new BABYLON.Matrix();
  10759. this.checkCollisions = false;
  10760. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10761. this._collider = new BABYLON.Collider();
  10762. this._previousPosition = BABYLON.Vector3.Zero();
  10763. this._collisionVelocity = BABYLON.Vector3.Zero();
  10764. this._newPosition = BABYLON.Vector3.Zero();
  10765. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10766. if (collidedMesh === void 0) { collidedMesh = null; }
  10767. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10768. newPosition.multiplyInPlace(_this._collider.radius);
  10769. }
  10770. if (!collidedMesh) {
  10771. _this._previousPosition.copyFrom(_this.position);
  10772. _this.setPosition(_this._newPosition);
  10773. _this.position.copyFrom(_this._newPosition);
  10774. }
  10775. else {
  10776. _this.setPosition(_this._previousPosition);
  10777. _this.position.copyFrom(_this._previousPosition);
  10778. if (_this.onCollide) {
  10779. _this.onCollide(collidedMesh);
  10780. }
  10781. }
  10782. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._getTargetPosition(), _this.upVector, _this._viewMatrix);
  10783. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10784. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10785. _this._collisionTriggered = false;
  10786. };
  10787. if (!this.target) {
  10788. this.target = BABYLON.Vector3.Zero();
  10789. }
  10790. this.getViewMatrix();
  10791. }
  10792. ArcRotateCamera.prototype._getTargetPosition = function () {
  10793. return this.target.position || this.target;
  10794. };
  10795. // Cache
  10796. ArcRotateCamera.prototype._initCache = function () {
  10797. _super.prototype._initCache.call(this);
  10798. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10799. this._cache.alpha = undefined;
  10800. this._cache.beta = undefined;
  10801. this._cache.radius = undefined;
  10802. this._cache.targetScreenOffset = undefined;
  10803. };
  10804. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10805. if (!ignoreParentClass) {
  10806. _super.prototype._updateCache.call(this);
  10807. }
  10808. this._cache.target.copyFrom(this._getTargetPosition());
  10809. this._cache.alpha = this.alpha;
  10810. this._cache.beta = this.beta;
  10811. this._cache.radius = this.radius;
  10812. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10813. };
  10814. // Synchronized
  10815. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10816. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10817. return false;
  10818. return this._cache.target.equals(this._getTargetPosition())
  10819. && this._cache.alpha === this.alpha
  10820. && this._cache.beta === this.beta
  10821. && this._cache.radius === this.radius
  10822. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10823. };
  10824. // Methods
  10825. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10826. var _this = this;
  10827. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10828. var previousPinchDistance = 0;
  10829. var pointers = new BABYLON.SmartCollection();
  10830. if (this._attachedElement) {
  10831. return;
  10832. }
  10833. this._attachedElement = element;
  10834. var engine = this.getEngine();
  10835. if (this._onPointerDown === undefined) {
  10836. this._onPointerDown = function (evt) {
  10837. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10838. cacheSoloPointer = pointers.item(evt.pointerId);
  10839. if (!noPreventDefault) {
  10840. evt.preventDefault();
  10841. }
  10842. };
  10843. this._onPointerUp = function (evt) {
  10844. cacheSoloPointer = null;
  10845. previousPinchDistance = 0;
  10846. pointers.remove(evt.pointerId);
  10847. if (!noPreventDefault) {
  10848. evt.preventDefault();
  10849. }
  10850. };
  10851. this._onPointerMove = function (evt) {
  10852. if (!noPreventDefault) {
  10853. evt.preventDefault();
  10854. }
  10855. switch (pointers.count) {
  10856. case 1:
  10857. var offsetX = evt.clientX - cacheSoloPointer.x;
  10858. var offsetY = evt.clientY - cacheSoloPointer.y;
  10859. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10860. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10861. cacheSoloPointer.x = evt.clientX;
  10862. cacheSoloPointer.y = evt.clientY;
  10863. break;
  10864. case 2:
  10865. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10866. pointers.item(evt.pointerId).x = evt.clientX;
  10867. pointers.item(evt.pointerId).y = evt.clientY;
  10868. var direction = _this.pinchInwards ? 1 : -1;
  10869. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10870. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10871. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10872. if (previousPinchDistance === 0) {
  10873. previousPinchDistance = pinchSquaredDistance;
  10874. return;
  10875. }
  10876. if (pinchSquaredDistance !== previousPinchDistance) {
  10877. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10878. previousPinchDistance = pinchSquaredDistance;
  10879. }
  10880. break;
  10881. default:
  10882. if (pointers.item(evt.pointerId)) {
  10883. pointers.item(evt.pointerId).x = evt.clientX;
  10884. pointers.item(evt.pointerId).y = evt.clientY;
  10885. }
  10886. }
  10887. };
  10888. this._onMouseMove = function (evt) {
  10889. if (!engine.isPointerLock) {
  10890. return;
  10891. }
  10892. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10893. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10894. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10895. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10896. if (!noPreventDefault) {
  10897. evt.preventDefault();
  10898. }
  10899. };
  10900. this._wheel = function (event) {
  10901. var delta = 0;
  10902. if (event.wheelDelta) {
  10903. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10904. }
  10905. else if (event.detail) {
  10906. delta = -event.detail / _this.wheelPrecision;
  10907. }
  10908. if (delta)
  10909. _this.inertialRadiusOffset += delta;
  10910. if (event.preventDefault) {
  10911. if (!noPreventDefault) {
  10912. event.preventDefault();
  10913. }
  10914. }
  10915. };
  10916. this._onKeyDown = function (evt) {
  10917. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10918. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10919. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10920. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10921. var index = _this._keys.indexOf(evt.keyCode);
  10922. if (index === -1) {
  10923. _this._keys.push(evt.keyCode);
  10924. }
  10925. if (evt.preventDefault) {
  10926. if (!noPreventDefault) {
  10927. evt.preventDefault();
  10928. }
  10929. }
  10930. }
  10931. };
  10932. this._onKeyUp = function (evt) {
  10933. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10934. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10935. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10936. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10937. var index = _this._keys.indexOf(evt.keyCode);
  10938. if (index >= 0) {
  10939. _this._keys.splice(index, 1);
  10940. }
  10941. if (evt.preventDefault) {
  10942. if (!noPreventDefault) {
  10943. evt.preventDefault();
  10944. }
  10945. }
  10946. }
  10947. };
  10948. this._onLostFocus = function () {
  10949. _this._keys = [];
  10950. pointers.empty();
  10951. previousPinchDistance = 0;
  10952. cacheSoloPointer = null;
  10953. };
  10954. this._onGestureStart = function (e) {
  10955. if (window.MSGesture === undefined) {
  10956. return;
  10957. }
  10958. if (!_this._MSGestureHandler) {
  10959. _this._MSGestureHandler = new MSGesture();
  10960. _this._MSGestureHandler.target = element;
  10961. }
  10962. _this._MSGestureHandler.addPointer(e.pointerId);
  10963. };
  10964. this._onGesture = function (e) {
  10965. _this.radius *= e.scale;
  10966. if (e.preventDefault) {
  10967. if (!noPreventDefault) {
  10968. e.stopPropagation();
  10969. e.preventDefault();
  10970. }
  10971. }
  10972. };
  10973. this._reset = function () {
  10974. _this._keys = [];
  10975. _this.inertialAlphaOffset = 0;
  10976. _this.inertialBetaOffset = 0;
  10977. _this.inertialRadiusOffset = 0;
  10978. pointers.empty();
  10979. previousPinchDistance = 0;
  10980. cacheSoloPointer = null;
  10981. };
  10982. }
  10983. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10984. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10985. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10986. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10987. element.addEventListener("mousemove", this._onMouseMove, false);
  10988. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10989. element.addEventListener("MSGestureChange", this._onGesture, false);
  10990. element.addEventListener('mousewheel', this._wheel, false);
  10991. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10992. BABYLON.Tools.RegisterTopRootEvents([
  10993. { name: "keydown", handler: this._onKeyDown },
  10994. { name: "keyup", handler: this._onKeyUp },
  10995. { name: "blur", handler: this._onLostFocus }
  10996. ]);
  10997. };
  10998. ArcRotateCamera.prototype.detachControl = function (element) {
  10999. if (this._attachedElement !== element) {
  11000. return;
  11001. }
  11002. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11003. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11004. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11005. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11006. element.removeEventListener("mousemove", this._onMouseMove);
  11007. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11008. element.removeEventListener("MSGestureChange", this._onGesture);
  11009. element.removeEventListener('mousewheel', this._wheel);
  11010. element.removeEventListener('DOMMouseScroll', this._wheel);
  11011. BABYLON.Tools.UnregisterTopRootEvents([
  11012. { name: "keydown", handler: this._onKeyDown },
  11013. { name: "keyup", handler: this._onKeyUp },
  11014. { name: "blur", handler: this._onLostFocus }
  11015. ]);
  11016. this._MSGestureHandler = null;
  11017. this._attachedElement = null;
  11018. if (this._reset) {
  11019. this._reset();
  11020. }
  11021. };
  11022. ArcRotateCamera.prototype._checkInputs = function () {
  11023. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11024. if (this._collisionTriggered) {
  11025. return;
  11026. }
  11027. // Keyboard
  11028. for (var index = 0; index < this._keys.length; index++) {
  11029. var keyCode = this._keys[index];
  11030. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11031. this.inertialAlphaOffset -= 0.01;
  11032. }
  11033. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11034. this.inertialBetaOffset -= 0.01;
  11035. }
  11036. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11037. this.inertialAlphaOffset += 0.01;
  11038. }
  11039. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11040. this.inertialBetaOffset += 0.01;
  11041. }
  11042. }
  11043. // Inertia
  11044. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11045. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11046. this.beta += this.inertialBetaOffset;
  11047. this.radius -= this.inertialRadiusOffset;
  11048. this.inertialAlphaOffset *= this.inertia;
  11049. this.inertialBetaOffset *= this.inertia;
  11050. this.inertialRadiusOffset *= this.inertia;
  11051. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11052. this.inertialAlphaOffset = 0;
  11053. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11054. this.inertialBetaOffset = 0;
  11055. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11056. this.inertialRadiusOffset = 0;
  11057. }
  11058. // Limits
  11059. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11060. if (this.allowUpsideDown && this.beta > Math.PI) {
  11061. this.beta = this.beta - (2 * Math.PI);
  11062. }
  11063. }
  11064. else {
  11065. if (this.beta < this.lowerBetaLimit) {
  11066. this.beta = this.lowerBetaLimit;
  11067. }
  11068. }
  11069. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11070. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11071. this.beta = this.beta + (2 * Math.PI);
  11072. }
  11073. }
  11074. else {
  11075. if (this.beta > this.upperBetaLimit) {
  11076. this.beta = this.upperBetaLimit;
  11077. }
  11078. }
  11079. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11080. this.alpha = this.lowerAlphaLimit;
  11081. }
  11082. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11083. this.alpha = this.upperAlphaLimit;
  11084. }
  11085. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11086. this.radius = this.lowerRadiusLimit;
  11087. }
  11088. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11089. this.radius = this.upperRadiusLimit;
  11090. }
  11091. _super.prototype._checkInputs.call(this);
  11092. };
  11093. ArcRotateCamera.prototype.setPosition = function (position) {
  11094. var radiusv3 = position.subtract(this._getTargetPosition());
  11095. this.radius = radiusv3.length();
  11096. // Alpha
  11097. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11098. if (radiusv3.z < 0) {
  11099. this.alpha = 2 * Math.PI - this.alpha;
  11100. }
  11101. // Beta
  11102. this.beta = Math.acos(radiusv3.y / this.radius);
  11103. };
  11104. ArcRotateCamera.prototype._getViewMatrix = function () {
  11105. // Compute
  11106. var cosa = Math.cos(this.alpha);
  11107. var sina = Math.sin(this.alpha);
  11108. var cosb = Math.cos(this.beta);
  11109. var sinb = Math.sin(this.beta);
  11110. var target = this._getTargetPosition();
  11111. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  11112. if (this.checkCollisions) {
  11113. this._collider.radius = this.collisionRadius;
  11114. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  11115. this._collisionTriggered = true;
  11116. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11117. }
  11118. var up = this.upVector;
  11119. if (this.allowUpsideDown && this.beta < 0) {
  11120. var up = up.clone();
  11121. up = up.negate();
  11122. }
  11123. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11124. this._previousAlpha = this.alpha;
  11125. this._previousBeta = this.beta;
  11126. this._previousRadius = this.radius;
  11127. this._previousPosition.copyFrom(this.position);
  11128. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11129. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11130. return this._viewMatrix;
  11131. };
  11132. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11133. meshes = meshes || this.getScene().meshes;
  11134. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11135. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11136. this.radius = distance * this.zoomOnFactor;
  11137. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11138. };
  11139. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11140. var meshesOrMinMaxVector;
  11141. var distance;
  11142. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11143. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11144. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11145. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11146. }
  11147. else {
  11148. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11149. distance = meshesOrMinMaxVectorAndDistance.distance;
  11150. }
  11151. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11152. this.maxZ = distance * 2;
  11153. };
  11154. /**
  11155. * @override
  11156. * needs to be overridden, so sub has required properties to be copied
  11157. */
  11158. ArcRotateCamera.prototype.getSubCamera = function (name, isA) {
  11159. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  11160. return new BABYLON.ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  11161. };
  11162. /**
  11163. * @override
  11164. * needs to be overridden, adding copy of alpha, beta & radius
  11165. */
  11166. ArcRotateCamera.prototype._updateSubCameras = function () {
  11167. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  11168. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  11169. camA.alpha = this.alpha - this._subCamHalfSpace;
  11170. camB.alpha = this.alpha + this._subCamHalfSpace;
  11171. camA.beta = camB.beta = this.beta;
  11172. camA.radius = camB.radius = this.radius;
  11173. _super.prototype._updateSubCameras.call(this);
  11174. };
  11175. return ArcRotateCamera;
  11176. })(BABYLON.Camera);
  11177. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11178. })(BABYLON || (BABYLON = {}));
  11179. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11180. var __extends = (this && this.__extends) || function (d, b) {
  11181. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11182. function __() { this.constructor = d; }
  11183. __.prototype = b.prototype;
  11184. d.prototype = new __();
  11185. };
  11186. var BABYLON;
  11187. (function (BABYLON) {
  11188. // We're mainly based on the logic defined into the FreeCamera code
  11189. var DeviceOrientationCamera = (function (_super) {
  11190. __extends(DeviceOrientationCamera, _super);
  11191. function DeviceOrientationCamera(name, position, scene) {
  11192. var _this = this;
  11193. _super.call(this, name, position, scene);
  11194. this._offsetX = null;
  11195. this._offsetY = null;
  11196. this._orientationGamma = 0;
  11197. this._orientationBeta = 0;
  11198. this._initialOrientationGamma = 0;
  11199. this._initialOrientationBeta = 0;
  11200. this.angularSensibility = 10000.0;
  11201. this.moveSensibility = 50.0;
  11202. window.addEventListener("resize", function () {
  11203. _this._initialOrientationGamma = null;
  11204. }, false);
  11205. }
  11206. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11207. var _this = this;
  11208. if (this._attachedCanvas) {
  11209. return;
  11210. }
  11211. this._attachedCanvas = canvas;
  11212. if (!this._orientationChanged) {
  11213. this._orientationChanged = function (evt) {
  11214. if (!_this._initialOrientationGamma) {
  11215. _this._initialOrientationGamma = evt.gamma;
  11216. _this._initialOrientationBeta = evt.beta;
  11217. }
  11218. _this._orientationGamma = evt.gamma;
  11219. _this._orientationBeta = evt.beta;
  11220. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11221. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11222. };
  11223. }
  11224. window.addEventListener("deviceorientation", this._orientationChanged);
  11225. };
  11226. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11227. if (this._attachedCanvas != canvas) {
  11228. return;
  11229. }
  11230. window.removeEventListener("deviceorientation", this._orientationChanged);
  11231. this._attachedCanvas = null;
  11232. this._orientationGamma = 0;
  11233. this._orientationBeta = 0;
  11234. this._initialOrientationGamma = 0;
  11235. this._initialOrientationBeta = 0;
  11236. };
  11237. DeviceOrientationCamera.prototype._checkInputs = function () {
  11238. if (!this._offsetX) {
  11239. return;
  11240. }
  11241. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11242. var speed = this._computeLocalCameraSpeed();
  11243. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11244. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11245. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11246. _super.prototype._checkInputs.call(this);
  11247. };
  11248. return DeviceOrientationCamera;
  11249. })(BABYLON.FreeCamera);
  11250. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11251. })(BABYLON || (BABYLON = {}));
  11252. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11253. var __extends = (this && this.__extends) || function (d, b) {
  11254. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11255. function __() { this.constructor = d; }
  11256. __.prototype = b.prototype;
  11257. d.prototype = new __();
  11258. };
  11259. var BABYLON;
  11260. (function (BABYLON) {
  11261. var Gamepads = (function () {
  11262. function Gamepads(ongamedpadconnected) {
  11263. var _this = this;
  11264. this.babylonGamepads = [];
  11265. this.oneGamepadConnected = false;
  11266. this.isMonitoring = false;
  11267. this.gamepadEventSupported = 'GamepadEvent' in window;
  11268. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11269. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11270. 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=";
  11271. this._callbackGamepadConnected = ongamedpadconnected;
  11272. if (this.gamepadSupportAvailable) {
  11273. // Checking if the gamepad connected event is supported (like in Firefox)
  11274. if (this.gamepadEventSupported) {
  11275. window.addEventListener('gamepadconnected', function (evt) {
  11276. _this._onGamepadConnected(evt);
  11277. }, false);
  11278. window.addEventListener('gamepaddisconnected', function (evt) {
  11279. _this._onGamepadDisconnected(evt);
  11280. }, false);
  11281. }
  11282. else {
  11283. this._startMonitoringGamepads();
  11284. }
  11285. if (!this.oneGamepadConnected) {
  11286. this._insertGamepadDOMInstructions();
  11287. }
  11288. }
  11289. else {
  11290. this._insertGamepadDOMNotSupported();
  11291. }
  11292. }
  11293. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11294. Gamepads.gamepadDOMInfo = document.createElement("div");
  11295. var buttonAImage = document.createElement("img");
  11296. buttonAImage.src = this.buttonADataURL;
  11297. var spanMessage = document.createElement("span");
  11298. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11299. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11300. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11301. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11302. Gamepads.gamepadDOMInfo.style.width = "100%";
  11303. Gamepads.gamepadDOMInfo.style.height = "48px";
  11304. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11305. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11306. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11307. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11308. buttonAImage.style.position = "relative";
  11309. buttonAImage.style.bottom = "8px";
  11310. spanMessage.style.position = "relative";
  11311. spanMessage.style.fontSize = "32px";
  11312. spanMessage.style.bottom = "32px";
  11313. spanMessage.style.color = "green";
  11314. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11315. };
  11316. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11317. Gamepads.gamepadDOMInfo = document.createElement("div");
  11318. var spanMessage = document.createElement("span");
  11319. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11320. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11321. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11322. Gamepads.gamepadDOMInfo.style.width = "100%";
  11323. Gamepads.gamepadDOMInfo.style.height = "40px";
  11324. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11325. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11326. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11327. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11328. spanMessage.style.position = "relative";
  11329. spanMessage.style.fontSize = "32px";
  11330. spanMessage.style.color = "red";
  11331. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11332. };
  11333. Gamepads.prototype.dispose = function () {
  11334. if (Gamepads.gamepadDOMInfo) {
  11335. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11336. }
  11337. };
  11338. Gamepads.prototype._onGamepadConnected = function (evt) {
  11339. var newGamepad = this._addNewGamepad(evt.gamepad);
  11340. if (this._callbackGamepadConnected)
  11341. this._callbackGamepadConnected(newGamepad);
  11342. this._startMonitoringGamepads();
  11343. };
  11344. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11345. if (!this.oneGamepadConnected) {
  11346. this.oneGamepadConnected = true;
  11347. if (Gamepads.gamepadDOMInfo) {
  11348. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11349. Gamepads.gamepadDOMInfo = null;
  11350. }
  11351. }
  11352. var newGamepad;
  11353. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11354. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11355. }
  11356. else {
  11357. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  11358. }
  11359. this.babylonGamepads.push(newGamepad);
  11360. return newGamepad;
  11361. };
  11362. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11363. // Remove the gamepad from the list of gamepads to monitor.
  11364. for (var i in this.babylonGamepads) {
  11365. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11366. this.babylonGamepads.splice(i, 1);
  11367. break;
  11368. }
  11369. }
  11370. // If no gamepads are left, stop the polling loop.
  11371. if (this.babylonGamepads.length == 0) {
  11372. this._stopMonitoringGamepads();
  11373. }
  11374. };
  11375. Gamepads.prototype._startMonitoringGamepads = function () {
  11376. if (!this.isMonitoring) {
  11377. this.isMonitoring = true;
  11378. this._checkGamepadsStatus();
  11379. }
  11380. };
  11381. Gamepads.prototype._stopMonitoringGamepads = function () {
  11382. this.isMonitoring = false;
  11383. };
  11384. Gamepads.prototype._checkGamepadsStatus = function () {
  11385. var _this = this;
  11386. // updating gamepad objects
  11387. this._updateGamepadObjects();
  11388. for (var i in this.babylonGamepads) {
  11389. this.babylonGamepads[i].update();
  11390. }
  11391. if (this.isMonitoring) {
  11392. if (window.requestAnimationFrame) {
  11393. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11394. }
  11395. else if (window.mozRequestAnimationFrame) {
  11396. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11397. }
  11398. else if (window.webkitRequestAnimationFrame) {
  11399. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11400. }
  11401. }
  11402. };
  11403. // This function is called only on Chrome, which does not yet support
  11404. // connection/disconnection events, but requires you to monitor
  11405. // an array for changes.
  11406. Gamepads.prototype._updateGamepadObjects = function () {
  11407. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11408. for (var i = 0; i < gamepads.length; i++) {
  11409. if (gamepads[i]) {
  11410. if (!(gamepads[i].index in this.babylonGamepads)) {
  11411. var newGamepad = this._addNewGamepad(gamepads[i]);
  11412. if (this._callbackGamepadConnected) {
  11413. this._callbackGamepadConnected(newGamepad);
  11414. }
  11415. }
  11416. else {
  11417. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11418. }
  11419. }
  11420. }
  11421. };
  11422. return Gamepads;
  11423. })();
  11424. BABYLON.Gamepads = Gamepads;
  11425. var StickValues = (function () {
  11426. function StickValues(x, y) {
  11427. this.x = x;
  11428. this.y = y;
  11429. }
  11430. return StickValues;
  11431. })();
  11432. BABYLON.StickValues = StickValues;
  11433. var Gamepad = (function () {
  11434. function Gamepad(id, index, browserGamepad) {
  11435. this.id = id;
  11436. this.index = index;
  11437. this.browserGamepad = browserGamepad;
  11438. if (this.browserGamepad.axes.length >= 2) {
  11439. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11440. }
  11441. if (this.browserGamepad.axes.length >= 4) {
  11442. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11443. }
  11444. }
  11445. Gamepad.prototype.onleftstickchanged = function (callback) {
  11446. this._onleftstickchanged = callback;
  11447. };
  11448. Gamepad.prototype.onrightstickchanged = function (callback) {
  11449. this._onrightstickchanged = callback;
  11450. };
  11451. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11452. get: function () {
  11453. return this._leftStick;
  11454. },
  11455. set: function (newValues) {
  11456. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11457. this._onleftstickchanged(newValues);
  11458. }
  11459. this._leftStick = newValues;
  11460. },
  11461. enumerable: true,
  11462. configurable: true
  11463. });
  11464. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11465. get: function () {
  11466. return this._rightStick;
  11467. },
  11468. set: function (newValues) {
  11469. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11470. this._onrightstickchanged(newValues);
  11471. }
  11472. this._rightStick = newValues;
  11473. },
  11474. enumerable: true,
  11475. configurable: true
  11476. });
  11477. Gamepad.prototype.update = function () {
  11478. if (this._leftStick) {
  11479. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11480. }
  11481. if (this._rightStick) {
  11482. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11483. }
  11484. };
  11485. return Gamepad;
  11486. })();
  11487. BABYLON.Gamepad = Gamepad;
  11488. var GenericPad = (function (_super) {
  11489. __extends(GenericPad, _super);
  11490. function GenericPad(id, index, gamepad) {
  11491. _super.call(this, id, index, gamepad);
  11492. this.id = id;
  11493. this.index = index;
  11494. this.gamepad = gamepad;
  11495. this._buttons = new Array(gamepad.buttons.length);
  11496. }
  11497. GenericPad.prototype.onbuttondown = function (callback) {
  11498. this._onbuttondown = callback;
  11499. };
  11500. GenericPad.prototype.onbuttonup = function (callback) {
  11501. this._onbuttonup = callback;
  11502. };
  11503. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11504. if (newValue !== currentValue) {
  11505. if (this._onbuttondown && newValue === 1) {
  11506. this._onbuttondown(buttonIndex);
  11507. }
  11508. if (this._onbuttonup && newValue === 0) {
  11509. this._onbuttonup(buttonIndex);
  11510. }
  11511. }
  11512. return newValue;
  11513. };
  11514. GenericPad.prototype.update = function () {
  11515. _super.prototype.update.call(this);
  11516. for (var index = 0; index < this._buttons.length; index++) {
  11517. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11518. }
  11519. };
  11520. return GenericPad;
  11521. })(Gamepad);
  11522. BABYLON.GenericPad = GenericPad;
  11523. (function (Xbox360Button) {
  11524. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11525. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11526. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11527. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11528. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11529. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11530. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11531. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11532. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11533. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11534. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11535. var Xbox360Button = BABYLON.Xbox360Button;
  11536. (function (Xbox360Dpad) {
  11537. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11538. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11539. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11540. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11541. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11542. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11543. var Xbox360Pad = (function (_super) {
  11544. __extends(Xbox360Pad, _super);
  11545. function Xbox360Pad() {
  11546. _super.apply(this, arguments);
  11547. this._leftTrigger = 0;
  11548. this._rightTrigger = 0;
  11549. this._buttonA = 0;
  11550. this._buttonB = 0;
  11551. this._buttonX = 0;
  11552. this._buttonY = 0;
  11553. this._buttonBack = 0;
  11554. this._buttonStart = 0;
  11555. this._buttonLB = 0;
  11556. this._buttonRB = 0;
  11557. this._buttonLeftStick = 0;
  11558. this._buttonRightStick = 0;
  11559. this._dPadUp = 0;
  11560. this._dPadDown = 0;
  11561. this._dPadLeft = 0;
  11562. this._dPadRight = 0;
  11563. }
  11564. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11565. this._onlefttriggerchanged = callback;
  11566. };
  11567. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11568. this._onrighttriggerchanged = callback;
  11569. };
  11570. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11571. get: function () {
  11572. return this._leftTrigger;
  11573. },
  11574. set: function (newValue) {
  11575. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11576. this._onlefttriggerchanged(newValue);
  11577. }
  11578. this._leftTrigger = newValue;
  11579. },
  11580. enumerable: true,
  11581. configurable: true
  11582. });
  11583. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11584. get: function () {
  11585. return this._rightTrigger;
  11586. },
  11587. set: function (newValue) {
  11588. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11589. this._onrighttriggerchanged(newValue);
  11590. }
  11591. this._rightTrigger = newValue;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11597. this._onbuttondown = callback;
  11598. };
  11599. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11600. this._onbuttonup = callback;
  11601. };
  11602. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11603. this._ondpaddown = callback;
  11604. };
  11605. Xbox360Pad.prototype.ondpadup = function (callback) {
  11606. this._ondpadup = callback;
  11607. };
  11608. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11609. if (newValue !== currentValue) {
  11610. if (this._onbuttondown && newValue === 1) {
  11611. this._onbuttondown(buttonType);
  11612. }
  11613. if (this._onbuttonup && newValue === 0) {
  11614. this._onbuttonup(buttonType);
  11615. }
  11616. }
  11617. return newValue;
  11618. };
  11619. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11620. if (newValue !== currentValue) {
  11621. if (this._ondpaddown && newValue === 1) {
  11622. this._ondpaddown(buttonType);
  11623. }
  11624. if (this._ondpadup && newValue === 0) {
  11625. this._ondpadup(buttonType);
  11626. }
  11627. }
  11628. return newValue;
  11629. };
  11630. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11631. get: function () {
  11632. return this._buttonA;
  11633. },
  11634. set: function (value) {
  11635. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11636. },
  11637. enumerable: true,
  11638. configurable: true
  11639. });
  11640. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11641. get: function () {
  11642. return this._buttonB;
  11643. },
  11644. set: function (value) {
  11645. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11651. get: function () {
  11652. return this._buttonX;
  11653. },
  11654. set: function (value) {
  11655. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11661. get: function () {
  11662. return this._buttonY;
  11663. },
  11664. set: function (value) {
  11665. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11666. },
  11667. enumerable: true,
  11668. configurable: true
  11669. });
  11670. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11671. get: function () {
  11672. return this._buttonStart;
  11673. },
  11674. set: function (value) {
  11675. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11676. },
  11677. enumerable: true,
  11678. configurable: true
  11679. });
  11680. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11681. get: function () {
  11682. return this._buttonBack;
  11683. },
  11684. set: function (value) {
  11685. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11691. get: function () {
  11692. return this._buttonLB;
  11693. },
  11694. set: function (value) {
  11695. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11701. get: function () {
  11702. return this._buttonRB;
  11703. },
  11704. set: function (value) {
  11705. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11706. },
  11707. enumerable: true,
  11708. configurable: true
  11709. });
  11710. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11711. get: function () {
  11712. return this._buttonLeftStick;
  11713. },
  11714. set: function (value) {
  11715. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11721. get: function () {
  11722. return this._buttonRightStick;
  11723. },
  11724. set: function (value) {
  11725. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11731. get: function () {
  11732. return this._dPadUp;
  11733. },
  11734. set: function (value) {
  11735. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11741. get: function () {
  11742. return this._dPadDown;
  11743. },
  11744. set: function (value) {
  11745. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  11746. },
  11747. enumerable: true,
  11748. configurable: true
  11749. });
  11750. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11751. get: function () {
  11752. return this._dPadLeft;
  11753. },
  11754. set: function (value) {
  11755. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11761. get: function () {
  11762. return this._dPadRight;
  11763. },
  11764. set: function (value) {
  11765. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Xbox360Pad.prototype.update = function () {
  11771. _super.prototype.update.call(this);
  11772. this.buttonA = this.browserGamepad.buttons[0].value;
  11773. this.buttonB = this.browserGamepad.buttons[1].value;
  11774. this.buttonX = this.browserGamepad.buttons[2].value;
  11775. this.buttonY = this.browserGamepad.buttons[3].value;
  11776. this.buttonLB = this.browserGamepad.buttons[4].value;
  11777. this.buttonRB = this.browserGamepad.buttons[5].value;
  11778. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11779. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11780. this.buttonBack = this.browserGamepad.buttons[8].value;
  11781. this.buttonStart = this.browserGamepad.buttons[9].value;
  11782. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11783. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11784. this.dPadUp = this.browserGamepad.buttons[12].value;
  11785. this.dPadDown = this.browserGamepad.buttons[13].value;
  11786. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11787. this.dPadRight = this.browserGamepad.buttons[15].value;
  11788. };
  11789. return Xbox360Pad;
  11790. })(Gamepad);
  11791. BABYLON.Xbox360Pad = Xbox360Pad;
  11792. })(BABYLON || (BABYLON = {}));
  11793. //# sourceMappingURL=babylon.gamepads.js.map
  11794. var __extends = (this && this.__extends) || function (d, b) {
  11795. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11796. function __() { this.constructor = d; }
  11797. __.prototype = b.prototype;
  11798. d.prototype = new __();
  11799. };
  11800. var BABYLON;
  11801. (function (BABYLON) {
  11802. // We're mainly based on the logic defined into the FreeCamera code
  11803. var GamepadCamera = (function (_super) {
  11804. __extends(GamepadCamera, _super);
  11805. function GamepadCamera(name, position, scene) {
  11806. var _this = this;
  11807. _super.call(this, name, position, scene);
  11808. this.angularSensibility = 200;
  11809. this.moveSensibility = 75;
  11810. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11811. }
  11812. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11813. // Only the first gamepad can control the camera
  11814. if (gamepad.index === 0) {
  11815. this._gamepad = gamepad;
  11816. }
  11817. };
  11818. GamepadCamera.prototype._checkInputs = function () {
  11819. if (this._gamepad) {
  11820. var LSValues = this._gamepad.leftStick;
  11821. var normalizedLX = LSValues.x / this.moveSensibility;
  11822. var normalizedLY = LSValues.y / this.moveSensibility;
  11823. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11824. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11825. var RSValues = this._gamepad.rightStick;
  11826. var normalizedRX = RSValues.x / this.angularSensibility;
  11827. var normalizedRY = RSValues.y / this.angularSensibility;
  11828. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11829. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11830. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11831. var speed = this._computeLocalCameraSpeed() * 50.0;
  11832. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11833. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11834. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11835. }
  11836. _super.prototype._checkInputs.call(this);
  11837. };
  11838. GamepadCamera.prototype.dispose = function () {
  11839. this._gamepads.dispose();
  11840. _super.prototype.dispose.call(this);
  11841. };
  11842. return GamepadCamera;
  11843. })(BABYLON.FreeCamera);
  11844. BABYLON.GamepadCamera = GamepadCamera;
  11845. })(BABYLON || (BABYLON = {}));
  11846. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11847. var BABYLON;
  11848. (function (BABYLON) {
  11849. var RenderingManager = (function () {
  11850. function RenderingManager(scene) {
  11851. this._renderingGroups = new Array();
  11852. this._scene = scene;
  11853. }
  11854. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11855. if (this._scene._activeParticleSystems.length === 0) {
  11856. return;
  11857. }
  11858. // Particles
  11859. var beforeParticlesDate = BABYLON.Tools.Now;
  11860. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11861. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11862. if (particleSystem.renderingGroupId !== index) {
  11863. continue;
  11864. }
  11865. this._clearDepthBuffer();
  11866. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11867. this._scene._activeParticles += particleSystem.render();
  11868. }
  11869. }
  11870. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11871. };
  11872. RenderingManager.prototype._renderSprites = function (index) {
  11873. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11874. return;
  11875. }
  11876. // Sprites
  11877. var beforeSpritessDate = BABYLON.Tools.Now;
  11878. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11879. var spriteManager = this._scene.spriteManagers[id];
  11880. if (spriteManager.renderingGroupId === index) {
  11881. this._clearDepthBuffer();
  11882. spriteManager.render();
  11883. }
  11884. }
  11885. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11886. };
  11887. RenderingManager.prototype._clearDepthBuffer = function () {
  11888. if (this._depthBufferAlreadyCleaned) {
  11889. return;
  11890. }
  11891. this._scene.getEngine().clear(0, false, true);
  11892. this._depthBufferAlreadyCleaned = true;
  11893. };
  11894. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11895. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11896. this._depthBufferAlreadyCleaned = false;
  11897. var renderingGroup = this._renderingGroups[index];
  11898. var needToStepBack = false;
  11899. if (renderingGroup) {
  11900. this._clearDepthBuffer();
  11901. if (!renderingGroup.render(customRenderFunction)) {
  11902. this._renderingGroups.splice(index, 1);
  11903. needToStepBack = true;
  11904. }
  11905. }
  11906. if (renderSprites) {
  11907. this._renderSprites(index);
  11908. }
  11909. if (renderParticles) {
  11910. this._renderParticles(index, activeMeshes);
  11911. }
  11912. if (needToStepBack) {
  11913. index--;
  11914. }
  11915. }
  11916. };
  11917. RenderingManager.prototype.reset = function () {
  11918. for (var index in this._renderingGroups) {
  11919. var renderingGroup = this._renderingGroups[index];
  11920. renderingGroup.prepare();
  11921. }
  11922. };
  11923. RenderingManager.prototype.dispatch = function (subMesh) {
  11924. var mesh = subMesh.getMesh();
  11925. var renderingGroupId = mesh.renderingGroupId || 0;
  11926. if (!this._renderingGroups[renderingGroupId]) {
  11927. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11928. }
  11929. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11930. };
  11931. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11932. return RenderingManager;
  11933. })();
  11934. BABYLON.RenderingManager = RenderingManager;
  11935. })(BABYLON || (BABYLON = {}));
  11936. //# sourceMappingURL=babylon.renderingManager.js.map
  11937. var BABYLON;
  11938. (function (BABYLON) {
  11939. var RenderingGroup = (function () {
  11940. function RenderingGroup(index, scene) {
  11941. this.index = index;
  11942. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11943. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11944. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11945. this._scene = scene;
  11946. }
  11947. RenderingGroup.prototype.render = function (customRenderFunction) {
  11948. if (customRenderFunction) {
  11949. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11950. return true;
  11951. }
  11952. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11953. return false;
  11954. }
  11955. var engine = this._scene.getEngine();
  11956. // Opaque
  11957. var subIndex;
  11958. var submesh;
  11959. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11960. submesh = this._opaqueSubMeshes.data[subIndex];
  11961. submesh.render();
  11962. }
  11963. // Alpha test
  11964. engine.setAlphaTesting(true);
  11965. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11966. submesh = this._alphaTestSubMeshes.data[subIndex];
  11967. submesh.render();
  11968. }
  11969. engine.setAlphaTesting(false);
  11970. // Transparent
  11971. if (this._transparentSubMeshes.length) {
  11972. // Sorting
  11973. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11974. submesh = this._transparentSubMeshes.data[subIndex];
  11975. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11976. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11977. }
  11978. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11979. sortedArray.sort(function (a, b) {
  11980. // Alpha index first
  11981. if (a._alphaIndex > b._alphaIndex) {
  11982. return 1;
  11983. }
  11984. if (a._alphaIndex < b._alphaIndex) {
  11985. return -1;
  11986. }
  11987. // Then distance to camera
  11988. if (a._distanceToCamera < b._distanceToCamera) {
  11989. return 1;
  11990. }
  11991. if (a._distanceToCamera > b._distanceToCamera) {
  11992. return -1;
  11993. }
  11994. return 0;
  11995. });
  11996. // Rendering
  11997. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11998. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11999. submesh = sortedArray[subIndex];
  12000. submesh.render();
  12001. }
  12002. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12003. }
  12004. return true;
  12005. };
  12006. RenderingGroup.prototype.prepare = function () {
  12007. this._opaqueSubMeshes.reset();
  12008. this._transparentSubMeshes.reset();
  12009. this._alphaTestSubMeshes.reset();
  12010. };
  12011. RenderingGroup.prototype.dispatch = function (subMesh) {
  12012. var material = subMesh.getMaterial();
  12013. var mesh = subMesh.getMesh();
  12014. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12015. this._transparentSubMeshes.push(subMesh);
  12016. }
  12017. else if (material.needAlphaTesting()) {
  12018. this._alphaTestSubMeshes.push(subMesh);
  12019. }
  12020. else {
  12021. this._opaqueSubMeshes.push(subMesh); // Opaque
  12022. }
  12023. };
  12024. return RenderingGroup;
  12025. })();
  12026. BABYLON.RenderingGroup = RenderingGroup;
  12027. })(BABYLON || (BABYLON = {}));
  12028. //# sourceMappingURL=babylon.renderingGroup.js.map
  12029. var BABYLON;
  12030. (function (BABYLON) {
  12031. /**
  12032. * Represents a scene to be rendered by the engine.
  12033. * @see http://doc.babylonjs.com/page.php?p=21911
  12034. */
  12035. var Scene = (function () {
  12036. /**
  12037. * @constructor
  12038. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12039. */
  12040. function Scene(engine) {
  12041. // Members
  12042. this.autoClear = true;
  12043. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12044. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12045. this.forceWireframe = false;
  12046. this.forcePointsCloud = false;
  12047. this.forceShowBoundingBoxes = false;
  12048. this.animationsEnabled = true;
  12049. 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
  12050. // Fog
  12051. /**
  12052. * is fog enabled on this scene.
  12053. * @type {boolean}
  12054. */
  12055. this.fogEnabled = true;
  12056. this.fogMode = Scene.FOGMODE_NONE;
  12057. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12058. this.fogDensity = 0.1;
  12059. this.fogStart = 0;
  12060. this.fogEnd = 1000.0;
  12061. // Lights
  12062. /**
  12063. * is shadow enabled on this scene.
  12064. * @type {boolean}
  12065. */
  12066. this.shadowsEnabled = true;
  12067. /**
  12068. * is light enabled on this scene.
  12069. * @type {boolean}
  12070. */
  12071. this.lightsEnabled = true;
  12072. /**
  12073. * All of the lights added to this scene.
  12074. * @see BABYLON.Light
  12075. * @type {BABYLON.Light[]}
  12076. */
  12077. this.lights = new Array();
  12078. // Cameras
  12079. /**
  12080. * All of the cameras added to this scene.
  12081. * @see BABYLON.Camera
  12082. * @type {BABYLON.Camera[]}
  12083. */
  12084. this.cameras = new Array();
  12085. this.activeCameras = new Array();
  12086. // Meshes
  12087. /**
  12088. * All of the (abstract) meshes added to this scene.
  12089. * @see BABYLON.AbstractMesh
  12090. * @type {BABYLON.AbstractMesh[]}
  12091. */
  12092. this.meshes = new Array();
  12093. // Geometries
  12094. this._geometries = new Array();
  12095. this.materials = new Array();
  12096. this.multiMaterials = new Array();
  12097. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12098. // Textures
  12099. this.texturesEnabled = true;
  12100. this.textures = new Array();
  12101. // Particles
  12102. this.particlesEnabled = true;
  12103. this.particleSystems = new Array();
  12104. // Sprites
  12105. this.spritesEnabled = true;
  12106. this.spriteManagers = new Array();
  12107. // Layers
  12108. this.layers = new Array();
  12109. // Skeletons
  12110. this.skeletonsEnabled = true;
  12111. this.skeletons = new Array();
  12112. // Lens flares
  12113. this.lensFlaresEnabled = true;
  12114. this.lensFlareSystems = new Array();
  12115. // Collisions
  12116. this.collisionsEnabled = true;
  12117. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  12118. // Postprocesses
  12119. this.postProcessesEnabled = true;
  12120. // Customs render targets
  12121. this.renderTargetsEnabled = true;
  12122. this.dumpNextRenderTargets = false;
  12123. this.customRenderTargets = new Array();
  12124. // Imported meshes
  12125. this.importedMeshesFiles = new Array();
  12126. this._actionManagers = new Array();
  12127. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12128. // Procedural textures
  12129. this.proceduralTexturesEnabled = true;
  12130. this._proceduralTextures = new Array();
  12131. this.soundTracks = new Array();
  12132. this._audioEnabled = true;
  12133. this._headphone = false;
  12134. this._totalVertices = 0;
  12135. this._activeIndices = 0;
  12136. this._activeParticles = 0;
  12137. this._lastFrameDuration = 0;
  12138. this._evaluateActiveMeshesDuration = 0;
  12139. this._renderTargetsDuration = 0;
  12140. this._particlesDuration = 0;
  12141. this._renderDuration = 0;
  12142. this._spritesDuration = 0;
  12143. this._animationRatio = 0;
  12144. this._renderId = 0;
  12145. this._executeWhenReadyTimeoutId = -1;
  12146. this._toBeDisposed = new BABYLON.SmartArray(256);
  12147. this._onReadyCallbacks = new Array();
  12148. this._pendingData = []; //ANY
  12149. this._onBeforeRenderCallbacks = new Array();
  12150. this._onAfterRenderCallbacks = new Array();
  12151. this._activeMeshes = new BABYLON.SmartArray(256);
  12152. this._processedMaterials = new BABYLON.SmartArray(256);
  12153. this._renderTargets = new BABYLON.SmartArray(256);
  12154. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12155. this._activeSkeletons = new BABYLON.SmartArray(32);
  12156. this._activeBones = 0;
  12157. this._activeAnimatables = new Array();
  12158. this._transformMatrix = BABYLON.Matrix.Zero();
  12159. this._uniqueIdCounter = 0;
  12160. this._engine = engine;
  12161. engine.scenes.push(this);
  12162. this._renderingManager = new BABYLON.RenderingManager(this);
  12163. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12164. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12165. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12166. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12167. this.attachControl();
  12168. this._debugLayer = new BABYLON.DebugLayer(this);
  12169. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12170. //simplification queue
  12171. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12172. //collision coordinator initialization. For now legacy per default.
  12173. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12174. }
  12175. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12176. get: function () {
  12177. return Scene._FOGMODE_NONE;
  12178. },
  12179. enumerable: true,
  12180. configurable: true
  12181. });
  12182. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12183. get: function () {
  12184. return Scene._FOGMODE_EXP;
  12185. },
  12186. enumerable: true,
  12187. configurable: true
  12188. });
  12189. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12190. get: function () {
  12191. return Scene._FOGMODE_EXP2;
  12192. },
  12193. enumerable: true,
  12194. configurable: true
  12195. });
  12196. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12197. get: function () {
  12198. return Scene._FOGMODE_LINEAR;
  12199. },
  12200. enumerable: true,
  12201. configurable: true
  12202. });
  12203. Object.defineProperty(Scene.prototype, "debugLayer", {
  12204. // Properties
  12205. get: function () {
  12206. return this._debugLayer;
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12212. get: function () {
  12213. return this._workerCollisions;
  12214. },
  12215. set: function (enabled) {
  12216. enabled = (enabled && !!Worker);
  12217. this._workerCollisions = enabled;
  12218. if (this.collisionCoordinator) {
  12219. this.collisionCoordinator.destroy();
  12220. }
  12221. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12222. this.collisionCoordinator.init(this);
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12228. /**
  12229. * The mesh that is currently under the pointer.
  12230. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12231. */
  12232. get: function () {
  12233. return this._meshUnderPointer;
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. Object.defineProperty(Scene.prototype, "pointerX", {
  12239. /**
  12240. * Current on-screen X position of the pointer
  12241. * @return {number} X position of the pointer
  12242. */
  12243. get: function () {
  12244. return this._pointerX;
  12245. },
  12246. enumerable: true,
  12247. configurable: true
  12248. });
  12249. Object.defineProperty(Scene.prototype, "pointerY", {
  12250. /**
  12251. * Current on-screen Y position of the pointer
  12252. * @return {number} Y position of the pointer
  12253. */
  12254. get: function () {
  12255. return this._pointerY;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Scene.prototype.getCachedMaterial = function () {
  12261. return this._cachedMaterial;
  12262. };
  12263. Scene.prototype.getBoundingBoxRenderer = function () {
  12264. return this._boundingBoxRenderer;
  12265. };
  12266. Scene.prototype.getOutlineRenderer = function () {
  12267. return this._outlineRenderer;
  12268. };
  12269. Scene.prototype.getEngine = function () {
  12270. return this._engine;
  12271. };
  12272. Scene.prototype.getTotalVertices = function () {
  12273. return this._totalVertices;
  12274. };
  12275. Scene.prototype.getActiveIndices = function () {
  12276. return this._activeIndices;
  12277. };
  12278. Scene.prototype.getActiveParticles = function () {
  12279. return this._activeParticles;
  12280. };
  12281. Scene.prototype.getActiveBones = function () {
  12282. return this._activeBones;
  12283. };
  12284. // Stats
  12285. Scene.prototype.getLastFrameDuration = function () {
  12286. return this._lastFrameDuration;
  12287. };
  12288. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12289. return this._evaluateActiveMeshesDuration;
  12290. };
  12291. Scene.prototype.getActiveMeshes = function () {
  12292. return this._activeMeshes;
  12293. };
  12294. Scene.prototype.getRenderTargetsDuration = function () {
  12295. return this._renderTargetsDuration;
  12296. };
  12297. Scene.prototype.getRenderDuration = function () {
  12298. return this._renderDuration;
  12299. };
  12300. Scene.prototype.getParticlesDuration = function () {
  12301. return this._particlesDuration;
  12302. };
  12303. Scene.prototype.getSpritesDuration = function () {
  12304. return this._spritesDuration;
  12305. };
  12306. Scene.prototype.getAnimationRatio = function () {
  12307. return this._animationRatio;
  12308. };
  12309. Scene.prototype.getRenderId = function () {
  12310. return this._renderId;
  12311. };
  12312. Scene.prototype.incrementRenderId = function () {
  12313. this._renderId++;
  12314. };
  12315. Scene.prototype._updatePointerPosition = function (evt) {
  12316. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12317. this._pointerX = evt.clientX - canvasRect.left;
  12318. this._pointerY = evt.clientY - canvasRect.top;
  12319. if (this.cameraToUseForPointers) {
  12320. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12321. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12322. }
  12323. };
  12324. // Pointers handling
  12325. Scene.prototype.attachControl = function () {
  12326. var _this = this;
  12327. this._onPointerMove = function (evt) {
  12328. var canvas = _this._engine.getRenderingCanvas();
  12329. _this._updatePointerPosition(evt);
  12330. 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);
  12331. if (pickResult.hit) {
  12332. _this._meshUnderPointer = pickResult.pickedMesh;
  12333. _this.setPointerOverMesh(pickResult.pickedMesh);
  12334. canvas.style.cursor = "pointer";
  12335. }
  12336. else {
  12337. _this.setPointerOverMesh(null);
  12338. canvas.style.cursor = "";
  12339. _this._meshUnderPointer = null;
  12340. }
  12341. };
  12342. this._onPointerDown = function (evt) {
  12343. var predicate = null;
  12344. if (!_this.onPointerDown) {
  12345. predicate = function (mesh) {
  12346. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12347. };
  12348. }
  12349. _this._updatePointerPosition(evt);
  12350. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12351. if (pickResult.hit) {
  12352. if (pickResult.pickedMesh.actionManager) {
  12353. switch (evt.button) {
  12354. case 0:
  12355. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12356. break;
  12357. case 1:
  12358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12359. break;
  12360. case 2:
  12361. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12362. break;
  12363. }
  12364. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12365. }
  12366. }
  12367. if (_this.onPointerDown) {
  12368. _this.onPointerDown(evt, pickResult);
  12369. }
  12370. };
  12371. this._onPointerUp = function (evt) {
  12372. var predicate = null;
  12373. if (!_this.onPointerUp) {
  12374. predicate = function (mesh) {
  12375. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12376. };
  12377. }
  12378. _this._updatePointerPosition(evt);
  12379. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12380. if (pickResult.hit) {
  12381. if (pickResult.pickedMesh.actionManager) {
  12382. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12383. }
  12384. }
  12385. if (_this.onPointerUp) {
  12386. _this.onPointerUp(evt, pickResult);
  12387. }
  12388. };
  12389. this._onKeyDown = function (evt) {
  12390. if (_this.actionManager) {
  12391. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12392. }
  12393. };
  12394. this._onKeyUp = function (evt) {
  12395. if (_this.actionManager) {
  12396. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12397. }
  12398. };
  12399. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12400. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12401. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12402. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12403. BABYLON.Tools.RegisterTopRootEvents([
  12404. { name: "keydown", handler: this._onKeyDown },
  12405. { name: "keyup", handler: this._onKeyUp }
  12406. ]);
  12407. };
  12408. Scene.prototype.detachControl = function () {
  12409. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12410. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12411. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12412. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12413. BABYLON.Tools.UnregisterTopRootEvents([
  12414. { name: "keydown", handler: this._onKeyDown },
  12415. { name: "keyup", handler: this._onKeyUp }
  12416. ]);
  12417. };
  12418. // Ready
  12419. Scene.prototype.isReady = function () {
  12420. if (this._pendingData.length > 0) {
  12421. return false;
  12422. }
  12423. for (var index = 0; index < this._geometries.length; index++) {
  12424. var geometry = this._geometries[index];
  12425. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12426. return false;
  12427. }
  12428. }
  12429. for (index = 0; index < this.meshes.length; index++) {
  12430. var mesh = this.meshes[index];
  12431. if (!mesh.isReady()) {
  12432. return false;
  12433. }
  12434. var mat = mesh.material;
  12435. if (mat) {
  12436. if (!mat.isReady(mesh)) {
  12437. return false;
  12438. }
  12439. }
  12440. }
  12441. return true;
  12442. };
  12443. Scene.prototype.resetCachedMaterial = function () {
  12444. this._cachedMaterial = null;
  12445. };
  12446. Scene.prototype.registerBeforeRender = function (func) {
  12447. this._onBeforeRenderCallbacks.push(func);
  12448. };
  12449. Scene.prototype.unregisterBeforeRender = function (func) {
  12450. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12451. if (index > -1) {
  12452. this._onBeforeRenderCallbacks.splice(index, 1);
  12453. }
  12454. };
  12455. Scene.prototype.registerAfterRender = function (func) {
  12456. this._onAfterRenderCallbacks.push(func);
  12457. };
  12458. Scene.prototype.unregisterAfterRender = function (func) {
  12459. var index = this._onAfterRenderCallbacks.indexOf(func);
  12460. if (index > -1) {
  12461. this._onAfterRenderCallbacks.splice(index, 1);
  12462. }
  12463. };
  12464. Scene.prototype._addPendingData = function (data) {
  12465. this._pendingData.push(data);
  12466. };
  12467. Scene.prototype._removePendingData = function (data) {
  12468. var index = this._pendingData.indexOf(data);
  12469. if (index !== -1) {
  12470. this._pendingData.splice(index, 1);
  12471. }
  12472. };
  12473. Scene.prototype.getWaitingItemsCount = function () {
  12474. return this._pendingData.length;
  12475. };
  12476. /**
  12477. * Registers a function to be executed when the scene is ready.
  12478. * @param {Function} func - the function to be executed.
  12479. */
  12480. Scene.prototype.executeWhenReady = function (func) {
  12481. var _this = this;
  12482. this._onReadyCallbacks.push(func);
  12483. if (this._executeWhenReadyTimeoutId !== -1) {
  12484. return;
  12485. }
  12486. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12487. _this._checkIsReady();
  12488. }, 150);
  12489. };
  12490. Scene.prototype._checkIsReady = function () {
  12491. var _this = this;
  12492. if (this.isReady()) {
  12493. this._onReadyCallbacks.forEach(function (func) {
  12494. func();
  12495. });
  12496. this._onReadyCallbacks = [];
  12497. this._executeWhenReadyTimeoutId = -1;
  12498. return;
  12499. }
  12500. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12501. _this._checkIsReady();
  12502. }, 150);
  12503. };
  12504. // Animations
  12505. /**
  12506. * Will start the animation sequence of a given target
  12507. * @param target - the target
  12508. * @param {number} from - from which frame should animation start
  12509. * @param {number} to - till which frame should animation run.
  12510. * @param {boolean} [loop] - should the animation loop
  12511. * @param {number} [speedRatio] - the speed in which to run the animation
  12512. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12513. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12514. * @return {BABYLON.Animatable} the animatable object created for this animation
  12515. * @see BABYLON.Animatable
  12516. * @see http://doc.babylonjs.com/page.php?p=22081
  12517. */
  12518. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12519. if (speedRatio === undefined) {
  12520. speedRatio = 1.0;
  12521. }
  12522. this.stopAnimation(target);
  12523. if (!animatable) {
  12524. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12525. }
  12526. // Local animations
  12527. if (target.animations) {
  12528. animatable.appendAnimations(target, target.animations);
  12529. }
  12530. // Children animations
  12531. if (target.getAnimatables) {
  12532. var animatables = target.getAnimatables();
  12533. for (var index = 0; index < animatables.length; index++) {
  12534. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12535. }
  12536. }
  12537. return animatable;
  12538. };
  12539. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12540. if (speedRatio === undefined) {
  12541. speedRatio = 1.0;
  12542. }
  12543. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12544. return animatable;
  12545. };
  12546. Scene.prototype.getAnimatableByTarget = function (target) {
  12547. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12548. if (this._activeAnimatables[index].target === target) {
  12549. return this._activeAnimatables[index];
  12550. }
  12551. }
  12552. return null;
  12553. };
  12554. /**
  12555. * Will stop the animation of the given target
  12556. * @param target - the target
  12557. * @see beginAnimation
  12558. */
  12559. Scene.prototype.stopAnimation = function (target) {
  12560. var animatable = this.getAnimatableByTarget(target);
  12561. if (animatable) {
  12562. animatable.stop();
  12563. }
  12564. };
  12565. Scene.prototype._animate = function () {
  12566. if (!this.animationsEnabled) {
  12567. return;
  12568. }
  12569. if (!this._animationStartDate) {
  12570. this._animationStartDate = BABYLON.Tools.Now;
  12571. }
  12572. // Getting time
  12573. var now = BABYLON.Tools.Now;
  12574. var delay = now - this._animationStartDate;
  12575. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12576. this._activeAnimatables[index]._animate(delay);
  12577. }
  12578. };
  12579. // Matrix
  12580. Scene.prototype.getViewMatrix = function () {
  12581. return this._viewMatrix;
  12582. };
  12583. Scene.prototype.getProjectionMatrix = function () {
  12584. return this._projectionMatrix;
  12585. };
  12586. Scene.prototype.getTransformMatrix = function () {
  12587. return this._transformMatrix;
  12588. };
  12589. Scene.prototype.setTransformMatrix = function (view, projection) {
  12590. this._viewMatrix = view;
  12591. this._projectionMatrix = projection;
  12592. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12593. };
  12594. // Methods
  12595. Scene.prototype.addMesh = function (newMesh) {
  12596. newMesh.uniqueId = this._uniqueIdCounter++;
  12597. var position = this.meshes.push(newMesh);
  12598. //notify the collision coordinator
  12599. this.collisionCoordinator.onMeshAdded(newMesh);
  12600. if (this.onNewMeshAdded) {
  12601. this.onNewMeshAdded(newMesh, position, this);
  12602. }
  12603. };
  12604. Scene.prototype.removeMesh = function (toRemove) {
  12605. var index = this.meshes.indexOf(toRemove);
  12606. if (index !== -1) {
  12607. // Remove from the scene if mesh found
  12608. this.meshes.splice(index, 1);
  12609. }
  12610. //notify the collision coordinator
  12611. this.collisionCoordinator.onMeshRemoved(toRemove);
  12612. if (this.onMeshRemoved) {
  12613. this.onMeshRemoved(toRemove);
  12614. }
  12615. return index;
  12616. };
  12617. Scene.prototype.removeLight = function (toRemove) {
  12618. var index = this.lights.indexOf(toRemove);
  12619. if (index !== -1) {
  12620. // Remove from the scene if mesh found
  12621. this.lights.splice(index, 1);
  12622. }
  12623. if (this.onLightRemoved) {
  12624. this.onLightRemoved(toRemove);
  12625. }
  12626. return index;
  12627. };
  12628. Scene.prototype.removeCamera = function (toRemove) {
  12629. var index = this.cameras.indexOf(toRemove);
  12630. if (index !== -1) {
  12631. // Remove from the scene if mesh found
  12632. this.cameras.splice(index, 1);
  12633. }
  12634. // Remove from activeCameras
  12635. var index2 = this.activeCameras.indexOf(toRemove);
  12636. if (index2 !== -1) {
  12637. // Remove from the scene if mesh found
  12638. this.activeCameras.splice(index2, 1);
  12639. }
  12640. // Reset the activeCamera
  12641. if (this.activeCamera === toRemove) {
  12642. if (this.cameras.length > 0) {
  12643. this.activeCamera = this.cameras[0];
  12644. }
  12645. else {
  12646. this.activeCamera = null;
  12647. }
  12648. }
  12649. if (this.onCameraRemoved) {
  12650. this.onCameraRemoved(toRemove);
  12651. }
  12652. return index;
  12653. };
  12654. Scene.prototype.addLight = function (newLight) {
  12655. newLight.uniqueId = this._uniqueIdCounter++;
  12656. var position = this.lights.push(newLight);
  12657. if (this.onNewLightAdded) {
  12658. this.onNewLightAdded(newLight, position, this);
  12659. }
  12660. };
  12661. Scene.prototype.addCamera = function (newCamera) {
  12662. newCamera.uniqueId = this._uniqueIdCounter++;
  12663. var position = this.cameras.push(newCamera);
  12664. if (this.onNewCameraAdded) {
  12665. this.onNewCameraAdded(newCamera, position, this);
  12666. }
  12667. };
  12668. /**
  12669. * sets the active camera of the scene using its ID
  12670. * @param {string} id - the camera's ID
  12671. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12672. * @see activeCamera
  12673. */
  12674. Scene.prototype.setActiveCameraByID = function (id) {
  12675. var camera = this.getCameraByID(id);
  12676. if (camera) {
  12677. this.activeCamera = camera;
  12678. return camera;
  12679. }
  12680. return null;
  12681. };
  12682. /**
  12683. * sets the active camera of the scene using its name
  12684. * @param {string} name - the camera's name
  12685. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12686. * @see activeCamera
  12687. */
  12688. Scene.prototype.setActiveCameraByName = function (name) {
  12689. var camera = this.getCameraByName(name);
  12690. if (camera) {
  12691. this.activeCamera = camera;
  12692. return camera;
  12693. }
  12694. return null;
  12695. };
  12696. /**
  12697. * get a material using its id
  12698. * @param {string} the material's ID
  12699. * @return {BABYLON.Material|null} the material or null if none found.
  12700. */
  12701. Scene.prototype.getMaterialByID = function (id) {
  12702. for (var index = 0; index < this.materials.length; index++) {
  12703. if (this.materials[index].id === id) {
  12704. return this.materials[index];
  12705. }
  12706. }
  12707. return null;
  12708. };
  12709. /**
  12710. * get a material using its name
  12711. * @param {string} the material's name
  12712. * @return {BABYLON.Material|null} the material or null if none found.
  12713. */
  12714. Scene.prototype.getMaterialByName = function (name) {
  12715. for (var index = 0; index < this.materials.length; index++) {
  12716. if (this.materials[index].name === name) {
  12717. return this.materials[index];
  12718. }
  12719. }
  12720. return null;
  12721. };
  12722. Scene.prototype.getCameraByID = function (id) {
  12723. for (var index = 0; index < this.cameras.length; index++) {
  12724. if (this.cameras[index].id === id) {
  12725. return this.cameras[index];
  12726. }
  12727. }
  12728. return null;
  12729. };
  12730. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12731. for (var index = 0; index < this.cameras.length; index++) {
  12732. if (this.cameras[index].uniqueId === uniqueId) {
  12733. return this.cameras[index];
  12734. }
  12735. }
  12736. return null;
  12737. };
  12738. /**
  12739. * get a camera using its name
  12740. * @param {string} the camera's name
  12741. * @return {BABYLON.Camera|null} the camera or null if none found.
  12742. */
  12743. Scene.prototype.getCameraByName = function (name) {
  12744. for (var index = 0; index < this.cameras.length; index++) {
  12745. if (this.cameras[index].name === name) {
  12746. return this.cameras[index];
  12747. }
  12748. }
  12749. return null;
  12750. };
  12751. /**
  12752. * get a light node using its name
  12753. * @param {string} the light's name
  12754. * @return {BABYLON.Light|null} the light or null if none found.
  12755. */
  12756. Scene.prototype.getLightByName = function (name) {
  12757. for (var index = 0; index < this.lights.length; index++) {
  12758. if (this.lights[index].name === name) {
  12759. return this.lights[index];
  12760. }
  12761. }
  12762. return null;
  12763. };
  12764. /**
  12765. * get a light node using its ID
  12766. * @param {string} the light's id
  12767. * @return {BABYLON.Light|null} the light or null if none found.
  12768. */
  12769. Scene.prototype.getLightByID = function (id) {
  12770. for (var index = 0; index < this.lights.length; index++) {
  12771. if (this.lights[index].id === id) {
  12772. return this.lights[index];
  12773. }
  12774. }
  12775. return null;
  12776. };
  12777. /**
  12778. * get a light node using its scene-generated unique ID
  12779. * @param {number} the light's unique id
  12780. * @return {BABYLON.Light|null} the light or null if none found.
  12781. */
  12782. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12783. for (var index = 0; index < this.lights.length; index++) {
  12784. if (this.lights[index].uniqueId === uniqueId) {
  12785. return this.lights[index];
  12786. }
  12787. }
  12788. return null;
  12789. };
  12790. /**
  12791. * get a geometry using its ID
  12792. * @param {string} the geometry's id
  12793. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12794. */
  12795. Scene.prototype.getGeometryByID = function (id) {
  12796. for (var index = 0; index < this._geometries.length; index++) {
  12797. if (this._geometries[index].id === id) {
  12798. return this._geometries[index];
  12799. }
  12800. }
  12801. return null;
  12802. };
  12803. /**
  12804. * add a new geometry to this scene.
  12805. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12806. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12807. * @return {boolean} was the geometry added or not
  12808. */
  12809. Scene.prototype.pushGeometry = function (geometry, force) {
  12810. if (!force && this.getGeometryByID(geometry.id)) {
  12811. return false;
  12812. }
  12813. this._geometries.push(geometry);
  12814. //notify the collision coordinator
  12815. this.collisionCoordinator.onGeometryAdded(geometry);
  12816. if (this.onGeometryAdded) {
  12817. this.onGeometryAdded(geometry);
  12818. }
  12819. return true;
  12820. };
  12821. /**
  12822. * Removes an existing geometry
  12823. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12824. * @return {boolean} was the geometry removed or not
  12825. */
  12826. Scene.prototype.removeGeometry = function (geometry) {
  12827. var index = this._geometries.indexOf(geometry);
  12828. if (index > -1) {
  12829. this._geometries.splice(index, 1);
  12830. //notify the collision coordinator
  12831. this.collisionCoordinator.onGeometryDeleted(geometry);
  12832. if (this.onGeometryRemoved) {
  12833. this.onGeometryRemoved(geometry);
  12834. }
  12835. return true;
  12836. }
  12837. return false;
  12838. };
  12839. Scene.prototype.getGeometries = function () {
  12840. return this._geometries;
  12841. };
  12842. /**
  12843. * Get the first added mesh found of a given ID
  12844. * @param {string} id - the id to search for
  12845. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12846. */
  12847. Scene.prototype.getMeshByID = function (id) {
  12848. for (var index = 0; index < this.meshes.length; index++) {
  12849. if (this.meshes[index].id === id) {
  12850. return this.meshes[index];
  12851. }
  12852. }
  12853. return null;
  12854. };
  12855. /**
  12856. * Get a mesh with its auto-generated unique id
  12857. * @param {number} uniqueId - the unique id to search for
  12858. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12859. */
  12860. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12861. for (var index = 0; index < this.meshes.length; index++) {
  12862. if (this.meshes[index].uniqueId === uniqueId) {
  12863. return this.meshes[index];
  12864. }
  12865. }
  12866. return null;
  12867. };
  12868. /**
  12869. * Get a the last added mesh found of a given ID
  12870. * @param {string} id - the id to search for
  12871. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12872. */
  12873. Scene.prototype.getLastMeshByID = function (id) {
  12874. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12875. if (this.meshes[index].id === id) {
  12876. return this.meshes[index];
  12877. }
  12878. }
  12879. return null;
  12880. };
  12881. /**
  12882. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12883. * @param {string} id - the id to search for
  12884. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12885. */
  12886. Scene.prototype.getLastEntryByID = function (id) {
  12887. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12888. if (this.meshes[index].id === id) {
  12889. return this.meshes[index];
  12890. }
  12891. }
  12892. for (index = this.cameras.length - 1; index >= 0; index--) {
  12893. if (this.cameras[index].id === id) {
  12894. return this.cameras[index];
  12895. }
  12896. }
  12897. for (index = this.lights.length - 1; index >= 0; index--) {
  12898. if (this.lights[index].id === id) {
  12899. return this.lights[index];
  12900. }
  12901. }
  12902. return null;
  12903. };
  12904. Scene.prototype.getNodeByName = function (name) {
  12905. var mesh = this.getMeshByName(name);
  12906. if (mesh) {
  12907. return mesh;
  12908. }
  12909. var light = this.getLightByName(name);
  12910. if (light) {
  12911. return light;
  12912. }
  12913. return this.getCameraByName(name);
  12914. };
  12915. Scene.prototype.getMeshByName = function (name) {
  12916. for (var index = 0; index < this.meshes.length; index++) {
  12917. if (this.meshes[index].name === name) {
  12918. return this.meshes[index];
  12919. }
  12920. }
  12921. return null;
  12922. };
  12923. Scene.prototype.getSoundByName = function (name) {
  12924. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12925. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12926. return this.mainSoundTrack.soundCollection[index];
  12927. }
  12928. }
  12929. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12930. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12931. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12932. return this.soundTracks[sdIndex].soundCollection[index];
  12933. }
  12934. }
  12935. }
  12936. return null;
  12937. };
  12938. Scene.prototype.getLastSkeletonByID = function (id) {
  12939. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12940. if (this.skeletons[index].id === id) {
  12941. return this.skeletons[index];
  12942. }
  12943. }
  12944. return null;
  12945. };
  12946. Scene.prototype.getSkeletonById = function (id) {
  12947. for (var index = 0; index < this.skeletons.length; index++) {
  12948. if (this.skeletons[index].id === id) {
  12949. return this.skeletons[index];
  12950. }
  12951. }
  12952. return null;
  12953. };
  12954. Scene.prototype.getSkeletonByName = function (name) {
  12955. for (var index = 0; index < this.skeletons.length; index++) {
  12956. if (this.skeletons[index].name === name) {
  12957. return this.skeletons[index];
  12958. }
  12959. }
  12960. return null;
  12961. };
  12962. Scene.prototype.isActiveMesh = function (mesh) {
  12963. return (this._activeMeshes.indexOf(mesh) !== -1);
  12964. };
  12965. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12966. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12967. var material = subMesh.getMaterial();
  12968. if (mesh.showSubMeshesBoundingBox) {
  12969. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12970. }
  12971. if (material) {
  12972. // Render targets
  12973. if (material.getRenderTargetTextures) {
  12974. if (this._processedMaterials.indexOf(material) === -1) {
  12975. this._processedMaterials.push(material);
  12976. this._renderTargets.concat(material.getRenderTargetTextures());
  12977. }
  12978. }
  12979. // Dispatch
  12980. this._activeIndices += subMesh.indexCount;
  12981. this._renderingManager.dispatch(subMesh);
  12982. }
  12983. }
  12984. };
  12985. Scene.prototype._evaluateActiveMeshes = function () {
  12986. this.activeCamera._activeMeshes.reset();
  12987. this._activeMeshes.reset();
  12988. this._renderingManager.reset();
  12989. this._processedMaterials.reset();
  12990. this._activeParticleSystems.reset();
  12991. this._activeSkeletons.reset();
  12992. this._boundingBoxRenderer.reset();
  12993. if (!this._frustumPlanes) {
  12994. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12995. }
  12996. else {
  12997. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12998. }
  12999. // Meshes
  13000. var meshes;
  13001. var len;
  13002. if (this._selectionOctree) {
  13003. var selection = this._selectionOctree.select(this._frustumPlanes);
  13004. meshes = selection.data;
  13005. len = selection.length;
  13006. }
  13007. else {
  13008. len = this.meshes.length;
  13009. meshes = this.meshes;
  13010. }
  13011. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13012. var mesh = meshes[meshIndex];
  13013. if (mesh.isBlocked) {
  13014. continue;
  13015. }
  13016. this._totalVertices += mesh.getTotalVertices();
  13017. if (!mesh.isReady() || !mesh.isEnabled()) {
  13018. continue;
  13019. }
  13020. mesh.computeWorldMatrix();
  13021. // Intersections
  13022. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13023. this._meshesForIntersections.pushNoDuplicate(mesh);
  13024. }
  13025. // Switch to current LOD
  13026. var meshLOD = mesh.getLOD(this.activeCamera);
  13027. if (!meshLOD) {
  13028. continue;
  13029. }
  13030. mesh._preActivate();
  13031. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13032. this._activeMeshes.push(mesh);
  13033. this.activeCamera._activeMeshes.push(mesh);
  13034. mesh._activate(this._renderId);
  13035. this._activeMesh(meshLOD);
  13036. }
  13037. }
  13038. // Particle systems
  13039. var beforeParticlesDate = BABYLON.Tools.Now;
  13040. if (this.particlesEnabled) {
  13041. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13042. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13043. var particleSystem = this.particleSystems[particleIndex];
  13044. if (!particleSystem.isStarted()) {
  13045. continue;
  13046. }
  13047. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13048. this._activeParticleSystems.push(particleSystem);
  13049. particleSystem.animate();
  13050. }
  13051. }
  13052. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13053. }
  13054. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13055. };
  13056. Scene.prototype._activeMesh = function (mesh) {
  13057. if (mesh.skeleton && this.skeletonsEnabled) {
  13058. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13059. }
  13060. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13061. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13062. }
  13063. if (mesh && mesh.subMeshes) {
  13064. // Submeshes Octrees
  13065. var len;
  13066. var subMeshes;
  13067. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13068. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13069. len = intersections.length;
  13070. subMeshes = intersections.data;
  13071. }
  13072. else {
  13073. subMeshes = mesh.subMeshes;
  13074. len = subMeshes.length;
  13075. }
  13076. for (var subIndex = 0; subIndex < len; subIndex++) {
  13077. var subMesh = subMeshes[subIndex];
  13078. this._evaluateSubMesh(subMesh, mesh);
  13079. }
  13080. }
  13081. };
  13082. Scene.prototype.updateTransformMatrix = function (force) {
  13083. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13084. };
  13085. Scene.prototype._renderForCamera = function (camera) {
  13086. var engine = this._engine;
  13087. this.activeCamera = camera;
  13088. if (!this.activeCamera)
  13089. throw new Error("Active camera not set");
  13090. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13091. // Viewport
  13092. engine.setViewport(this.activeCamera.viewport);
  13093. // Camera
  13094. this.resetCachedMaterial();
  13095. this._renderId++;
  13096. this.updateTransformMatrix();
  13097. if (this.beforeCameraRender) {
  13098. this.beforeCameraRender(this.activeCamera);
  13099. }
  13100. // Meshes
  13101. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13102. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13103. this._evaluateActiveMeshes();
  13104. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13105. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13106. // Skeletons
  13107. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13108. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13109. skeleton.prepare();
  13110. }
  13111. // Render targets
  13112. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13113. if (this.renderTargetsEnabled) {
  13114. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13115. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13116. var renderTarget = this._renderTargets.data[renderIndex];
  13117. if (renderTarget._shouldRender()) {
  13118. this._renderId++;
  13119. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13120. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13121. }
  13122. }
  13123. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13124. this._renderId++;
  13125. }
  13126. if (this._renderTargets.length > 0) {
  13127. engine.restoreDefaultFramebuffer();
  13128. }
  13129. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13130. // Prepare Frame
  13131. this.postProcessManager._prepareFrame();
  13132. var beforeRenderDate = BABYLON.Tools.Now;
  13133. // Backgrounds
  13134. if (this.layers.length) {
  13135. engine.setDepthBuffer(false);
  13136. var layerIndex;
  13137. var layer;
  13138. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13139. layer = this.layers[layerIndex];
  13140. if (layer.isBackground) {
  13141. layer.render();
  13142. }
  13143. }
  13144. engine.setDepthBuffer(true);
  13145. }
  13146. // Render
  13147. BABYLON.Tools.StartPerformanceCounter("Main render");
  13148. this._renderingManager.render(null, null, true, true);
  13149. BABYLON.Tools.EndPerformanceCounter("Main render");
  13150. // Bounding boxes
  13151. this._boundingBoxRenderer.render();
  13152. // Lens flares
  13153. if (this.lensFlaresEnabled) {
  13154. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13155. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13156. this.lensFlareSystems[lensFlareSystemIndex].render();
  13157. }
  13158. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13159. }
  13160. // Foregrounds
  13161. if (this.layers.length) {
  13162. engine.setDepthBuffer(false);
  13163. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13164. layer = this.layers[layerIndex];
  13165. if (!layer.isBackground) {
  13166. layer.render();
  13167. }
  13168. }
  13169. engine.setDepthBuffer(true);
  13170. }
  13171. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13172. // Finalize frame
  13173. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13174. // Update camera
  13175. this.activeCamera._updateFromScene();
  13176. // Reset some special arrays
  13177. this._renderTargets.reset();
  13178. if (this.afterCameraRender) {
  13179. this.afterCameraRender(this.activeCamera);
  13180. }
  13181. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13182. };
  13183. Scene.prototype._processSubCameras = function (camera) {
  13184. if (camera.subCameras.length === 0) {
  13185. this._renderForCamera(camera);
  13186. return;
  13187. }
  13188. // Sub-cameras
  13189. for (var index = 0; index < camera.subCameras.length; index++) {
  13190. this._renderForCamera(camera.subCameras[index]);
  13191. }
  13192. this.activeCamera = camera;
  13193. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13194. // Update camera
  13195. this.activeCamera._updateFromScene();
  13196. };
  13197. Scene.prototype._checkIntersections = function () {
  13198. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13199. var sourceMesh = this._meshesForIntersections.data[index];
  13200. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13201. var action = sourceMesh.actionManager.actions[actionIndex];
  13202. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13203. var parameters = action.getTriggerParameter();
  13204. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13205. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13206. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13207. if (areIntersecting && currentIntersectionInProgress === -1) {
  13208. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13209. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13210. sourceMesh._intersectionsInProgress.push(otherMesh);
  13211. }
  13212. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13213. sourceMesh._intersectionsInProgress.push(otherMesh);
  13214. }
  13215. }
  13216. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13217. //They intersected, and now they don't.
  13218. //is this trigger an exit trigger? execute an event.
  13219. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13220. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13221. }
  13222. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13223. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13224. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13225. }
  13226. }
  13227. }
  13228. }
  13229. }
  13230. };
  13231. Scene.prototype.render = function () {
  13232. var startDate = BABYLON.Tools.Now;
  13233. this._particlesDuration = 0;
  13234. this._spritesDuration = 0;
  13235. this._activeParticles = 0;
  13236. this._renderDuration = 0;
  13237. this._renderTargetsDuration = 0;
  13238. this._evaluateActiveMeshesDuration = 0;
  13239. this._totalVertices = 0;
  13240. this._activeIndices = 0;
  13241. this._activeBones = 0;
  13242. this.getEngine().resetDrawCalls();
  13243. this._meshesForIntersections.reset();
  13244. this.resetCachedMaterial();
  13245. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13246. // Actions
  13247. if (this.actionManager) {
  13248. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13249. }
  13250. //Simplification Queue
  13251. if (!this.simplificationQueue.running) {
  13252. this.simplificationQueue.executeNext();
  13253. }
  13254. // Before render
  13255. if (this.beforeRender) {
  13256. this.beforeRender();
  13257. }
  13258. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13259. this._onBeforeRenderCallbacks[callbackIndex]();
  13260. }
  13261. // Animations
  13262. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13263. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13264. this._animate();
  13265. // Physics
  13266. if (this._physicsEngine) {
  13267. BABYLON.Tools.StartPerformanceCounter("Physics");
  13268. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13269. BABYLON.Tools.EndPerformanceCounter("Physics");
  13270. }
  13271. // Customs render targets
  13272. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13273. var engine = this.getEngine();
  13274. var currentActiveCamera = this.activeCamera;
  13275. if (this.renderTargetsEnabled) {
  13276. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13277. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13278. var renderTarget = this.customRenderTargets[customIndex];
  13279. if (renderTarget._shouldRender()) {
  13280. this._renderId++;
  13281. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13282. if (!this.activeCamera)
  13283. throw new Error("Active camera not set");
  13284. // Viewport
  13285. engine.setViewport(this.activeCamera.viewport);
  13286. // Camera
  13287. this.updateTransformMatrix();
  13288. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13289. }
  13290. }
  13291. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13292. this._renderId++;
  13293. }
  13294. if (this.customRenderTargets.length > 0) {
  13295. engine.restoreDefaultFramebuffer();
  13296. }
  13297. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13298. this.activeCamera = currentActiveCamera;
  13299. // Procedural textures
  13300. if (this.proceduralTexturesEnabled) {
  13301. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13302. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13303. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13304. if (proceduralTexture._shouldRender()) {
  13305. proceduralTexture.render();
  13306. }
  13307. }
  13308. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13309. }
  13310. // Clear
  13311. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13312. // Shadows
  13313. if (this.shadowsEnabled) {
  13314. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13315. var light = this.lights[lightIndex];
  13316. var shadowGenerator = light.getShadowGenerator();
  13317. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13318. this._renderTargets.push(shadowGenerator.getShadowMap());
  13319. }
  13320. }
  13321. }
  13322. // Depth renderer
  13323. if (this._depthRenderer) {
  13324. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13325. }
  13326. // RenderPipeline
  13327. this.postProcessRenderPipelineManager.update();
  13328. // Multi-cameras?
  13329. if (this.activeCameras.length > 0) {
  13330. var currentRenderId = this._renderId;
  13331. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13332. this._renderId = currentRenderId;
  13333. this._processSubCameras(this.activeCameras[cameraIndex]);
  13334. }
  13335. }
  13336. else {
  13337. if (!this.activeCamera) {
  13338. throw new Error("No camera defined");
  13339. }
  13340. this._processSubCameras(this.activeCamera);
  13341. }
  13342. // Intersection checks
  13343. this._checkIntersections();
  13344. // Update the audio listener attached to the camera
  13345. this._updateAudioParameters();
  13346. // After render
  13347. if (this.afterRender) {
  13348. this.afterRender();
  13349. }
  13350. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13351. this._onAfterRenderCallbacks[callbackIndex]();
  13352. }
  13353. // Cleaning
  13354. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13355. this._toBeDisposed.data[index].dispose();
  13356. this._toBeDisposed[index] = null;
  13357. }
  13358. this._toBeDisposed.reset();
  13359. if (this.dumpNextRenderTargets) {
  13360. this.dumpNextRenderTargets = false;
  13361. }
  13362. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13363. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13364. };
  13365. Scene.prototype._updateAudioParameters = function () {
  13366. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13367. return;
  13368. }
  13369. var listeningCamera;
  13370. var audioEngine = BABYLON.Engine.audioEngine;
  13371. if (this.activeCameras.length > 0) {
  13372. listeningCamera = this.activeCameras[0];
  13373. }
  13374. else {
  13375. listeningCamera = this.activeCamera;
  13376. }
  13377. if (listeningCamera && audioEngine.canUseWebAudio) {
  13378. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13379. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13380. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13381. cameraDirection.normalize();
  13382. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13383. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13384. var sound = this.mainSoundTrack.soundCollection[i];
  13385. if (sound.useCustomAttenuation) {
  13386. sound.updateDistanceFromListener();
  13387. }
  13388. }
  13389. for (i = 0; i < this.soundTracks.length; i++) {
  13390. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13391. sound = this.soundTracks[i].soundCollection[j];
  13392. if (sound.useCustomAttenuation) {
  13393. sound.updateDistanceFromListener();
  13394. }
  13395. }
  13396. }
  13397. }
  13398. };
  13399. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13400. // Audio
  13401. get: function () {
  13402. return this._audioEnabled;
  13403. },
  13404. set: function (value) {
  13405. this._audioEnabled = value;
  13406. if (this._audioEnabled) {
  13407. this._enableAudio();
  13408. }
  13409. else {
  13410. this._disableAudio();
  13411. }
  13412. },
  13413. enumerable: true,
  13414. configurable: true
  13415. });
  13416. Scene.prototype._disableAudio = function () {
  13417. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13418. this.mainSoundTrack.soundCollection[i].pause();
  13419. }
  13420. for (i = 0; i < this.soundTracks.length; i++) {
  13421. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13422. this.soundTracks[i].soundCollection[j].pause();
  13423. }
  13424. }
  13425. };
  13426. Scene.prototype._enableAudio = function () {
  13427. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13428. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13429. this.mainSoundTrack.soundCollection[i].play();
  13430. }
  13431. }
  13432. for (i = 0; i < this.soundTracks.length; i++) {
  13433. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13434. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13435. this.soundTracks[i].soundCollection[j].play();
  13436. }
  13437. }
  13438. }
  13439. };
  13440. Object.defineProperty(Scene.prototype, "headphone", {
  13441. get: function () {
  13442. return this._headphone;
  13443. },
  13444. set: function (value) {
  13445. this._headphone = value;
  13446. if (this._headphone) {
  13447. this._switchAudioModeForHeadphones();
  13448. }
  13449. else {
  13450. this._switchAudioModeForNormalSpeakers();
  13451. }
  13452. },
  13453. enumerable: true,
  13454. configurable: true
  13455. });
  13456. Scene.prototype._switchAudioModeForHeadphones = function () {
  13457. this.mainSoundTrack.switchPanningModelToHRTF();
  13458. for (var i = 0; i < this.soundTracks.length; i++) {
  13459. this.soundTracks[i].switchPanningModelToHRTF();
  13460. }
  13461. };
  13462. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13463. this.mainSoundTrack.switchPanningModelToEqualPower();
  13464. for (var i = 0; i < this.soundTracks.length; i++) {
  13465. this.soundTracks[i].switchPanningModelToEqualPower();
  13466. }
  13467. };
  13468. Scene.prototype.enableDepthRenderer = function () {
  13469. if (this._depthRenderer) {
  13470. return this._depthRenderer;
  13471. }
  13472. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13473. return this._depthRenderer;
  13474. };
  13475. Scene.prototype.disableDepthRenderer = function () {
  13476. if (!this._depthRenderer) {
  13477. return;
  13478. }
  13479. this._depthRenderer.dispose();
  13480. this._depthRenderer = null;
  13481. };
  13482. Scene.prototype.dispose = function () {
  13483. this.beforeRender = null;
  13484. this.afterRender = null;
  13485. this.skeletons = [];
  13486. this._boundingBoxRenderer.dispose();
  13487. if (this._depthRenderer) {
  13488. this._depthRenderer.dispose();
  13489. }
  13490. // Debug layer
  13491. this.debugLayer.hide();
  13492. // Events
  13493. if (this.onDispose) {
  13494. this.onDispose();
  13495. }
  13496. this._onBeforeRenderCallbacks = [];
  13497. this._onAfterRenderCallbacks = [];
  13498. this.detachControl();
  13499. // Release sounds & sounds tracks
  13500. this.disposeSounds();
  13501. // Detach cameras
  13502. var canvas = this._engine.getRenderingCanvas();
  13503. var index;
  13504. for (index = 0; index < this.cameras.length; index++) {
  13505. this.cameras[index].detachControl(canvas);
  13506. }
  13507. // Release lights
  13508. while (this.lights.length) {
  13509. this.lights[0].dispose();
  13510. }
  13511. // Release meshes
  13512. while (this.meshes.length) {
  13513. this.meshes[0].dispose(true);
  13514. }
  13515. // Release cameras
  13516. while (this.cameras.length) {
  13517. this.cameras[0].dispose();
  13518. }
  13519. // Release materials
  13520. while (this.materials.length) {
  13521. this.materials[0].dispose();
  13522. }
  13523. // Release particles
  13524. while (this.particleSystems.length) {
  13525. this.particleSystems[0].dispose();
  13526. }
  13527. // Release sprites
  13528. while (this.spriteManagers.length) {
  13529. this.spriteManagers[0].dispose();
  13530. }
  13531. // Release layers
  13532. while (this.layers.length) {
  13533. this.layers[0].dispose();
  13534. }
  13535. // Release textures
  13536. while (this.textures.length) {
  13537. this.textures[0].dispose();
  13538. }
  13539. // Post-processes
  13540. this.postProcessManager.dispose();
  13541. // Physics
  13542. if (this._physicsEngine) {
  13543. this.disablePhysicsEngine();
  13544. }
  13545. // Remove from engine
  13546. index = this._engine.scenes.indexOf(this);
  13547. if (index > -1) {
  13548. this._engine.scenes.splice(index, 1);
  13549. }
  13550. this._engine.wipeCaches();
  13551. };
  13552. // Release sounds & sounds tracks
  13553. Scene.prototype.disposeSounds = function () {
  13554. this.mainSoundTrack.dispose();
  13555. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13556. this.soundTracks[scIndex].dispose();
  13557. }
  13558. };
  13559. // Octrees
  13560. Scene.prototype.getWorldExtends = function () {
  13561. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13562. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13563. for (var index = 0; index < this.meshes.length; index++) {
  13564. var mesh = this.meshes[index];
  13565. mesh.computeWorldMatrix(true);
  13566. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13567. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13568. BABYLON.Tools.CheckExtends(minBox, min, max);
  13569. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13570. }
  13571. return {
  13572. min: min,
  13573. max: max
  13574. };
  13575. };
  13576. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13577. if (maxCapacity === void 0) { maxCapacity = 64; }
  13578. if (maxDepth === void 0) { maxDepth = 2; }
  13579. if (!this._selectionOctree) {
  13580. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13581. }
  13582. var worldExtends = this.getWorldExtends();
  13583. // Update octree
  13584. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13585. return this._selectionOctree;
  13586. };
  13587. // Picking
  13588. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13589. var engine = this._engine;
  13590. if (!camera) {
  13591. if (!this.activeCamera)
  13592. throw new Error("Active camera not set");
  13593. camera = this.activeCamera;
  13594. }
  13595. var cameraViewport = camera.viewport;
  13596. var viewport = cameraViewport.toGlobal(engine);
  13597. // Moving coordinates to local viewport world
  13598. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13599. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13600. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13601. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13602. };
  13603. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13604. var pickingInfo = null;
  13605. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13606. var mesh = this.meshes[meshIndex];
  13607. if (predicate) {
  13608. if (!predicate(mesh)) {
  13609. continue;
  13610. }
  13611. }
  13612. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13613. continue;
  13614. }
  13615. var world = mesh.getWorldMatrix();
  13616. var ray = rayFunction(world);
  13617. var result = mesh.intersects(ray, fastCheck);
  13618. if (!result || !result.hit)
  13619. continue;
  13620. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13621. continue;
  13622. pickingInfo = result;
  13623. if (fastCheck) {
  13624. break;
  13625. }
  13626. }
  13627. return pickingInfo || new BABYLON.PickingInfo();
  13628. };
  13629. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13630. var _this = this;
  13631. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13632. /// <param name="x">X position on screen</param>
  13633. /// <param name="y">Y position on screen</param>
  13634. /// <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>
  13635. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13636. /// <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>
  13637. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13638. };
  13639. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13640. var _this = this;
  13641. return this._internalPick(function (world) {
  13642. if (!_this._pickWithRayInverseMatrix) {
  13643. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13644. }
  13645. world.invertToRef(_this._pickWithRayInverseMatrix);
  13646. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13647. }, predicate, fastCheck);
  13648. };
  13649. Scene.prototype.setPointerOverMesh = function (mesh) {
  13650. if (this._pointerOverMesh === mesh) {
  13651. return;
  13652. }
  13653. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13654. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13655. }
  13656. this._pointerOverMesh = mesh;
  13657. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13658. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13659. }
  13660. };
  13661. Scene.prototype.getPointerOverMesh = function () {
  13662. return this._pointerOverMesh;
  13663. };
  13664. // Physics
  13665. Scene.prototype.getPhysicsEngine = function () {
  13666. return this._physicsEngine;
  13667. };
  13668. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13669. if (this._physicsEngine) {
  13670. return true;
  13671. }
  13672. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13673. if (!this._physicsEngine.isSupported()) {
  13674. this._physicsEngine = null;
  13675. return false;
  13676. }
  13677. this._physicsEngine._initialize(gravity);
  13678. return true;
  13679. };
  13680. Scene.prototype.disablePhysicsEngine = function () {
  13681. if (!this._physicsEngine) {
  13682. return;
  13683. }
  13684. this._physicsEngine.dispose();
  13685. this._physicsEngine = undefined;
  13686. };
  13687. Scene.prototype.isPhysicsEnabled = function () {
  13688. return this._physicsEngine !== undefined;
  13689. };
  13690. Scene.prototype.setGravity = function (gravity) {
  13691. if (!this._physicsEngine) {
  13692. return;
  13693. }
  13694. this._physicsEngine._setGravity(gravity);
  13695. };
  13696. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13697. if (parts.parts) {
  13698. options = parts;
  13699. parts = parts.parts;
  13700. }
  13701. if (!this._physicsEngine) {
  13702. return null;
  13703. }
  13704. for (var index = 0; index < parts.length; index++) {
  13705. var mesh = parts[index].mesh;
  13706. mesh._physicImpostor = parts[index].impostor;
  13707. mesh._physicsMass = options.mass / parts.length;
  13708. mesh._physicsFriction = options.friction;
  13709. mesh._physicRestitution = options.restitution;
  13710. }
  13711. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13712. };
  13713. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13714. for (var index = 0; index < compound.parts.length; index++) {
  13715. var mesh = compound.parts[index].mesh;
  13716. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13717. this._physicsEngine._unregisterMesh(mesh);
  13718. }
  13719. };
  13720. // Misc.
  13721. Scene.prototype.createDefaultCameraOrLight = function () {
  13722. // Light
  13723. if (this.lights.length === 0) {
  13724. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13725. }
  13726. // Camera
  13727. if (!this.activeCamera) {
  13728. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13729. // Compute position
  13730. var worldExtends = this.getWorldExtends();
  13731. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13732. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13733. camera.setTarget(worldCenter);
  13734. this.activeCamera = camera;
  13735. }
  13736. };
  13737. // Tags
  13738. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13739. if (tagsQuery === undefined) {
  13740. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13741. return list;
  13742. }
  13743. var listByTags = [];
  13744. forEach = forEach || (function (item) { return; });
  13745. for (var i in list) {
  13746. var item = list[i];
  13747. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13748. listByTags.push(item);
  13749. forEach(item);
  13750. }
  13751. }
  13752. return listByTags;
  13753. };
  13754. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13755. return this._getByTags(this.meshes, tagsQuery, forEach);
  13756. };
  13757. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13758. return this._getByTags(this.cameras, tagsQuery, forEach);
  13759. };
  13760. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13761. return this._getByTags(this.lights, tagsQuery, forEach);
  13762. };
  13763. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13764. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13765. };
  13766. // Statics
  13767. Scene._FOGMODE_NONE = 0;
  13768. Scene._FOGMODE_EXP = 1;
  13769. Scene._FOGMODE_EXP2 = 2;
  13770. Scene._FOGMODE_LINEAR = 3;
  13771. Scene.MinDeltaTime = 1.0;
  13772. Scene.MaxDeltaTime = 1000.0;
  13773. return Scene;
  13774. })();
  13775. BABYLON.Scene = Scene;
  13776. })(BABYLON || (BABYLON = {}));
  13777. //# sourceMappingURL=babylon.scene.js.map
  13778. var BABYLON;
  13779. (function (BABYLON) {
  13780. var VertexBuffer = (function () {
  13781. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13782. if (engine instanceof BABYLON.Mesh) {
  13783. this._engine = engine.getScene().getEngine();
  13784. }
  13785. else {
  13786. this._engine = engine;
  13787. }
  13788. this._updatable = updatable;
  13789. this._data = data;
  13790. if (!postponeInternalCreation) {
  13791. this.create();
  13792. }
  13793. this._kind = kind;
  13794. if (stride) {
  13795. this._strideSize = stride;
  13796. return;
  13797. }
  13798. // Deduce stride from kind
  13799. switch (kind) {
  13800. case VertexBuffer.PositionKind:
  13801. this._strideSize = 3;
  13802. break;
  13803. case VertexBuffer.NormalKind:
  13804. this._strideSize = 3;
  13805. break;
  13806. case VertexBuffer.UVKind:
  13807. this._strideSize = 2;
  13808. break;
  13809. case VertexBuffer.UV2Kind:
  13810. this._strideSize = 2;
  13811. break;
  13812. case VertexBuffer.ColorKind:
  13813. this._strideSize = 4;
  13814. break;
  13815. case VertexBuffer.MatricesIndicesKind:
  13816. this._strideSize = 4;
  13817. break;
  13818. case VertexBuffer.MatricesWeightsKind:
  13819. this._strideSize = 4;
  13820. break;
  13821. }
  13822. }
  13823. // Properties
  13824. VertexBuffer.prototype.isUpdatable = function () {
  13825. return this._updatable;
  13826. };
  13827. VertexBuffer.prototype.getData = function () {
  13828. return this._data;
  13829. };
  13830. VertexBuffer.prototype.getBuffer = function () {
  13831. return this._buffer;
  13832. };
  13833. VertexBuffer.prototype.getStrideSize = function () {
  13834. return this._strideSize;
  13835. };
  13836. // Methods
  13837. VertexBuffer.prototype.create = function (data) {
  13838. if (!data && this._buffer) {
  13839. return; // nothing to do
  13840. }
  13841. data = data || this._data;
  13842. if (!this._buffer) {
  13843. if (this._updatable) {
  13844. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13845. }
  13846. else {
  13847. this._buffer = this._engine.createVertexBuffer(data);
  13848. }
  13849. }
  13850. if (this._updatable) {
  13851. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13852. this._data = data;
  13853. }
  13854. };
  13855. VertexBuffer.prototype.update = function (data) {
  13856. this.create(data);
  13857. };
  13858. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13859. if (!this._buffer) {
  13860. return;
  13861. }
  13862. if (this._updatable) {
  13863. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13864. this._data = null;
  13865. }
  13866. };
  13867. VertexBuffer.prototype.dispose = function () {
  13868. if (!this._buffer) {
  13869. return;
  13870. }
  13871. if (this._engine._releaseBuffer(this._buffer)) {
  13872. this._buffer = null;
  13873. }
  13874. };
  13875. Object.defineProperty(VertexBuffer, "PositionKind", {
  13876. get: function () {
  13877. return VertexBuffer._PositionKind;
  13878. },
  13879. enumerable: true,
  13880. configurable: true
  13881. });
  13882. Object.defineProperty(VertexBuffer, "NormalKind", {
  13883. get: function () {
  13884. return VertexBuffer._NormalKind;
  13885. },
  13886. enumerable: true,
  13887. configurable: true
  13888. });
  13889. Object.defineProperty(VertexBuffer, "UVKind", {
  13890. get: function () {
  13891. return VertexBuffer._UVKind;
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13897. get: function () {
  13898. return VertexBuffer._UV2Kind;
  13899. },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. Object.defineProperty(VertexBuffer, "ColorKind", {
  13904. get: function () {
  13905. return VertexBuffer._ColorKind;
  13906. },
  13907. enumerable: true,
  13908. configurable: true
  13909. });
  13910. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13911. get: function () {
  13912. return VertexBuffer._MatricesIndicesKind;
  13913. },
  13914. enumerable: true,
  13915. configurable: true
  13916. });
  13917. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13918. get: function () {
  13919. return VertexBuffer._MatricesWeightsKind;
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. // Enums
  13925. VertexBuffer._PositionKind = "position";
  13926. VertexBuffer._NormalKind = "normal";
  13927. VertexBuffer._UVKind = "uv";
  13928. VertexBuffer._UV2Kind = "uv2";
  13929. VertexBuffer._ColorKind = "color";
  13930. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13931. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13932. return VertexBuffer;
  13933. })();
  13934. BABYLON.VertexBuffer = VertexBuffer;
  13935. })(BABYLON || (BABYLON = {}));
  13936. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13937. var __extends = (this && this.__extends) || function (d, b) {
  13938. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13939. function __() { this.constructor = d; }
  13940. __.prototype = b.prototype;
  13941. d.prototype = new __();
  13942. };
  13943. var BABYLON;
  13944. (function (BABYLON) {
  13945. /**
  13946. * Creates an instance based on a source mesh.
  13947. */
  13948. var InstancedMesh = (function (_super) {
  13949. __extends(InstancedMesh, _super);
  13950. function InstancedMesh(name, source) {
  13951. _super.call(this, name, source.getScene());
  13952. source.instances.push(this);
  13953. this._sourceMesh = source;
  13954. this.position.copyFrom(source.position);
  13955. this.rotation.copyFrom(source.rotation);
  13956. this.scaling.copyFrom(source.scaling);
  13957. if (source.rotationQuaternion) {
  13958. this.rotationQuaternion = source.rotationQuaternion.clone();
  13959. }
  13960. this.infiniteDistance = source.infiniteDistance;
  13961. this.setPivotMatrix(source.getPivotMatrix());
  13962. this.refreshBoundingInfo();
  13963. this._syncSubMeshes();
  13964. }
  13965. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13966. // Methods
  13967. get: function () {
  13968. return this._sourceMesh.receiveShadows;
  13969. },
  13970. enumerable: true,
  13971. configurable: true
  13972. });
  13973. Object.defineProperty(InstancedMesh.prototype, "material", {
  13974. get: function () {
  13975. return this._sourceMesh.material;
  13976. },
  13977. enumerable: true,
  13978. configurable: true
  13979. });
  13980. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13981. get: function () {
  13982. return this._sourceMesh.visibility;
  13983. },
  13984. enumerable: true,
  13985. configurable: true
  13986. });
  13987. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13988. get: function () {
  13989. return this._sourceMesh.skeleton;
  13990. },
  13991. enumerable: true,
  13992. configurable: true
  13993. });
  13994. InstancedMesh.prototype.getTotalVertices = function () {
  13995. return this._sourceMesh.getTotalVertices();
  13996. };
  13997. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13998. get: function () {
  13999. return this._sourceMesh;
  14000. },
  14001. enumerable: true,
  14002. configurable: true
  14003. });
  14004. InstancedMesh.prototype.getVerticesData = function (kind) {
  14005. return this._sourceMesh.getVerticesData(kind);
  14006. };
  14007. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14008. return this._sourceMesh.isVerticesDataPresent(kind);
  14009. };
  14010. InstancedMesh.prototype.getIndices = function () {
  14011. return this._sourceMesh.getIndices();
  14012. };
  14013. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14014. get: function () {
  14015. return this._sourceMesh._positions;
  14016. },
  14017. enumerable: true,
  14018. configurable: true
  14019. });
  14020. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14021. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14022. if (data) {
  14023. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14024. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14025. }
  14026. this._updateBoundingInfo();
  14027. };
  14028. InstancedMesh.prototype._preActivate = function () {
  14029. if (this._currentLOD) {
  14030. this._currentLOD._preActivate();
  14031. }
  14032. };
  14033. InstancedMesh.prototype._activate = function (renderId) {
  14034. if (this._currentLOD) {
  14035. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14036. }
  14037. };
  14038. InstancedMesh.prototype.getLOD = function (camera) {
  14039. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14040. if (this._currentLOD === this.sourceMesh) {
  14041. return this;
  14042. }
  14043. return this._currentLOD;
  14044. };
  14045. InstancedMesh.prototype._syncSubMeshes = function () {
  14046. this.releaseSubMeshes();
  14047. if (this._sourceMesh.subMeshes) {
  14048. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14049. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14050. }
  14051. }
  14052. };
  14053. InstancedMesh.prototype._generatePointsArray = function () {
  14054. return this._sourceMesh._generatePointsArray();
  14055. };
  14056. // Clone
  14057. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14058. var result = this._sourceMesh.createInstance(name);
  14059. // Deep copy
  14060. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14061. // Bounding info
  14062. this.refreshBoundingInfo();
  14063. // Parent
  14064. if (newParent) {
  14065. result.parent = newParent;
  14066. }
  14067. if (!doNotCloneChildren) {
  14068. // Children
  14069. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14070. var mesh = this.getScene().meshes[index];
  14071. if (mesh.parent === this) {
  14072. mesh.clone(mesh.name, result);
  14073. }
  14074. }
  14075. }
  14076. result.computeWorldMatrix(true);
  14077. return result;
  14078. };
  14079. // Dispoe
  14080. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14081. // Remove from mesh
  14082. var index = this._sourceMesh.instances.indexOf(this);
  14083. this._sourceMesh.instances.splice(index, 1);
  14084. _super.prototype.dispose.call(this, doNotRecurse);
  14085. };
  14086. return InstancedMesh;
  14087. })(BABYLON.AbstractMesh);
  14088. BABYLON.InstancedMesh = InstancedMesh;
  14089. })(BABYLON || (BABYLON = {}));
  14090. //# sourceMappingURL=babylon.instancedMesh.js.map
  14091. var __extends = (this && this.__extends) || function (d, b) {
  14092. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14093. function __() { this.constructor = d; }
  14094. __.prototype = b.prototype;
  14095. d.prototype = new __();
  14096. };
  14097. var BABYLON;
  14098. (function (BABYLON) {
  14099. var _InstancesBatch = (function () {
  14100. function _InstancesBatch() {
  14101. this.mustReturn = false;
  14102. this.visibleInstances = new Array();
  14103. this.renderSelf = new Array();
  14104. }
  14105. return _InstancesBatch;
  14106. })();
  14107. BABYLON._InstancesBatch = _InstancesBatch;
  14108. var Mesh = (function (_super) {
  14109. __extends(Mesh, _super);
  14110. /**
  14111. * @constructor
  14112. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14113. * @param {Scene} scene - The scene to add this mesh to.
  14114. * @param {Node} parent - The parent of this mesh, if it has one
  14115. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14116. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14117. * When false, achieved by calling a clone(), also passing False.
  14118. * This will make creation of children, recursive.
  14119. */
  14120. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14121. if (parent === void 0) { parent = null; }
  14122. _super.call(this, name, scene);
  14123. // Members
  14124. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14125. this.instances = new Array();
  14126. this._LODLevels = new Array();
  14127. this._onBeforeRenderCallbacks = new Array();
  14128. this._onAfterRenderCallbacks = new Array();
  14129. this._visibleInstances = {};
  14130. this._renderIdForInstances = new Array();
  14131. this._batchCache = new _InstancesBatch();
  14132. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14133. this._sideOrientation = Mesh._DEFAULTSIDE;
  14134. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14135. if (source) {
  14136. // Geometry
  14137. if (source._geometry) {
  14138. source._geometry.applyToMesh(this);
  14139. }
  14140. // Deep copy
  14141. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14142. // Material
  14143. this.material = source.material;
  14144. if (!doNotCloneChildren) {
  14145. // Children
  14146. for (var index = 0; index < scene.meshes.length; index++) {
  14147. var mesh = scene.meshes[index];
  14148. if (mesh.parent === source) {
  14149. // doNotCloneChildren is always going to be False
  14150. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14151. }
  14152. }
  14153. }
  14154. // Particles
  14155. for (index = 0; index < scene.particleSystems.length; index++) {
  14156. var system = scene.particleSystems[index];
  14157. if (system.emitter === source) {
  14158. system.clone(system.name, this);
  14159. }
  14160. }
  14161. this.computeWorldMatrix(true);
  14162. }
  14163. // Parent
  14164. if (parent !== null) {
  14165. this.parent = parent;
  14166. }
  14167. }
  14168. Object.defineProperty(Mesh, "FRONTSIDE", {
  14169. get: function () {
  14170. return Mesh._FRONTSIDE;
  14171. },
  14172. enumerable: true,
  14173. configurable: true
  14174. });
  14175. Object.defineProperty(Mesh, "BACKSIDE", {
  14176. get: function () {
  14177. return Mesh._BACKSIDE;
  14178. },
  14179. enumerable: true,
  14180. configurable: true
  14181. });
  14182. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14183. get: function () {
  14184. return Mesh._DOUBLESIDE;
  14185. },
  14186. enumerable: true,
  14187. configurable: true
  14188. });
  14189. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14190. get: function () {
  14191. return Mesh._DEFAULTSIDE;
  14192. },
  14193. enumerable: true,
  14194. configurable: true
  14195. });
  14196. Object.defineProperty(Mesh, "NO_CAP", {
  14197. get: function () {
  14198. return Mesh._NO_CAP;
  14199. },
  14200. enumerable: true,
  14201. configurable: true
  14202. });
  14203. Object.defineProperty(Mesh, "CAP_START", {
  14204. get: function () {
  14205. return Mesh._CAP_START;
  14206. },
  14207. enumerable: true,
  14208. configurable: true
  14209. });
  14210. Object.defineProperty(Mesh, "CAP_END", {
  14211. get: function () {
  14212. return Mesh._CAP_END;
  14213. },
  14214. enumerable: true,
  14215. configurable: true
  14216. });
  14217. Object.defineProperty(Mesh, "CAP_ALL", {
  14218. get: function () {
  14219. return Mesh._CAP_ALL;
  14220. },
  14221. enumerable: true,
  14222. configurable: true
  14223. });
  14224. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14225. // Methods
  14226. get: function () {
  14227. return this._LODLevels.length > 0;
  14228. },
  14229. enumerable: true,
  14230. configurable: true
  14231. });
  14232. Mesh.prototype._sortLODLevels = function () {
  14233. this._LODLevels.sort(function (a, b) {
  14234. if (a.distance < b.distance) {
  14235. return 1;
  14236. }
  14237. if (a.distance > b.distance) {
  14238. return -1;
  14239. }
  14240. return 0;
  14241. });
  14242. };
  14243. /**
  14244. * Add a mesh as LOD level triggered at the given distance.
  14245. * @param {number} distance - the distance from the center of the object to show this level
  14246. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14247. * @return {BABYLON.Mesh} this mesh (for chaining)
  14248. */
  14249. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14250. if (mesh && mesh._masterMesh) {
  14251. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14252. return this;
  14253. }
  14254. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14255. this._LODLevels.push(level);
  14256. if (mesh) {
  14257. mesh._masterMesh = this;
  14258. }
  14259. this._sortLODLevels();
  14260. return this;
  14261. };
  14262. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14263. for (var index = 0; index < this._LODLevels.length; index++) {
  14264. var level = this._LODLevels[index];
  14265. if (level.distance === distance) {
  14266. return level.mesh;
  14267. }
  14268. }
  14269. return null;
  14270. };
  14271. /**
  14272. * Remove a mesh from the LOD array
  14273. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14274. * @return {BABYLON.Mesh} this mesh (for chaining)
  14275. */
  14276. Mesh.prototype.removeLODLevel = function (mesh) {
  14277. for (var index = 0; index < this._LODLevels.length; index++) {
  14278. if (this._LODLevels[index].mesh === mesh) {
  14279. this._LODLevels.splice(index, 1);
  14280. if (mesh) {
  14281. mesh._masterMesh = null;
  14282. }
  14283. }
  14284. }
  14285. this._sortLODLevels();
  14286. return this;
  14287. };
  14288. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14289. if (!this._LODLevels || this._LODLevels.length === 0) {
  14290. return this;
  14291. }
  14292. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14293. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14294. if (this.onLODLevelSelection) {
  14295. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14296. }
  14297. return this;
  14298. }
  14299. for (var index = 0; index < this._LODLevels.length; index++) {
  14300. var level = this._LODLevels[index];
  14301. if (level.distance < distanceToCamera) {
  14302. if (level.mesh) {
  14303. level.mesh._preActivate();
  14304. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14305. }
  14306. if (this.onLODLevelSelection) {
  14307. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14308. }
  14309. return level.mesh;
  14310. }
  14311. }
  14312. if (this.onLODLevelSelection) {
  14313. this.onLODLevelSelection(distanceToCamera, this, this);
  14314. }
  14315. return this;
  14316. };
  14317. Object.defineProperty(Mesh.prototype, "geometry", {
  14318. get: function () {
  14319. return this._geometry;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. Mesh.prototype.getTotalVertices = function () {
  14325. if (!this._geometry) {
  14326. return 0;
  14327. }
  14328. return this._geometry.getTotalVertices();
  14329. };
  14330. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14331. if (!this._geometry) {
  14332. return null;
  14333. }
  14334. return this._geometry.getVerticesData(kind, copyWhenShared);
  14335. };
  14336. Mesh.prototype.getVertexBuffer = function (kind) {
  14337. if (!this._geometry) {
  14338. return undefined;
  14339. }
  14340. return this._geometry.getVertexBuffer(kind);
  14341. };
  14342. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14343. if (!this._geometry) {
  14344. if (this._delayInfo) {
  14345. return this._delayInfo.indexOf(kind) !== -1;
  14346. }
  14347. return false;
  14348. }
  14349. return this._geometry.isVerticesDataPresent(kind);
  14350. };
  14351. Mesh.prototype.getVerticesDataKinds = function () {
  14352. if (!this._geometry) {
  14353. var result = [];
  14354. if (this._delayInfo) {
  14355. for (var kind in this._delayInfo) {
  14356. result.push(kind);
  14357. }
  14358. }
  14359. return result;
  14360. }
  14361. return this._geometry.getVerticesDataKinds();
  14362. };
  14363. Mesh.prototype.getTotalIndices = function () {
  14364. if (!this._geometry) {
  14365. return 0;
  14366. }
  14367. return this._geometry.getTotalIndices();
  14368. };
  14369. Mesh.prototype.getIndices = function (copyWhenShared) {
  14370. if (!this._geometry) {
  14371. return [];
  14372. }
  14373. return this._geometry.getIndices(copyWhenShared);
  14374. };
  14375. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14376. get: function () {
  14377. return this._masterMesh !== null && this._masterMesh !== undefined;
  14378. },
  14379. enumerable: true,
  14380. configurable: true
  14381. });
  14382. Mesh.prototype.isReady = function () {
  14383. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14384. return false;
  14385. }
  14386. return _super.prototype.isReady.call(this);
  14387. };
  14388. Mesh.prototype.isDisposed = function () {
  14389. return this._isDisposed;
  14390. };
  14391. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14392. get: function () {
  14393. return this._sideOrientation;
  14394. },
  14395. set: function (sideO) {
  14396. this._sideOrientation = sideO;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14402. get: function () {
  14403. return this._areNormalsFrozen;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14409. Mesh.prototype.freezeNormals = function () {
  14410. this._areNormalsFrozen = true;
  14411. };
  14412. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14413. Mesh.prototype.unfreezeNormals = function () {
  14414. this._areNormalsFrozen = false;
  14415. };
  14416. // Methods
  14417. Mesh.prototype._preActivate = function () {
  14418. var sceneRenderId = this.getScene().getRenderId();
  14419. if (this._preActivateId === sceneRenderId) {
  14420. return;
  14421. }
  14422. this._preActivateId = sceneRenderId;
  14423. this._visibleInstances = null;
  14424. };
  14425. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14426. if (!this._visibleInstances) {
  14427. this._visibleInstances = {};
  14428. this._visibleInstances.defaultRenderId = renderId;
  14429. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14430. }
  14431. if (!this._visibleInstances[renderId]) {
  14432. this._visibleInstances[renderId] = new Array();
  14433. }
  14434. this._visibleInstances[renderId].push(instance);
  14435. };
  14436. Mesh.prototype.refreshBoundingInfo = function () {
  14437. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14438. if (data) {
  14439. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14440. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14441. }
  14442. if (this.subMeshes) {
  14443. for (var index = 0; index < this.subMeshes.length; index++) {
  14444. this.subMeshes[index].refreshBoundingInfo();
  14445. }
  14446. }
  14447. this._updateBoundingInfo();
  14448. };
  14449. Mesh.prototype._createGlobalSubMesh = function () {
  14450. var totalVertices = this.getTotalVertices();
  14451. if (!totalVertices || !this.getIndices()) {
  14452. return null;
  14453. }
  14454. this.releaseSubMeshes();
  14455. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14456. };
  14457. Mesh.prototype.subdivide = function (count) {
  14458. if (count < 1) {
  14459. return;
  14460. }
  14461. var totalIndices = this.getTotalIndices();
  14462. var subdivisionSize = (totalIndices / count) | 0;
  14463. var offset = 0;
  14464. // Ensure that subdivisionSize is a multiple of 3
  14465. while (subdivisionSize % 3 !== 0) {
  14466. subdivisionSize++;
  14467. }
  14468. this.releaseSubMeshes();
  14469. for (var index = 0; index < count; index++) {
  14470. if (offset >= totalIndices) {
  14471. break;
  14472. }
  14473. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14474. offset += subdivisionSize;
  14475. }
  14476. this.synchronizeInstances();
  14477. };
  14478. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14479. if (kind instanceof Array) {
  14480. var temp = data;
  14481. data = kind;
  14482. kind = temp;
  14483. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14484. }
  14485. if (!this._geometry) {
  14486. var vertexData = new BABYLON.VertexData();
  14487. vertexData.set(data, kind);
  14488. var scene = this.getScene();
  14489. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14490. }
  14491. else {
  14492. this._geometry.setVerticesData(kind, data, updatable, stride);
  14493. }
  14494. };
  14495. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14496. if (!this._geometry) {
  14497. return;
  14498. }
  14499. if (!makeItUnique) {
  14500. this._geometry.updateVerticesData(kind, data, updateExtends);
  14501. }
  14502. else {
  14503. this.makeGeometryUnique();
  14504. this.updateVerticesData(kind, data, updateExtends, false);
  14505. }
  14506. };
  14507. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14508. if (!this._geometry) {
  14509. return;
  14510. }
  14511. if (!makeItUnique) {
  14512. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14513. }
  14514. else {
  14515. this.makeGeometryUnique();
  14516. this.updateVerticesDataDirectly(kind, data, offset, false);
  14517. }
  14518. };
  14519. // Mesh positions update function :
  14520. // updates the mesh positions according to the positionFunction returned values.
  14521. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14522. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14523. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14524. if (computeNormals === void 0) { computeNormals = true; }
  14525. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14526. positionFunction(positions);
  14527. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14528. if (computeNormals) {
  14529. var indices = this.getIndices();
  14530. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14531. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14532. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14533. }
  14534. };
  14535. Mesh.prototype.makeGeometryUnique = function () {
  14536. if (!this._geometry) {
  14537. return;
  14538. }
  14539. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14540. geometry.applyToMesh(this);
  14541. };
  14542. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14543. if (!this._geometry) {
  14544. var vertexData = new BABYLON.VertexData();
  14545. vertexData.indices = indices;
  14546. var scene = this.getScene();
  14547. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14548. }
  14549. else {
  14550. this._geometry.setIndices(indices, totalVertices);
  14551. }
  14552. };
  14553. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14554. var engine = this.getScene().getEngine();
  14555. // Wireframe
  14556. var indexToBind;
  14557. switch (fillMode) {
  14558. case BABYLON.Material.PointFillMode:
  14559. indexToBind = null;
  14560. break;
  14561. case BABYLON.Material.WireFrameFillMode:
  14562. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14563. break;
  14564. default:
  14565. case BABYLON.Material.TriangleFillMode:
  14566. indexToBind = this._geometry.getIndexBuffer();
  14567. break;
  14568. }
  14569. // VBOs
  14570. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14571. };
  14572. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14573. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14574. return;
  14575. }
  14576. var engine = this.getScene().getEngine();
  14577. // Draw order
  14578. switch (fillMode) {
  14579. case BABYLON.Material.PointFillMode:
  14580. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14581. break;
  14582. case BABYLON.Material.WireFrameFillMode:
  14583. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14584. break;
  14585. default:
  14586. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14587. }
  14588. };
  14589. Mesh.prototype.registerBeforeRender = function (func) {
  14590. this._onBeforeRenderCallbacks.push(func);
  14591. };
  14592. Mesh.prototype.unregisterBeforeRender = function (func) {
  14593. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14594. if (index > -1) {
  14595. this._onBeforeRenderCallbacks.splice(index, 1);
  14596. }
  14597. };
  14598. Mesh.prototype.registerAfterRender = function (func) {
  14599. this._onAfterRenderCallbacks.push(func);
  14600. };
  14601. Mesh.prototype.unregisterAfterRender = function (func) {
  14602. var index = this._onAfterRenderCallbacks.indexOf(func);
  14603. if (index > -1) {
  14604. this._onAfterRenderCallbacks.splice(index, 1);
  14605. }
  14606. };
  14607. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14608. var scene = this.getScene();
  14609. this._batchCache.mustReturn = false;
  14610. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14611. this._batchCache.visibleInstances[subMeshId] = null;
  14612. if (this._visibleInstances) {
  14613. var currentRenderId = scene.getRenderId();
  14614. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14615. var selfRenderId = this._renderId;
  14616. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14617. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14618. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14619. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14620. }
  14621. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14622. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14623. this._batchCache.mustReturn = true;
  14624. return this._batchCache;
  14625. }
  14626. if (currentRenderId !== selfRenderId) {
  14627. this._batchCache.renderSelf[subMeshId] = false;
  14628. }
  14629. }
  14630. this._renderIdForInstances[subMeshId] = currentRenderId;
  14631. }
  14632. return this._batchCache;
  14633. };
  14634. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14635. var visibleInstances = batch.visibleInstances[subMesh._id];
  14636. var matricesCount = visibleInstances.length + 1;
  14637. var bufferSize = matricesCount * 16 * 4;
  14638. while (this._instancesBufferSize < bufferSize) {
  14639. this._instancesBufferSize *= 2;
  14640. }
  14641. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14642. if (this._worldMatricesInstancesBuffer) {
  14643. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14644. }
  14645. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14646. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14647. }
  14648. var offset = 0;
  14649. var instancesCount = 0;
  14650. var world = this.getWorldMatrix();
  14651. if (batch.renderSelf[subMesh._id]) {
  14652. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14653. offset += 16;
  14654. instancesCount++;
  14655. }
  14656. if (visibleInstances) {
  14657. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14658. var instance = visibleInstances[instanceIndex];
  14659. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14660. offset += 16;
  14661. instancesCount++;
  14662. }
  14663. }
  14664. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14665. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14666. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14667. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14668. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14669. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14670. this._draw(subMesh, fillMode, instancesCount);
  14671. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14672. };
  14673. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14674. var scene = this.getScene();
  14675. var engine = scene.getEngine();
  14676. if (hardwareInstancedRendering) {
  14677. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14678. }
  14679. else {
  14680. if (batch.renderSelf[subMesh._id]) {
  14681. // Draw
  14682. if (onBeforeDraw) {
  14683. onBeforeDraw(false, this.getWorldMatrix());
  14684. }
  14685. this._draw(subMesh, fillMode);
  14686. }
  14687. if (batch.visibleInstances[subMesh._id]) {
  14688. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14689. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14690. // World
  14691. var world = instance.getWorldMatrix();
  14692. if (onBeforeDraw) {
  14693. onBeforeDraw(true, world);
  14694. }
  14695. // Draw
  14696. this._draw(subMesh, fillMode);
  14697. }
  14698. }
  14699. }
  14700. };
  14701. Mesh.prototype.render = function (subMesh) {
  14702. var scene = this.getScene();
  14703. // Managing instances
  14704. var batch = this._getInstancesRenderList(subMesh._id);
  14705. if (batch.mustReturn) {
  14706. return;
  14707. }
  14708. // Checking geometry state
  14709. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14710. return;
  14711. }
  14712. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14713. this._onBeforeRenderCallbacks[callbackIndex](this);
  14714. }
  14715. var engine = scene.getEngine();
  14716. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14717. // Material
  14718. var effectiveMaterial = subMesh.getMaterial();
  14719. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14720. return;
  14721. }
  14722. // Outline - step 1
  14723. var savedDepthWrite = engine.getDepthWrite();
  14724. if (this.renderOutline) {
  14725. engine.setDepthWrite(false);
  14726. scene.getOutlineRenderer().render(subMesh, batch);
  14727. engine.setDepthWrite(savedDepthWrite);
  14728. }
  14729. effectiveMaterial._preBind();
  14730. var effect = effectiveMaterial.getEffect();
  14731. // Bind
  14732. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14733. this._bind(subMesh, effect, fillMode);
  14734. var world = this.getWorldMatrix();
  14735. effectiveMaterial.bind(world, this);
  14736. // Draw
  14737. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14738. if (isInstance) {
  14739. effectiveMaterial.bindOnlyWorldMatrix(world);
  14740. }
  14741. });
  14742. // Unbind
  14743. effectiveMaterial.unbind();
  14744. // Outline - step 2
  14745. if (this.renderOutline && savedDepthWrite) {
  14746. engine.setDepthWrite(true);
  14747. engine.setColorWrite(false);
  14748. scene.getOutlineRenderer().render(subMesh, batch);
  14749. engine.setColorWrite(true);
  14750. }
  14751. // Overlay
  14752. if (this.renderOverlay) {
  14753. var currentMode = engine.getAlphaMode();
  14754. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14755. scene.getOutlineRenderer().render(subMesh, batch, true);
  14756. engine.setAlphaMode(currentMode);
  14757. }
  14758. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14759. this._onAfterRenderCallbacks[callbackIndex](this);
  14760. }
  14761. };
  14762. Mesh.prototype.getEmittedParticleSystems = function () {
  14763. var results = new Array();
  14764. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14765. var particleSystem = this.getScene().particleSystems[index];
  14766. if (particleSystem.emitter === this) {
  14767. results.push(particleSystem);
  14768. }
  14769. }
  14770. return results;
  14771. };
  14772. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14773. var results = new Array();
  14774. var descendants = this.getDescendants();
  14775. descendants.push(this);
  14776. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14777. var particleSystem = this.getScene().particleSystems[index];
  14778. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14779. results.push(particleSystem);
  14780. }
  14781. }
  14782. return results;
  14783. };
  14784. Mesh.prototype.getChildren = function () {
  14785. var results = [];
  14786. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14787. var mesh = this.getScene().meshes[index];
  14788. if (mesh.parent === this) {
  14789. results.push(mesh);
  14790. }
  14791. }
  14792. return results;
  14793. };
  14794. Mesh.prototype._checkDelayState = function () {
  14795. var _this = this;
  14796. var that = this;
  14797. var scene = this.getScene();
  14798. if (this._geometry) {
  14799. this._geometry.load(scene);
  14800. }
  14801. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14802. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14803. scene._addPendingData(that);
  14804. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14805. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14806. if (data instanceof ArrayBuffer) {
  14807. _this._delayLoadingFunction(data, _this);
  14808. }
  14809. else {
  14810. _this._delayLoadingFunction(JSON.parse(data), _this);
  14811. }
  14812. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14813. scene._removePendingData(_this);
  14814. }, function () { }, scene.database, getBinaryData);
  14815. }
  14816. };
  14817. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14818. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14819. return false;
  14820. }
  14821. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14822. return false;
  14823. }
  14824. this._checkDelayState();
  14825. return true;
  14826. };
  14827. Mesh.prototype.setMaterialByID = function (id) {
  14828. var materials = this.getScene().materials;
  14829. for (var index = 0; index < materials.length; index++) {
  14830. if (materials[index].id === id) {
  14831. this.material = materials[index];
  14832. return;
  14833. }
  14834. }
  14835. // Multi
  14836. var multiMaterials = this.getScene().multiMaterials;
  14837. for (index = 0; index < multiMaterials.length; index++) {
  14838. if (multiMaterials[index].id === id) {
  14839. this.material = multiMaterials[index];
  14840. return;
  14841. }
  14842. }
  14843. };
  14844. Mesh.prototype.getAnimatables = function () {
  14845. var results = [];
  14846. if (this.material) {
  14847. results.push(this.material);
  14848. }
  14849. if (this.skeleton) {
  14850. results.push(this.skeleton);
  14851. }
  14852. return results;
  14853. };
  14854. // Geometry
  14855. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14856. // Position
  14857. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14858. return;
  14859. }
  14860. this._resetPointsArrayCache();
  14861. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14862. var temp = [];
  14863. for (var index = 0; index < data.length; index += 3) {
  14864. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14865. }
  14866. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14867. // Normals
  14868. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14869. return;
  14870. }
  14871. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14872. temp = [];
  14873. for (index = 0; index < data.length; index += 3) {
  14874. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14875. }
  14876. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14877. };
  14878. // Cache
  14879. Mesh.prototype._resetPointsArrayCache = function () {
  14880. this._positions = null;
  14881. };
  14882. Mesh.prototype._generatePointsArray = function () {
  14883. if (this._positions)
  14884. return true;
  14885. this._positions = [];
  14886. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14887. if (!data) {
  14888. return false;
  14889. }
  14890. for (var index = 0; index < data.length; index += 3) {
  14891. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14892. }
  14893. return true;
  14894. };
  14895. // Clone
  14896. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14897. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14898. };
  14899. // Dispose
  14900. Mesh.prototype.dispose = function (doNotRecurse) {
  14901. if (this._geometry) {
  14902. this._geometry.releaseForMesh(this, true);
  14903. }
  14904. // Instances
  14905. if (this._worldMatricesInstancesBuffer) {
  14906. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14907. this._worldMatricesInstancesBuffer = null;
  14908. }
  14909. while (this.instances.length) {
  14910. this.instances[0].dispose();
  14911. }
  14912. _super.prototype.dispose.call(this, doNotRecurse);
  14913. };
  14914. // Geometric tools
  14915. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14916. var _this = this;
  14917. var scene = this.getScene();
  14918. var onload = function (img) {
  14919. // Getting height map data
  14920. var canvas = document.createElement("canvas");
  14921. var context = canvas.getContext("2d");
  14922. var heightMapWidth = img.width;
  14923. var heightMapHeight = img.height;
  14924. canvas.width = heightMapWidth;
  14925. canvas.height = heightMapHeight;
  14926. context.drawImage(img, 0, 0);
  14927. // Create VertexData from map data
  14928. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14929. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14930. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14931. //execute success callback, if set
  14932. if (onSuccess) {
  14933. onSuccess(_this);
  14934. }
  14935. };
  14936. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14937. };
  14938. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14939. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14940. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14941. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14942. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14943. return;
  14944. }
  14945. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14946. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14947. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14948. var position = BABYLON.Vector3.Zero();
  14949. var normal = BABYLON.Vector3.Zero();
  14950. var uv = BABYLON.Vector2.Zero();
  14951. for (var index = 0; index < positions.length; index += 3) {
  14952. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14953. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14954. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14955. // Compute height
  14956. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14957. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14958. var pos = (u + v * heightMapWidth) * 4;
  14959. var r = buffer[pos] / 255.0;
  14960. var g = buffer[pos + 1] / 255.0;
  14961. var b = buffer[pos + 2] / 255.0;
  14962. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14963. normal.normalize();
  14964. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14965. position = position.add(normal);
  14966. position.toArray(positions, index);
  14967. }
  14968. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14969. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14970. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14971. };
  14972. Mesh.prototype.convertToFlatShadedMesh = function () {
  14973. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14974. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14975. var kinds = this.getVerticesDataKinds();
  14976. var vbs = [];
  14977. var data = [];
  14978. var newdata = [];
  14979. var updatableNormals = false;
  14980. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14981. var kind = kinds[kindIndex];
  14982. var vertexBuffer = this.getVertexBuffer(kind);
  14983. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14984. updatableNormals = vertexBuffer.isUpdatable();
  14985. kinds.splice(kindIndex, 1);
  14986. kindIndex--;
  14987. continue;
  14988. }
  14989. vbs[kind] = vertexBuffer;
  14990. data[kind] = vbs[kind].getData();
  14991. newdata[kind] = [];
  14992. }
  14993. // Save previous submeshes
  14994. var previousSubmeshes = this.subMeshes.slice(0);
  14995. var indices = this.getIndices();
  14996. var totalIndices = this.getTotalIndices();
  14997. // Generating unique vertices per face
  14998. for (var index = 0; index < totalIndices; index++) {
  14999. var vertexIndex = indices[index];
  15000. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15001. kind = kinds[kindIndex];
  15002. var stride = vbs[kind].getStrideSize();
  15003. for (var offset = 0; offset < stride; offset++) {
  15004. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15005. }
  15006. }
  15007. }
  15008. // Updating faces & normal
  15009. var normals = [];
  15010. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15011. for (index = 0; index < totalIndices; index += 3) {
  15012. indices[index] = index;
  15013. indices[index + 1] = index + 1;
  15014. indices[index + 2] = index + 2;
  15015. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15016. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15017. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15018. var p1p2 = p1.subtract(p2);
  15019. var p3p2 = p3.subtract(p2);
  15020. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15021. // Store same normals for every vertex
  15022. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15023. normals.push(normal.x);
  15024. normals.push(normal.y);
  15025. normals.push(normal.z);
  15026. }
  15027. }
  15028. this.setIndices(indices);
  15029. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15030. // Updating vertex buffers
  15031. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15032. kind = kinds[kindIndex];
  15033. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15034. }
  15035. // Updating submeshes
  15036. this.releaseSubMeshes();
  15037. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15038. var previousOne = previousSubmeshes[submeshIndex];
  15039. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15040. }
  15041. this.synchronizeInstances();
  15042. };
  15043. // Instances
  15044. Mesh.prototype.createInstance = function (name) {
  15045. return new BABYLON.InstancedMesh(name, this);
  15046. };
  15047. Mesh.prototype.synchronizeInstances = function () {
  15048. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15049. var instance = this.instances[instanceIndex];
  15050. instance._syncSubMeshes();
  15051. }
  15052. };
  15053. /**
  15054. * Simplify the mesh according to the given array of settings.
  15055. * Function will return immediately and will simplify async.
  15056. * @param settings a collection of simplification settings.
  15057. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15058. * @param type the type of simplification to run.
  15059. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15060. */
  15061. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15062. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15063. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15064. this.getScene().simplificationQueue.addTask({
  15065. settings: settings,
  15066. parallelProcessing: parallelProcessing,
  15067. mesh: this,
  15068. simplificationType: simplificationType,
  15069. successCallback: successCallback
  15070. });
  15071. };
  15072. /**
  15073. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15074. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15075. * This should be used together with the simplification to avoid disappearing triangles.
  15076. * @param successCallback an optional success callback to be called after the optimization finished.
  15077. */
  15078. Mesh.prototype.optimizeIndices = function (successCallback) {
  15079. var _this = this;
  15080. var indices = this.getIndices();
  15081. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15082. var vectorPositions = [];
  15083. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15084. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15085. }
  15086. var dupes = [];
  15087. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15088. var realPos = vectorPositions.length - 1 - iteration;
  15089. var testedPosition = vectorPositions[realPos];
  15090. for (var j = 0; j < realPos; ++j) {
  15091. var againstPosition = vectorPositions[j];
  15092. if (testedPosition.equals(againstPosition)) {
  15093. dupes[realPos] = j;
  15094. break;
  15095. }
  15096. }
  15097. }, function () {
  15098. for (var i = 0; i < indices.length; ++i) {
  15099. indices[i] = dupes[indices[i]] || indices[i];
  15100. }
  15101. //indices are now reordered
  15102. var originalSubMeshes = _this.subMeshes.slice(0);
  15103. _this.setIndices(indices);
  15104. _this.subMeshes = originalSubMeshes;
  15105. if (successCallback) {
  15106. successCallback(_this);
  15107. }
  15108. });
  15109. };
  15110. // Statics
  15111. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15112. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15113. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15114. if (ribbonInstance) {
  15115. // positionFunction : ribbon case
  15116. // only pathArray and sideOrientation parameters are taken into account for positions update
  15117. var positionFunction = function (positions) {
  15118. var minlg = pathArray[0].length;
  15119. var i = 0;
  15120. var ns = (ribbonInstance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15121. for (var si = 1; si <= ns; si++) {
  15122. for (var p = 0; p < pathArray.length; p++) {
  15123. var path = pathArray[p];
  15124. var l = path.length;
  15125. minlg = (minlg < l) ? minlg : l;
  15126. var j = 0;
  15127. while (j < minlg) {
  15128. positions[i] = path[j].x;
  15129. positions[i + 1] = path[j].y;
  15130. positions[i + 2] = path[j].z;
  15131. j++;
  15132. i += 3;
  15133. }
  15134. }
  15135. }
  15136. };
  15137. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15138. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15139. return ribbonInstance;
  15140. }
  15141. else {
  15142. var ribbon = new Mesh(name, scene);
  15143. ribbon.sideOrientation = sideOrientation;
  15144. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15145. vertexData.applyToMesh(ribbon, updatable);
  15146. return ribbon;
  15147. }
  15148. };
  15149. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15150. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15151. var disc = new Mesh(name, scene);
  15152. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15153. vertexData.applyToMesh(disc, updatable);
  15154. return disc;
  15155. };
  15156. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15157. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15158. var box = new Mesh(name, scene);
  15159. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15160. vertexData.applyToMesh(box, updatable);
  15161. return box;
  15162. };
  15163. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15164. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15165. var sphere = new Mesh(name, scene);
  15166. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15167. vertexData.applyToMesh(sphere, updatable);
  15168. return sphere;
  15169. };
  15170. // Cylinder and cone (Code inspired by SharpDX.org)
  15171. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15172. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15173. // subdivisions is a new parameter, we need to support old signature
  15174. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15175. if (scene !== undefined) {
  15176. updatable = scene;
  15177. }
  15178. scene = subdivisions;
  15179. subdivisions = 1;
  15180. }
  15181. var cylinder = new Mesh(name, scene);
  15182. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15183. vertexData.applyToMesh(cylinder, updatable);
  15184. return cylinder;
  15185. };
  15186. // Torus (Code from SharpDX.org)
  15187. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15188. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15189. var torus = new Mesh(name, scene);
  15190. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15191. vertexData.applyToMesh(torus, updatable);
  15192. return torus;
  15193. };
  15194. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15195. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15196. var torusKnot = new Mesh(name, scene);
  15197. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15198. vertexData.applyToMesh(torusKnot, updatable);
  15199. return torusKnot;
  15200. };
  15201. // Lines
  15202. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15203. if (linesInstance === void 0) { linesInstance = null; }
  15204. if (linesInstance) {
  15205. var positionFunction = function (positions) {
  15206. var i = 0;
  15207. for (var p = 0; p < points.length; p++) {
  15208. positions[i] = points[p].x;
  15209. positions[i + 1] = points[p].y;
  15210. positions[i + 2] = points[p].z;
  15211. i += 3;
  15212. }
  15213. };
  15214. linesInstance.updateMeshPositions(positionFunction, false);
  15215. return linesInstance;
  15216. }
  15217. // lines creation
  15218. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15219. var vertexData = BABYLON.VertexData.CreateLines(points);
  15220. vertexData.applyToMesh(lines, updatable);
  15221. return lines;
  15222. };
  15223. // Dashed Lines
  15224. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15225. if (linesInstance === void 0) { linesInstance = null; }
  15226. if (linesInstance) {
  15227. var positionFunction = function (positions) {
  15228. var curvect = BABYLON.Vector3.Zero();
  15229. var nbSeg = positions.length / 6;
  15230. var lg = 0;
  15231. var nb = 0;
  15232. var shft = 0;
  15233. var dashshft = 0;
  15234. var curshft = 0;
  15235. var p = 0;
  15236. var i = 0;
  15237. var j = 0;
  15238. for (i = 0; i < points.length - 1; i++) {
  15239. points[i + 1].subtractToRef(points[i], curvect);
  15240. lg += curvect.length();
  15241. }
  15242. shft = lg / nbSeg;
  15243. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15244. for (i = 0; i < points.length - 1; i++) {
  15245. points[i + 1].subtractToRef(points[i], curvect);
  15246. nb = Math.floor(curvect.length() / shft);
  15247. curvect.normalize();
  15248. j = 0;
  15249. while (j < nb && p < positions.length) {
  15250. curshft = shft * j;
  15251. positions[p] = points[i].x + curshft * curvect.x;
  15252. positions[p + 1] = points[i].y + curshft * curvect.y;
  15253. positions[p + 2] = points[i].z + curshft * curvect.z;
  15254. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15255. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15256. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15257. p += 6;
  15258. j++;
  15259. }
  15260. }
  15261. while (p < positions.length) {
  15262. positions[p] = points[i].x;
  15263. positions[p + 1] = points[i].y;
  15264. positions[p + 2] = points[i].z;
  15265. p += 3;
  15266. }
  15267. };
  15268. linesInstance.updateMeshPositions(positionFunction, false);
  15269. return linesInstance;
  15270. }
  15271. // dashed lines creation
  15272. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15273. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15274. vertexData.applyToMesh(dashedLines, updatable);
  15275. dashedLines.dashSize = dashSize;
  15276. dashedLines.gapSize = gapSize;
  15277. return dashedLines;
  15278. };
  15279. // Extrusion
  15280. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15281. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15282. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15283. scale = scale || 1;
  15284. rotation = rotation || 0;
  15285. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15286. return extruded;
  15287. };
  15288. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15289. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15290. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15291. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15292. return extrudedCustom;
  15293. };
  15294. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15295. // extrusion geometry
  15296. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15297. var tangents = path3D.getTangents();
  15298. var normals = path3D.getNormals();
  15299. var binormals = path3D.getBinormals();
  15300. var distances = path3D.getDistances();
  15301. var angle = 0;
  15302. var returnScale = function (i, distance) { return scale; };
  15303. var returnRotation = function (i, distance) { return rotation; };
  15304. var rotate = custom ? rotateFunction : returnRotation;
  15305. var scl = custom ? scaleFunction : returnScale;
  15306. var index = 0;
  15307. for (var i = 0; i < curve.length; i++) {
  15308. var shapePath = new Array();
  15309. var angleStep = rotate(i, distances[i]);
  15310. var scaleRatio = scl(i, distances[i]);
  15311. for (var p = 0; p < shape.length; p++) {
  15312. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15313. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15314. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15315. shapePath.push(rotated);
  15316. }
  15317. shapePaths[index] = shapePath;
  15318. angle += angleStep;
  15319. index++;
  15320. }
  15321. // cap
  15322. var capPath = function (shapePath) {
  15323. var pointCap = Array();
  15324. var barycenter = BABYLON.Vector3.Zero();
  15325. var i;
  15326. for (i = 0; i < shapePath.length; i++) {
  15327. barycenter.addInPlace(shapePath[i]);
  15328. }
  15329. barycenter.scaleInPlace(1 / shapePath.length);
  15330. for (i = 0; i < shapePath.length; i++) {
  15331. pointCap.push(barycenter);
  15332. }
  15333. return pointCap;
  15334. };
  15335. switch (cap) {
  15336. case BABYLON.Mesh.NO_CAP:
  15337. break;
  15338. case BABYLON.Mesh.CAP_START:
  15339. shapePaths.unshift(capPath(shapePaths[0]));
  15340. break;
  15341. case BABYLON.Mesh.CAP_END:
  15342. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15343. break;
  15344. case BABYLON.Mesh.CAP_ALL:
  15345. shapePaths.unshift(capPath(shapePaths[0]));
  15346. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15347. break;
  15348. default:
  15349. break;
  15350. }
  15351. return shapePaths;
  15352. };
  15353. if (instance) {
  15354. var path3D = (instance.path3D).update(curve);
  15355. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15356. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15357. return instance;
  15358. }
  15359. // extruded shape creation
  15360. var path3D = new BABYLON.Path3D(curve);
  15361. var newShapePaths = new Array();
  15362. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15363. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15364. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15365. extrudedGeneric.pathArray = pathArray;
  15366. extrudedGeneric.path3D = path3D;
  15367. extrudedGeneric.cap = cap;
  15368. return extrudedGeneric;
  15369. };
  15370. // Lathe
  15371. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15372. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15373. radius = radius || 1;
  15374. tessellation = tessellation || radius * 60;
  15375. var pi2 = Math.PI * 2;
  15376. var Y = BABYLON.Axis.Y;
  15377. var shapeLathe = new Array();
  15378. // first rotatable point
  15379. var i = 0;
  15380. while (shape[i].x === 0) {
  15381. i++;
  15382. }
  15383. var pt = shape[i];
  15384. for (i = 0; i < shape.length; i++) {
  15385. shapeLathe.push(shape[i].subtract(pt));
  15386. }
  15387. // circle path
  15388. var step = pi2 / tessellation;
  15389. var rotated;
  15390. var path = new Array();
  15391. ;
  15392. for (i = 0; i < tessellation; i++) {
  15393. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15394. path.push(rotated);
  15395. }
  15396. path.push(path[0]);
  15397. // extrusion
  15398. var scaleFunction = function () { return 1; };
  15399. var rotateFunction = function () { return 0; };
  15400. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15401. return lathe;
  15402. };
  15403. // Plane & ground
  15404. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15405. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15406. var plane = new Mesh(name, scene);
  15407. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15408. vertexData.applyToMesh(plane, updatable);
  15409. return plane;
  15410. };
  15411. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15412. var ground = new BABYLON.GroundMesh(name, scene);
  15413. ground._setReady(false);
  15414. ground._subdivisions = subdivisions;
  15415. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15416. vertexData.applyToMesh(ground, updatable);
  15417. ground._setReady(true);
  15418. return ground;
  15419. };
  15420. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15421. var tiledGround = new Mesh(name, scene);
  15422. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15423. vertexData.applyToMesh(tiledGround, updatable);
  15424. return tiledGround;
  15425. };
  15426. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15427. var ground = new BABYLON.GroundMesh(name, scene);
  15428. ground._subdivisions = subdivisions;
  15429. ground._setReady(false);
  15430. var onload = function (img) {
  15431. // Getting height map data
  15432. var canvas = document.createElement("canvas");
  15433. var context = canvas.getContext("2d");
  15434. var heightMapWidth = img.width;
  15435. var heightMapHeight = img.height;
  15436. canvas.width = heightMapWidth;
  15437. canvas.height = heightMapHeight;
  15438. context.drawImage(img, 0, 0);
  15439. // Create VertexData from map data
  15440. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15441. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15442. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15443. vertexData.applyToMesh(ground, updatable);
  15444. ground._setReady(true);
  15445. //execute ready callback, if set
  15446. if (onReady) {
  15447. onReady(ground);
  15448. }
  15449. };
  15450. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15451. return ground;
  15452. };
  15453. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15454. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15455. if (tubeInstance === void 0) { tubeInstance = null; }
  15456. // tube geometry
  15457. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15458. var tangents = path3D.getTangents();
  15459. var normals = path3D.getNormals();
  15460. var distances = path3D.getDistances();
  15461. var pi2 = Math.PI * 2;
  15462. var step = pi2 / tessellation;
  15463. var returnRadius = function (i, distance) { return radius; };
  15464. var radiusFunctionFinal = radiusFunction || returnRadius;
  15465. var circlePath;
  15466. var rad;
  15467. var normal;
  15468. var rotated;
  15469. var rotationMatrix;
  15470. var index = 0;
  15471. for (var i = 0; i < path.length; i++) {
  15472. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15473. circlePath = Array(); // current circle array
  15474. normal = normals[i]; // current normal
  15475. for (var t = 0; t < tessellation; t++) {
  15476. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15477. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15478. circlePath.push(rotated);
  15479. }
  15480. circlePath.push(circlePath[0]);
  15481. circlePaths[index] = circlePath;
  15482. index++;
  15483. }
  15484. // cap
  15485. var capPath = function (nbPoints, pathIndex) {
  15486. var pointCap = Array();
  15487. for (var i = 0; i < nbPoints; i++) {
  15488. pointCap.push(path[pathIndex]);
  15489. }
  15490. return pointCap;
  15491. };
  15492. switch (cap) {
  15493. case BABYLON.Mesh.NO_CAP:
  15494. break;
  15495. case BABYLON.Mesh.CAP_START:
  15496. circlePaths.unshift(capPath(tessellation + 1, 0));
  15497. break;
  15498. case BABYLON.Mesh.CAP_END:
  15499. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15500. break;
  15501. case BABYLON.Mesh.CAP_ALL:
  15502. circlePaths.unshift(capPath(tessellation + 1, 0));
  15503. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15504. break;
  15505. default:
  15506. break;
  15507. }
  15508. return circlePaths;
  15509. };
  15510. if (tubeInstance) {
  15511. var path3D = (tubeInstance.path3D).update(path);
  15512. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15513. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15514. return tubeInstance;
  15515. }
  15516. // tube creation
  15517. var path3D = new BABYLON.Path3D(path);
  15518. var newPathArray = new Array();
  15519. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15520. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15521. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15522. tube.pathArray = pathArray;
  15523. tube.path3D = path3D;
  15524. tube.tessellation = tessellation;
  15525. tube.cap = cap;
  15526. return tube;
  15527. };
  15528. // Decals
  15529. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15530. if (angle === void 0) { angle = 0; }
  15531. var indices = sourceMesh.getIndices();
  15532. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15533. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15534. // Getting correct rotation
  15535. if (!normal) {
  15536. var target = new BABYLON.Vector3(0, 0, 1);
  15537. var camera = sourceMesh.getScene().activeCamera;
  15538. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15539. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15540. }
  15541. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15542. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15543. var pitch = Math.atan2(normal.y, len);
  15544. // Matrix
  15545. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15546. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15547. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15548. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15549. var vertexData = new BABYLON.VertexData();
  15550. vertexData.indices = [];
  15551. vertexData.positions = [];
  15552. vertexData.normals = [];
  15553. vertexData.uvs = [];
  15554. var currentVertexDataIndex = 0;
  15555. var extractDecalVector3 = function (indexId) {
  15556. var vertexId = indices[indexId];
  15557. var result = new BABYLON.PositionNormalVertex();
  15558. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15559. // Send vector to decal local world
  15560. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15561. // Get normal
  15562. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15563. return result;
  15564. };
  15565. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15566. var clip = function (vertices, axis) {
  15567. if (vertices.length === 0) {
  15568. return vertices;
  15569. }
  15570. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15571. var clipVertices = function (v0, v1) {
  15572. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15573. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15574. };
  15575. var result = new Array();
  15576. for (var index = 0; index < vertices.length; index += 3) {
  15577. var v1Out;
  15578. var v2Out;
  15579. var v3Out;
  15580. var total = 0;
  15581. var nV1, nV2, nV3, nV4;
  15582. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15583. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15584. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15585. v1Out = d1 > 0;
  15586. v2Out = d2 > 0;
  15587. v3Out = d3 > 0;
  15588. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15589. switch (total) {
  15590. case 0:
  15591. result.push(vertices[index]);
  15592. result.push(vertices[index + 1]);
  15593. result.push(vertices[index + 2]);
  15594. break;
  15595. case 1:
  15596. if (v1Out) {
  15597. nV1 = vertices[index + 1];
  15598. nV2 = vertices[index + 2];
  15599. nV3 = clipVertices(vertices[index], nV1);
  15600. nV4 = clipVertices(vertices[index], nV2);
  15601. }
  15602. if (v2Out) {
  15603. nV1 = vertices[index];
  15604. nV2 = vertices[index + 2];
  15605. nV3 = clipVertices(vertices[index + 1], nV1);
  15606. nV4 = clipVertices(vertices[index + 1], nV2);
  15607. result.push(nV3);
  15608. result.push(nV2.clone());
  15609. result.push(nV1.clone());
  15610. result.push(nV2.clone());
  15611. result.push(nV3.clone());
  15612. result.push(nV4);
  15613. break;
  15614. }
  15615. if (v3Out) {
  15616. nV1 = vertices[index];
  15617. nV2 = vertices[index + 1];
  15618. nV3 = clipVertices(vertices[index + 2], nV1);
  15619. nV4 = clipVertices(vertices[index + 2], nV2);
  15620. }
  15621. result.push(nV1.clone());
  15622. result.push(nV2.clone());
  15623. result.push(nV3);
  15624. result.push(nV4);
  15625. result.push(nV3.clone());
  15626. result.push(nV2.clone());
  15627. break;
  15628. case 2:
  15629. if (!v1Out) {
  15630. nV1 = vertices[index].clone();
  15631. nV2 = clipVertices(nV1, vertices[index + 1]);
  15632. nV3 = clipVertices(nV1, vertices[index + 2]);
  15633. result.push(nV1);
  15634. result.push(nV2);
  15635. result.push(nV3);
  15636. }
  15637. if (!v2Out) {
  15638. nV1 = vertices[index + 1].clone();
  15639. nV2 = clipVertices(nV1, vertices[index + 2]);
  15640. nV3 = clipVertices(nV1, vertices[index]);
  15641. result.push(nV1);
  15642. result.push(nV2);
  15643. result.push(nV3);
  15644. }
  15645. if (!v3Out) {
  15646. nV1 = vertices[index + 2].clone();
  15647. nV2 = clipVertices(nV1, vertices[index]);
  15648. nV3 = clipVertices(nV1, vertices[index + 1]);
  15649. result.push(nV1);
  15650. result.push(nV2);
  15651. result.push(nV3);
  15652. }
  15653. break;
  15654. case 3:
  15655. break;
  15656. }
  15657. }
  15658. return result;
  15659. };
  15660. for (var index = 0; index < indices.length; index += 3) {
  15661. var faceVertices = new Array();
  15662. faceVertices.push(extractDecalVector3(index));
  15663. faceVertices.push(extractDecalVector3(index + 1));
  15664. faceVertices.push(extractDecalVector3(index + 2));
  15665. // Clip
  15666. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15667. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15668. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15669. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15670. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15671. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15672. if (faceVertices.length === 0) {
  15673. continue;
  15674. }
  15675. // Add UVs and get back to world
  15676. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15677. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15678. var vertex = faceVertices[vIndex];
  15679. vertexData.indices.push(currentVertexDataIndex);
  15680. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15681. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15682. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15683. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15684. currentVertexDataIndex++;
  15685. }
  15686. }
  15687. // Return mesh
  15688. var decal = new Mesh(name, sourceMesh.getScene());
  15689. vertexData.applyToMesh(decal);
  15690. decal.position = position.clone();
  15691. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15692. return decal;
  15693. };
  15694. // Tools
  15695. Mesh.MinMax = function (meshes) {
  15696. var minVector = null;
  15697. var maxVector = null;
  15698. for (var i in meshes) {
  15699. var mesh = meshes[i];
  15700. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15701. if (!minVector) {
  15702. minVector = boundingBox.minimumWorld;
  15703. maxVector = boundingBox.maximumWorld;
  15704. continue;
  15705. }
  15706. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15707. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15708. }
  15709. return {
  15710. min: minVector,
  15711. max: maxVector
  15712. };
  15713. };
  15714. Mesh.Center = function (meshesOrMinMaxVector) {
  15715. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15716. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15717. };
  15718. /**
  15719. * Merge the array of meshes into a single mesh for performance reasons.
  15720. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15721. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15722. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15723. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15724. */
  15725. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15726. if (disposeSource === void 0) { disposeSource = true; }
  15727. if (!allow32BitsIndices) {
  15728. var totalVertices = 0;
  15729. // Counting vertices
  15730. for (var index = 0; index < meshes.length; index++) {
  15731. if (meshes[index]) {
  15732. totalVertices += meshes[index].getTotalVertices();
  15733. if (totalVertices > 65536) {
  15734. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15735. return null;
  15736. }
  15737. }
  15738. }
  15739. }
  15740. // Merge
  15741. var vertexData;
  15742. var otherVertexData;
  15743. var source;
  15744. for (index = 0; index < meshes.length; index++) {
  15745. if (meshes[index]) {
  15746. meshes[index].computeWorldMatrix(true);
  15747. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15748. otherVertexData.transform(meshes[index].getWorldMatrix());
  15749. if (vertexData) {
  15750. vertexData.merge(otherVertexData);
  15751. }
  15752. else {
  15753. vertexData = otherVertexData;
  15754. source = meshes[index];
  15755. }
  15756. }
  15757. }
  15758. if (!meshSubclass) {
  15759. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15760. }
  15761. vertexData.applyToMesh(meshSubclass);
  15762. // Setting properties
  15763. meshSubclass.material = source.material;
  15764. meshSubclass.checkCollisions = source.checkCollisions;
  15765. // Cleaning
  15766. if (disposeSource) {
  15767. for (index = 0; index < meshes.length; index++) {
  15768. if (meshes[index]) {
  15769. meshes[index].dispose();
  15770. }
  15771. }
  15772. }
  15773. return meshSubclass;
  15774. };
  15775. // Consts
  15776. Mesh._FRONTSIDE = 0;
  15777. Mesh._BACKSIDE = 1;
  15778. Mesh._DOUBLESIDE = 2;
  15779. Mesh._DEFAULTSIDE = 0;
  15780. Mesh._NO_CAP = 0;
  15781. Mesh._CAP_START = 1;
  15782. Mesh._CAP_END = 2;
  15783. Mesh._CAP_ALL = 3;
  15784. return Mesh;
  15785. })(BABYLON.AbstractMesh);
  15786. BABYLON.Mesh = Mesh;
  15787. })(BABYLON || (BABYLON = {}));
  15788. //# sourceMappingURL=babylon.mesh.js.map
  15789. var BABYLON;
  15790. (function (BABYLON) {
  15791. var SubMesh = (function () {
  15792. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15793. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15794. this.materialIndex = materialIndex;
  15795. this.verticesStart = verticesStart;
  15796. this.verticesCount = verticesCount;
  15797. this.indexStart = indexStart;
  15798. this.indexCount = indexCount;
  15799. this._renderId = 0;
  15800. this._mesh = mesh;
  15801. this._renderingMesh = renderingMesh || mesh;
  15802. mesh.subMeshes.push(this);
  15803. this._trianglePlanes = [];
  15804. this._id = mesh.subMeshes.length - 1;
  15805. if (createBoundingBox) {
  15806. this.refreshBoundingInfo();
  15807. mesh.computeWorldMatrix(true);
  15808. }
  15809. }
  15810. SubMesh.prototype.getBoundingInfo = function () {
  15811. return this._boundingInfo;
  15812. };
  15813. SubMesh.prototype.getMesh = function () {
  15814. return this._mesh;
  15815. };
  15816. SubMesh.prototype.getRenderingMesh = function () {
  15817. return this._renderingMesh;
  15818. };
  15819. SubMesh.prototype.getMaterial = function () {
  15820. var rootMaterial = this._renderingMesh.material;
  15821. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15822. var multiMaterial = rootMaterial;
  15823. return multiMaterial.getSubMaterial(this.materialIndex);
  15824. }
  15825. if (!rootMaterial) {
  15826. return this._mesh.getScene().defaultMaterial;
  15827. }
  15828. return rootMaterial;
  15829. };
  15830. // Methods
  15831. SubMesh.prototype.refreshBoundingInfo = function () {
  15832. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15833. if (!data) {
  15834. this._boundingInfo = this._mesh._boundingInfo;
  15835. return;
  15836. }
  15837. var indices = this._renderingMesh.getIndices();
  15838. var extend;
  15839. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15840. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15841. }
  15842. else {
  15843. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15844. }
  15845. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15846. };
  15847. SubMesh.prototype._checkCollision = function (collider) {
  15848. return this._boundingInfo._checkCollision(collider);
  15849. };
  15850. SubMesh.prototype.updateBoundingInfo = function (world) {
  15851. if (!this._boundingInfo) {
  15852. this.refreshBoundingInfo();
  15853. }
  15854. this._boundingInfo._update(world);
  15855. };
  15856. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15857. return this._boundingInfo.isInFrustum(frustumPlanes);
  15858. };
  15859. SubMesh.prototype.render = function () {
  15860. this._renderingMesh.render(this);
  15861. };
  15862. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15863. if (!this._linesIndexBuffer) {
  15864. var linesIndices = [];
  15865. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15866. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15867. }
  15868. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15869. this.linesIndexCount = linesIndices.length;
  15870. }
  15871. return this._linesIndexBuffer;
  15872. };
  15873. SubMesh.prototype.canIntersects = function (ray) {
  15874. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15875. };
  15876. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15877. var intersectInfo = null;
  15878. // Triangles test
  15879. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15880. var p0 = positions[indices[index]];
  15881. var p1 = positions[indices[index + 1]];
  15882. var p2 = positions[indices[index + 2]];
  15883. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15884. if (currentIntersectInfo) {
  15885. if (currentIntersectInfo.distance < 0) {
  15886. continue;
  15887. }
  15888. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15889. intersectInfo = currentIntersectInfo;
  15890. intersectInfo.faceId = index / 3;
  15891. if (fastCheck) {
  15892. break;
  15893. }
  15894. }
  15895. }
  15896. }
  15897. return intersectInfo;
  15898. };
  15899. // Clone
  15900. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15901. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15902. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15903. return result;
  15904. };
  15905. // Dispose
  15906. SubMesh.prototype.dispose = function () {
  15907. if (this._linesIndexBuffer) {
  15908. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15909. this._linesIndexBuffer = null;
  15910. }
  15911. // Remove from mesh
  15912. var index = this._mesh.subMeshes.indexOf(this);
  15913. this._mesh.subMeshes.splice(index, 1);
  15914. };
  15915. // Statics
  15916. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15917. var minVertexIndex = Number.MAX_VALUE;
  15918. var maxVertexIndex = -Number.MAX_VALUE;
  15919. renderingMesh = renderingMesh || mesh;
  15920. var indices = renderingMesh.getIndices();
  15921. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15922. var vertexIndex = indices[index];
  15923. if (vertexIndex < minVertexIndex)
  15924. minVertexIndex = vertexIndex;
  15925. if (vertexIndex > maxVertexIndex)
  15926. maxVertexIndex = vertexIndex;
  15927. }
  15928. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15929. };
  15930. return SubMesh;
  15931. })();
  15932. BABYLON.SubMesh = SubMesh;
  15933. })(BABYLON || (BABYLON = {}));
  15934. //# sourceMappingURL=babylon.subMesh.js.map
  15935. var BABYLON;
  15936. (function (BABYLON) {
  15937. var BaseTexture = (function () {
  15938. function BaseTexture(scene) {
  15939. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15940. this.hasAlpha = false;
  15941. this.getAlphaFromRGB = false;
  15942. this.level = 1;
  15943. this.isCube = false;
  15944. this.isRenderTarget = false;
  15945. this.animations = new Array();
  15946. this.coordinatesIndex = 0;
  15947. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15948. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15949. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15950. this.anisotropicFilteringLevel = 4;
  15951. this._scene = scene;
  15952. this._scene.textures.push(this);
  15953. }
  15954. BaseTexture.prototype.getScene = function () {
  15955. return this._scene;
  15956. };
  15957. BaseTexture.prototype.getTextureMatrix = function () {
  15958. return null;
  15959. };
  15960. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15961. return null;
  15962. };
  15963. BaseTexture.prototype.getInternalTexture = function () {
  15964. return this._texture;
  15965. };
  15966. BaseTexture.prototype.isReady = function () {
  15967. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15968. return true;
  15969. }
  15970. if (this._texture) {
  15971. return this._texture.isReady;
  15972. }
  15973. return false;
  15974. };
  15975. BaseTexture.prototype.getSize = function () {
  15976. if (this._texture._width) {
  15977. return { width: this._texture._width, height: this._texture._height };
  15978. }
  15979. if (this._texture._size) {
  15980. return { width: this._texture._size, height: this._texture._size };
  15981. }
  15982. return { width: 0, height: 0 };
  15983. };
  15984. BaseTexture.prototype.getBaseSize = function () {
  15985. if (!this.isReady())
  15986. return { width: 0, height: 0 };
  15987. if (this._texture._size) {
  15988. return { width: this._texture._size, height: this._texture._size };
  15989. }
  15990. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15991. };
  15992. BaseTexture.prototype.scale = function (ratio) {
  15993. };
  15994. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15995. get: function () {
  15996. return false;
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16002. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16003. for (var index = 0; index < texturesCache.length; index++) {
  16004. var texturesCacheEntry = texturesCache[index];
  16005. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16006. texturesCache.splice(index, 1);
  16007. return;
  16008. }
  16009. }
  16010. };
  16011. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16012. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16013. for (var index = 0; index < texturesCache.length; index++) {
  16014. var texturesCacheEntry = texturesCache[index];
  16015. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16016. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16017. texturesCacheEntry.references++;
  16018. return texturesCacheEntry;
  16019. }
  16020. }
  16021. }
  16022. return null;
  16023. };
  16024. BaseTexture.prototype.delayLoad = function () {
  16025. };
  16026. BaseTexture.prototype.releaseInternalTexture = function () {
  16027. if (!this._texture) {
  16028. return;
  16029. }
  16030. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16031. this._texture.references--;
  16032. // Final reference ?
  16033. if (this._texture.references === 0) {
  16034. var index = texturesCache.indexOf(this._texture);
  16035. texturesCache.splice(index, 1);
  16036. this._scene.getEngine()._releaseTexture(this._texture);
  16037. delete this._texture;
  16038. }
  16039. };
  16040. BaseTexture.prototype.clone = function () {
  16041. return null;
  16042. };
  16043. BaseTexture.prototype.dispose = function () {
  16044. // Remove from scene
  16045. var index = this._scene.textures.indexOf(this);
  16046. if (index >= 0) {
  16047. this._scene.textures.splice(index, 1);
  16048. }
  16049. if (this._texture === undefined) {
  16050. return;
  16051. }
  16052. this.releaseInternalTexture();
  16053. // Callback
  16054. if (this.onDispose) {
  16055. this.onDispose();
  16056. }
  16057. };
  16058. return BaseTexture;
  16059. })();
  16060. BABYLON.BaseTexture = BaseTexture;
  16061. })(BABYLON || (BABYLON = {}));
  16062. //# sourceMappingURL=babylon.baseTexture.js.map
  16063. var __extends = (this && this.__extends) || function (d, b) {
  16064. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16065. function __() { this.constructor = d; }
  16066. __.prototype = b.prototype;
  16067. d.prototype = new __();
  16068. };
  16069. var BABYLON;
  16070. (function (BABYLON) {
  16071. var Texture = (function (_super) {
  16072. __extends(Texture, _super);
  16073. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16074. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16075. if (onLoad === void 0) { onLoad = null; }
  16076. if (onError === void 0) { onError = null; }
  16077. if (buffer === void 0) { buffer = null; }
  16078. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16079. _super.call(this, scene);
  16080. this.uOffset = 0;
  16081. this.vOffset = 0;
  16082. this.uScale = 1.0;
  16083. this.vScale = 1.0;
  16084. this.uAng = 0;
  16085. this.vAng = 0;
  16086. this.wAng = 0;
  16087. this.name = url;
  16088. this.url = url;
  16089. this._noMipmap = noMipmap;
  16090. this._invertY = invertY;
  16091. this._samplingMode = samplingMode;
  16092. this._buffer = buffer;
  16093. this._deleteBuffer = deleteBuffer;
  16094. if (!url) {
  16095. return;
  16096. }
  16097. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16098. if (!this._texture) {
  16099. if (!scene.useDelayedTextureLoading) {
  16100. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16101. if (deleteBuffer) {
  16102. delete this._buffer;
  16103. }
  16104. }
  16105. else {
  16106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16107. }
  16108. }
  16109. else {
  16110. BABYLON.Tools.SetImmediate(function () {
  16111. if (onLoad) {
  16112. onLoad();
  16113. }
  16114. });
  16115. }
  16116. }
  16117. Texture.prototype.delayLoad = function () {
  16118. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16119. return;
  16120. }
  16121. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16122. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16123. if (!this._texture) {
  16124. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16125. if (this._deleteBuffer) {
  16126. delete this._buffer;
  16127. }
  16128. }
  16129. };
  16130. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16131. if (!this._texture) {
  16132. return;
  16133. }
  16134. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16135. };
  16136. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16137. x -= this.uOffset + 0.5;
  16138. y -= this.vOffset + 0.5;
  16139. z -= 0.5;
  16140. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16141. t.x *= this.uScale;
  16142. t.y *= this.vScale;
  16143. t.x += 0.5;
  16144. t.y += 0.5;
  16145. t.z += 0.5;
  16146. };
  16147. Texture.prototype.getTextureMatrix = function () {
  16148. if (this.uOffset === this._cachedUOffset &&
  16149. this.vOffset === this._cachedVOffset &&
  16150. this.uScale === this._cachedUScale &&
  16151. this.vScale === this._cachedVScale &&
  16152. this.uAng === this._cachedUAng &&
  16153. this.vAng === this._cachedVAng &&
  16154. this.wAng === this._cachedWAng) {
  16155. return this._cachedTextureMatrix;
  16156. }
  16157. this._cachedUOffset = this.uOffset;
  16158. this._cachedVOffset = this.vOffset;
  16159. this._cachedUScale = this.uScale;
  16160. this._cachedVScale = this.vScale;
  16161. this._cachedUAng = this.uAng;
  16162. this._cachedVAng = this.vAng;
  16163. this._cachedWAng = this.wAng;
  16164. if (!this._cachedTextureMatrix) {
  16165. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16166. this._rowGenerationMatrix = new BABYLON.Matrix();
  16167. this._t0 = BABYLON.Vector3.Zero();
  16168. this._t1 = BABYLON.Vector3.Zero();
  16169. this._t2 = BABYLON.Vector3.Zero();
  16170. }
  16171. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16172. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16173. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16174. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16175. this._t1.subtractInPlace(this._t0);
  16176. this._t2.subtractInPlace(this._t0);
  16177. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16178. this._cachedTextureMatrix.m[0] = this._t1.x;
  16179. this._cachedTextureMatrix.m[1] = this._t1.y;
  16180. this._cachedTextureMatrix.m[2] = this._t1.z;
  16181. this._cachedTextureMatrix.m[4] = this._t2.x;
  16182. this._cachedTextureMatrix.m[5] = this._t2.y;
  16183. this._cachedTextureMatrix.m[6] = this._t2.z;
  16184. this._cachedTextureMatrix.m[8] = this._t0.x;
  16185. this._cachedTextureMatrix.m[9] = this._t0.y;
  16186. this._cachedTextureMatrix.m[10] = this._t0.z;
  16187. return this._cachedTextureMatrix;
  16188. };
  16189. Texture.prototype.getReflectionTextureMatrix = function () {
  16190. if (this.uOffset === this._cachedUOffset &&
  16191. this.vOffset === this._cachedVOffset &&
  16192. this.uScale === this._cachedUScale &&
  16193. this.vScale === this._cachedVScale &&
  16194. this.coordinatesMode === this._cachedCoordinatesMode) {
  16195. return this._cachedTextureMatrix;
  16196. }
  16197. if (!this._cachedTextureMatrix) {
  16198. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16199. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16200. }
  16201. this._cachedCoordinatesMode = this.coordinatesMode;
  16202. switch (this.coordinatesMode) {
  16203. case Texture.SPHERICAL_MODE:
  16204. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16205. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16206. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16207. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16208. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16209. break;
  16210. case Texture.PLANAR_MODE:
  16211. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16212. this._cachedTextureMatrix[0] = this.uScale;
  16213. this._cachedTextureMatrix[5] = this.vScale;
  16214. this._cachedTextureMatrix[12] = this.uOffset;
  16215. this._cachedTextureMatrix[13] = this.vOffset;
  16216. break;
  16217. case Texture.PROJECTION_MODE:
  16218. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16219. this._projectionModeMatrix.m[0] = 0.5;
  16220. this._projectionModeMatrix.m[5] = -0.5;
  16221. this._projectionModeMatrix.m[10] = 0.0;
  16222. this._projectionModeMatrix.m[12] = 0.5;
  16223. this._projectionModeMatrix.m[13] = 0.5;
  16224. this._projectionModeMatrix.m[14] = 1.0;
  16225. this._projectionModeMatrix.m[15] = 1.0;
  16226. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16227. break;
  16228. default:
  16229. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16230. break;
  16231. }
  16232. return this._cachedTextureMatrix;
  16233. };
  16234. Texture.prototype.clone = function () {
  16235. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16236. // Base texture
  16237. newTexture.hasAlpha = this.hasAlpha;
  16238. newTexture.level = this.level;
  16239. newTexture.wrapU = this.wrapU;
  16240. newTexture.wrapV = this.wrapV;
  16241. newTexture.coordinatesIndex = this.coordinatesIndex;
  16242. newTexture.coordinatesMode = this.coordinatesMode;
  16243. // Texture
  16244. newTexture.uOffset = this.uOffset;
  16245. newTexture.vOffset = this.vOffset;
  16246. newTexture.uScale = this.uScale;
  16247. newTexture.vScale = this.vScale;
  16248. newTexture.uAng = this.uAng;
  16249. newTexture.vAng = this.vAng;
  16250. newTexture.wAng = this.wAng;
  16251. return newTexture;
  16252. };
  16253. // Statics
  16254. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16255. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16256. if (onLoad === void 0) { onLoad = null; }
  16257. if (onError === void 0) { onError = null; }
  16258. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16259. };
  16260. // Constants
  16261. Texture.NEAREST_SAMPLINGMODE = 1;
  16262. Texture.BILINEAR_SAMPLINGMODE = 2;
  16263. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16264. Texture.EXPLICIT_MODE = 0;
  16265. Texture.SPHERICAL_MODE = 1;
  16266. Texture.PLANAR_MODE = 2;
  16267. Texture.CUBIC_MODE = 3;
  16268. Texture.PROJECTION_MODE = 4;
  16269. Texture.SKYBOX_MODE = 5;
  16270. Texture.CLAMP_ADDRESSMODE = 0;
  16271. Texture.WRAP_ADDRESSMODE = 1;
  16272. Texture.MIRROR_ADDRESSMODE = 2;
  16273. return Texture;
  16274. })(BABYLON.BaseTexture);
  16275. BABYLON.Texture = Texture;
  16276. })(BABYLON || (BABYLON = {}));
  16277. //# sourceMappingURL=babylon.texture.js.map
  16278. var __extends = (this && this.__extends) || function (d, b) {
  16279. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16280. function __() { this.constructor = d; }
  16281. __.prototype = b.prototype;
  16282. d.prototype = new __();
  16283. };
  16284. var BABYLON;
  16285. (function (BABYLON) {
  16286. var CubeTexture = (function (_super) {
  16287. __extends(CubeTexture, _super);
  16288. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16289. _super.call(this, scene);
  16290. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16291. this.name = rootUrl;
  16292. this.url = rootUrl;
  16293. this._noMipmap = noMipmap;
  16294. this.hasAlpha = false;
  16295. this._texture = this._getFromCache(rootUrl, noMipmap);
  16296. if (!extensions) {
  16297. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16298. }
  16299. this._extensions = extensions;
  16300. if (!this._texture) {
  16301. if (!scene.useDelayedTextureLoading) {
  16302. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16303. }
  16304. else {
  16305. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16306. }
  16307. }
  16308. this.isCube = true;
  16309. this._textureMatrix = BABYLON.Matrix.Identity();
  16310. }
  16311. CubeTexture.prototype.clone = function () {
  16312. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16313. // Base texture
  16314. newTexture.level = this.level;
  16315. newTexture.wrapU = this.wrapU;
  16316. newTexture.wrapV = this.wrapV;
  16317. newTexture.coordinatesIndex = this.coordinatesIndex;
  16318. newTexture.coordinatesMode = this.coordinatesMode;
  16319. return newTexture;
  16320. };
  16321. // Methods
  16322. CubeTexture.prototype.delayLoad = function () {
  16323. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16324. return;
  16325. }
  16326. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16327. this._texture = this._getFromCache(this.url, this._noMipmap);
  16328. if (!this._texture) {
  16329. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16330. }
  16331. };
  16332. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16333. return this._textureMatrix;
  16334. };
  16335. return CubeTexture;
  16336. })(BABYLON.BaseTexture);
  16337. BABYLON.CubeTexture = CubeTexture;
  16338. })(BABYLON || (BABYLON = {}));
  16339. //# sourceMappingURL=babylon.cubeTexture.js.map
  16340. var __extends = (this && this.__extends) || function (d, b) {
  16341. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16342. function __() { this.constructor = d; }
  16343. __.prototype = b.prototype;
  16344. d.prototype = new __();
  16345. };
  16346. var BABYLON;
  16347. (function (BABYLON) {
  16348. var RenderTargetTexture = (function (_super) {
  16349. __extends(RenderTargetTexture, _super);
  16350. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16351. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16352. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16353. _super.call(this, null, scene, !generateMipMaps);
  16354. this.renderList = new Array();
  16355. this.renderParticles = true;
  16356. this.renderSprites = false;
  16357. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16358. this._currentRefreshId = -1;
  16359. this._refreshRate = 1;
  16360. this.name = name;
  16361. this.isRenderTarget = true;
  16362. this._size = size;
  16363. this._generateMipMaps = generateMipMaps;
  16364. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16365. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16366. // Rendering groups
  16367. this._renderingManager = new BABYLON.RenderingManager(scene);
  16368. }
  16369. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16370. this._currentRefreshId = -1;
  16371. };
  16372. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16373. get: function () {
  16374. return this._refreshRate;
  16375. },
  16376. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16377. set: function (value) {
  16378. this._refreshRate = value;
  16379. this.resetRefreshCounter();
  16380. },
  16381. enumerable: true,
  16382. configurable: true
  16383. });
  16384. RenderTargetTexture.prototype._shouldRender = function () {
  16385. if (this._currentRefreshId === -1) {
  16386. this._currentRefreshId = 1;
  16387. return true;
  16388. }
  16389. if (this.refreshRate === this._currentRefreshId) {
  16390. this._currentRefreshId = 1;
  16391. return true;
  16392. }
  16393. this._currentRefreshId++;
  16394. return false;
  16395. };
  16396. RenderTargetTexture.prototype.isReady = function () {
  16397. if (!this.getScene().renderTargetsEnabled) {
  16398. return false;
  16399. }
  16400. return _super.prototype.isReady.call(this);
  16401. };
  16402. RenderTargetTexture.prototype.getRenderSize = function () {
  16403. return this._size;
  16404. };
  16405. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16406. get: function () {
  16407. return true;
  16408. },
  16409. enumerable: true,
  16410. configurable: true
  16411. });
  16412. RenderTargetTexture.prototype.scale = function (ratio) {
  16413. var newSize = this._size * ratio;
  16414. this.resize(newSize, this._generateMipMaps);
  16415. };
  16416. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16417. this.releaseInternalTexture();
  16418. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16419. };
  16420. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16421. var scene = this.getScene();
  16422. var engine = scene.getEngine();
  16423. if (this._waitingRenderList) {
  16424. this.renderList = [];
  16425. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16426. var id = this._waitingRenderList[index];
  16427. this.renderList.push(scene.getMeshByID(id));
  16428. }
  16429. delete this._waitingRenderList;
  16430. }
  16431. if (this.renderList && this.renderList.length === 0) {
  16432. return;
  16433. }
  16434. // Bind
  16435. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16436. engine.bindFramebuffer(this._texture);
  16437. }
  16438. this._renderingManager.reset();
  16439. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16440. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16441. var mesh = currentRenderList[meshIndex];
  16442. if (mesh) {
  16443. if (!mesh.isReady()) {
  16444. // Reset _currentRefreshId
  16445. this.resetRefreshCounter();
  16446. continue;
  16447. }
  16448. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16449. mesh._activate(scene.getRenderId());
  16450. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16451. var subMesh = mesh.subMeshes[subIndex];
  16452. scene._activeIndices += subMesh.indexCount;
  16453. this._renderingManager.dispatch(subMesh);
  16454. }
  16455. }
  16456. }
  16457. }
  16458. if (this.onBeforeRender) {
  16459. this.onBeforeRender();
  16460. }
  16461. // Clear
  16462. if (this.onClear) {
  16463. this.onClear(engine);
  16464. }
  16465. else {
  16466. engine.clear(scene.clearColor, true, true);
  16467. }
  16468. if (!this._doNotChangeAspectRatio) {
  16469. scene.updateTransformMatrix(true);
  16470. }
  16471. // Render
  16472. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16473. if (useCameraPostProcess) {
  16474. scene.postProcessManager._finalizeFrame(false, this._texture);
  16475. }
  16476. if (!this._doNotChangeAspectRatio) {
  16477. scene.updateTransformMatrix(true);
  16478. }
  16479. if (this.onAfterRender) {
  16480. this.onAfterRender();
  16481. }
  16482. // Dump ?
  16483. if (dumpForDebug) {
  16484. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16485. }
  16486. // Unbind
  16487. engine.unBindFramebuffer(this._texture);
  16488. if (this.onAfterUnbind) {
  16489. this.onAfterUnbind();
  16490. }
  16491. };
  16492. RenderTargetTexture.prototype.clone = function () {
  16493. var textureSize = this.getSize();
  16494. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16495. // Base texture
  16496. newTexture.hasAlpha = this.hasAlpha;
  16497. newTexture.level = this.level;
  16498. // RenderTarget Texture
  16499. newTexture.coordinatesMode = this.coordinatesMode;
  16500. newTexture.renderList = this.renderList.slice(0);
  16501. return newTexture;
  16502. };
  16503. return RenderTargetTexture;
  16504. })(BABYLON.Texture);
  16505. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16506. })(BABYLON || (BABYLON = {}));
  16507. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16508. var __extends = (this && this.__extends) || function (d, b) {
  16509. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16510. function __() { this.constructor = d; }
  16511. __.prototype = b.prototype;
  16512. d.prototype = new __();
  16513. };
  16514. var BABYLON;
  16515. (function (BABYLON) {
  16516. var ProceduralTexture = (function (_super) {
  16517. __extends(ProceduralTexture, _super);
  16518. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16519. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16520. _super.call(this, null, scene, !generateMipMaps);
  16521. this._currentRefreshId = -1;
  16522. this._refreshRate = 1;
  16523. this._vertexDeclaration = [2];
  16524. this._vertexStrideSize = 2 * 4;
  16525. this._uniforms = new Array();
  16526. this._samplers = new Array();
  16527. this._textures = new Array();
  16528. this._floats = new Array();
  16529. this._floatsArrays = {};
  16530. this._colors3 = new Array();
  16531. this._colors4 = new Array();
  16532. this._vectors2 = new Array();
  16533. this._vectors3 = new Array();
  16534. this._matrices = new Array();
  16535. this._fallbackTextureUsed = false;
  16536. scene._proceduralTextures.push(this);
  16537. this.name = name;
  16538. this.isRenderTarget = true;
  16539. this._size = size;
  16540. this._generateMipMaps = generateMipMaps;
  16541. this.setFragment(fragment);
  16542. this._fallbackTexture = fallbackTexture;
  16543. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16544. // VBO
  16545. var vertices = [];
  16546. vertices.push(1, 1);
  16547. vertices.push(-1, 1);
  16548. vertices.push(-1, -1);
  16549. vertices.push(1, -1);
  16550. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16551. // Indices
  16552. var indices = [];
  16553. indices.push(0);
  16554. indices.push(1);
  16555. indices.push(2);
  16556. indices.push(0);
  16557. indices.push(2);
  16558. indices.push(3);
  16559. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16560. }
  16561. ProceduralTexture.prototype.reset = function () {
  16562. if (this._effect === undefined) {
  16563. return;
  16564. }
  16565. var engine = this.getScene().getEngine();
  16566. engine._releaseEffect(this._effect);
  16567. };
  16568. ProceduralTexture.prototype.isReady = function () {
  16569. var _this = this;
  16570. var engine = this.getScene().getEngine();
  16571. var shaders;
  16572. if (!this._fragment) {
  16573. return false;
  16574. }
  16575. if (this._fallbackTextureUsed) {
  16576. return true;
  16577. }
  16578. if (this._fragment.fragmentElement !== undefined) {
  16579. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16580. }
  16581. else {
  16582. shaders = { vertex: "procedural", fragment: this._fragment };
  16583. }
  16584. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16585. _this.releaseInternalTexture();
  16586. if (_this._fallbackTexture) {
  16587. _this._texture = _this._fallbackTexture._texture;
  16588. _this._texture.references++;
  16589. }
  16590. _this._fallbackTextureUsed = true;
  16591. });
  16592. return this._effect.isReady();
  16593. };
  16594. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16595. this._currentRefreshId = -1;
  16596. };
  16597. ProceduralTexture.prototype.setFragment = function (fragment) {
  16598. this._fragment = fragment;
  16599. };
  16600. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16601. get: function () {
  16602. return this._refreshRate;
  16603. },
  16604. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16605. set: function (value) {
  16606. this._refreshRate = value;
  16607. this.resetRefreshCounter();
  16608. },
  16609. enumerable: true,
  16610. configurable: true
  16611. });
  16612. ProceduralTexture.prototype._shouldRender = function () {
  16613. if (!this.isReady() || !this._texture) {
  16614. return false;
  16615. }
  16616. if (this._fallbackTextureUsed) {
  16617. return false;
  16618. }
  16619. if (this._currentRefreshId === -1) {
  16620. this._currentRefreshId = 1;
  16621. return true;
  16622. }
  16623. if (this.refreshRate === this._currentRefreshId) {
  16624. this._currentRefreshId = 1;
  16625. return true;
  16626. }
  16627. this._currentRefreshId++;
  16628. return false;
  16629. };
  16630. ProceduralTexture.prototype.getRenderSize = function () {
  16631. return this._size;
  16632. };
  16633. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16634. if (this._fallbackTextureUsed) {
  16635. return;
  16636. }
  16637. this.releaseInternalTexture();
  16638. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16639. };
  16640. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16641. if (this._uniforms.indexOf(uniformName) === -1) {
  16642. this._uniforms.push(uniformName);
  16643. }
  16644. };
  16645. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16646. if (this._samplers.indexOf(name) === -1) {
  16647. this._samplers.push(name);
  16648. }
  16649. this._textures[name] = texture;
  16650. return this;
  16651. };
  16652. ProceduralTexture.prototype.setFloat = function (name, value) {
  16653. this._checkUniform(name);
  16654. this._floats[name] = value;
  16655. return this;
  16656. };
  16657. ProceduralTexture.prototype.setFloats = function (name, value) {
  16658. this._checkUniform(name);
  16659. this._floatsArrays[name] = value;
  16660. return this;
  16661. };
  16662. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16663. this._checkUniform(name);
  16664. this._colors3[name] = value;
  16665. return this;
  16666. };
  16667. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16668. this._checkUniform(name);
  16669. this._colors4[name] = value;
  16670. return this;
  16671. };
  16672. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16673. this._checkUniform(name);
  16674. this._vectors2[name] = value;
  16675. return this;
  16676. };
  16677. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16678. this._checkUniform(name);
  16679. this._vectors3[name] = value;
  16680. return this;
  16681. };
  16682. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16683. this._checkUniform(name);
  16684. this._matrices[name] = value;
  16685. return this;
  16686. };
  16687. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16688. var scene = this.getScene();
  16689. var engine = scene.getEngine();
  16690. engine.bindFramebuffer(this._texture);
  16691. // Clear
  16692. engine.clear(scene.clearColor, true, true);
  16693. // Render
  16694. engine.enableEffect(this._effect);
  16695. engine.setState(false);
  16696. // Texture
  16697. for (var name in this._textures) {
  16698. this._effect.setTexture(name, this._textures[name]);
  16699. }
  16700. // Float
  16701. for (name in this._floats) {
  16702. this._effect.setFloat(name, this._floats[name]);
  16703. }
  16704. // Floats
  16705. for (name in this._floatsArrays) {
  16706. this._effect.setArray(name, this._floatsArrays[name]);
  16707. }
  16708. // Color3
  16709. for (name in this._colors3) {
  16710. this._effect.setColor3(name, this._colors3[name]);
  16711. }
  16712. // Color4
  16713. for (name in this._colors4) {
  16714. var color = this._colors4[name];
  16715. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16716. }
  16717. // Vector2
  16718. for (name in this._vectors2) {
  16719. this._effect.setVector2(name, this._vectors2[name]);
  16720. }
  16721. // Vector3
  16722. for (name in this._vectors3) {
  16723. this._effect.setVector3(name, this._vectors3[name]);
  16724. }
  16725. // Matrix
  16726. for (name in this._matrices) {
  16727. this._effect.setMatrix(name, this._matrices[name]);
  16728. }
  16729. // VBOs
  16730. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16731. // Draw order
  16732. engine.draw(true, 0, 6);
  16733. // Unbind
  16734. engine.unBindFramebuffer(this._texture);
  16735. };
  16736. ProceduralTexture.prototype.clone = function () {
  16737. var textureSize = this.getSize();
  16738. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16739. // Base texture
  16740. newTexture.hasAlpha = this.hasAlpha;
  16741. newTexture.level = this.level;
  16742. // RenderTarget Texture
  16743. newTexture.coordinatesMode = this.coordinatesMode;
  16744. return newTexture;
  16745. };
  16746. ProceduralTexture.prototype.dispose = function () {
  16747. var index = this.getScene()._proceduralTextures.indexOf(this);
  16748. if (index >= 0) {
  16749. this.getScene()._proceduralTextures.splice(index, 1);
  16750. }
  16751. _super.prototype.dispose.call(this);
  16752. };
  16753. return ProceduralTexture;
  16754. })(BABYLON.Texture);
  16755. BABYLON.ProceduralTexture = ProceduralTexture;
  16756. })(BABYLON || (BABYLON = {}));
  16757. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16758. var __extends = (this && this.__extends) || function (d, b) {
  16759. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16760. function __() { this.constructor = d; }
  16761. __.prototype = b.prototype;
  16762. d.prototype = new __();
  16763. };
  16764. var BABYLON;
  16765. (function (BABYLON) {
  16766. var MirrorTexture = (function (_super) {
  16767. __extends(MirrorTexture, _super);
  16768. function MirrorTexture(name, size, scene, generateMipMaps) {
  16769. var _this = this;
  16770. _super.call(this, name, size, scene, generateMipMaps, true);
  16771. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16772. this._transformMatrix = BABYLON.Matrix.Zero();
  16773. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16774. this.onBeforeRender = function () {
  16775. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16776. _this._savedViewMatrix = scene.getViewMatrix();
  16777. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16778. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16779. scene.clipPlane = _this.mirrorPlane;
  16780. scene.getEngine().cullBackFaces = false;
  16781. };
  16782. this.onAfterRender = function () {
  16783. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16784. scene.getEngine().cullBackFaces = true;
  16785. delete scene.clipPlane;
  16786. };
  16787. }
  16788. MirrorTexture.prototype.clone = function () {
  16789. var textureSize = this.getSize();
  16790. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16791. // Base texture
  16792. newTexture.hasAlpha = this.hasAlpha;
  16793. newTexture.level = this.level;
  16794. // Mirror Texture
  16795. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16796. newTexture.renderList = this.renderList.slice(0);
  16797. return newTexture;
  16798. };
  16799. return MirrorTexture;
  16800. })(BABYLON.RenderTargetTexture);
  16801. BABYLON.MirrorTexture = MirrorTexture;
  16802. })(BABYLON || (BABYLON = {}));
  16803. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16804. var __extends = (this && this.__extends) || function (d, b) {
  16805. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16806. function __() { this.constructor = d; }
  16807. __.prototype = b.prototype;
  16808. d.prototype = new __();
  16809. };
  16810. var BABYLON;
  16811. (function (BABYLON) {
  16812. var DynamicTexture = (function (_super) {
  16813. __extends(DynamicTexture, _super);
  16814. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16816. _super.call(this, null, scene, !generateMipMaps);
  16817. this.name = name;
  16818. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16819. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16820. this._generateMipMaps = generateMipMaps;
  16821. if (options.getContext) {
  16822. this._canvas = options;
  16823. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16824. }
  16825. else {
  16826. this._canvas = document.createElement("canvas");
  16827. if (options.width) {
  16828. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16829. }
  16830. else {
  16831. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16832. }
  16833. }
  16834. var textureSize = this.getSize();
  16835. this._canvas.width = textureSize.width;
  16836. this._canvas.height = textureSize.height;
  16837. this._context = this._canvas.getContext("2d");
  16838. }
  16839. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16840. get: function () {
  16841. return true;
  16842. },
  16843. enumerable: true,
  16844. configurable: true
  16845. });
  16846. DynamicTexture.prototype.scale = function (ratio) {
  16847. var textureSize = this.getSize();
  16848. textureSize.width *= ratio;
  16849. textureSize.height *= ratio;
  16850. this._canvas.width = textureSize.width;
  16851. this._canvas.height = textureSize.height;
  16852. this.releaseInternalTexture();
  16853. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16854. };
  16855. DynamicTexture.prototype.getContext = function () {
  16856. return this._context;
  16857. };
  16858. DynamicTexture.prototype.clear = function () {
  16859. var size = this.getSize();
  16860. this._context.fillRect(0, 0, size.width, size.height);
  16861. };
  16862. DynamicTexture.prototype.update = function (invertY) {
  16863. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16864. };
  16865. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16866. if (update === void 0) { update = true; }
  16867. var size = this.getSize();
  16868. if (clearColor) {
  16869. this._context.fillStyle = clearColor;
  16870. this._context.fillRect(0, 0, size.width, size.height);
  16871. }
  16872. this._context.font = font;
  16873. if (x === null) {
  16874. var textSize = this._context.measureText(text);
  16875. x = (size.width - textSize.width) / 2;
  16876. }
  16877. this._context.fillStyle = color;
  16878. this._context.fillText(text, x, y);
  16879. if (update) {
  16880. this.update(invertY);
  16881. }
  16882. };
  16883. DynamicTexture.prototype.clone = function () {
  16884. var textureSize = this.getSize();
  16885. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16886. // Base texture
  16887. newTexture.hasAlpha = this.hasAlpha;
  16888. newTexture.level = this.level;
  16889. // Dynamic Texture
  16890. newTexture.wrapU = this.wrapU;
  16891. newTexture.wrapV = this.wrapV;
  16892. return newTexture;
  16893. };
  16894. return DynamicTexture;
  16895. })(BABYLON.Texture);
  16896. BABYLON.DynamicTexture = DynamicTexture;
  16897. })(BABYLON || (BABYLON = {}));
  16898. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16899. var __extends = (this && this.__extends) || function (d, b) {
  16900. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16901. function __() { this.constructor = d; }
  16902. __.prototype = b.prototype;
  16903. d.prototype = new __();
  16904. };
  16905. var BABYLON;
  16906. (function (BABYLON) {
  16907. var VideoTexture = (function (_super) {
  16908. __extends(VideoTexture, _super);
  16909. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16910. var _this = this;
  16911. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16912. if (invertY === void 0) { invertY = false; }
  16913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16914. _super.call(this, null, scene, !generateMipMaps, invertY);
  16915. this._autoLaunch = true;
  16916. this.name = name;
  16917. this.video = document.createElement("video");
  16918. this.video.autoplay = false;
  16919. this.video.loop = true;
  16920. this.video.addEventListener("canplaythrough", function () {
  16921. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16922. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16923. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16924. }
  16925. else {
  16926. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16927. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16928. generateMipMaps = false;
  16929. }
  16930. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16931. _this._texture.isReady = true;
  16932. });
  16933. urls.forEach(function (url) {
  16934. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16935. var source = document.createElement("source");
  16936. source.src = url;
  16937. _this.video.appendChild(source);
  16938. });
  16939. this._lastUpdate = BABYLON.Tools.Now;
  16940. }
  16941. VideoTexture.prototype.update = function () {
  16942. if (this._autoLaunch) {
  16943. this._autoLaunch = false;
  16944. this.video.play();
  16945. }
  16946. var now = BABYLON.Tools.Now;
  16947. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16948. return false;
  16949. }
  16950. this._lastUpdate = now;
  16951. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16952. return true;
  16953. };
  16954. return VideoTexture;
  16955. })(BABYLON.Texture);
  16956. BABYLON.VideoTexture = VideoTexture;
  16957. })(BABYLON || (BABYLON = {}));
  16958. //# sourceMappingURL=babylon.videoTexture.js.map
  16959. var __extends = (this && this.__extends) || function (d, b) {
  16960. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16961. function __() { this.constructor = d; }
  16962. __.prototype = b.prototype;
  16963. d.prototype = new __();
  16964. };
  16965. var BABYLON;
  16966. (function (BABYLON) {
  16967. var CustomProceduralTexture = (function (_super) {
  16968. __extends(CustomProceduralTexture, _super);
  16969. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16970. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16971. this._animate = true;
  16972. this._time = 0;
  16973. this._texturePath = texturePath;
  16974. //Try to load json
  16975. this.loadJson(texturePath);
  16976. this.refreshRate = 1;
  16977. }
  16978. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16979. var _this = this;
  16980. var that = this;
  16981. function noConfigFile() {
  16982. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16983. try {
  16984. that.setFragment(that._texturePath);
  16985. }
  16986. catch (ex) {
  16987. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16988. }
  16989. }
  16990. var configFileUrl = jsonUrl + "/config.json";
  16991. var xhr = new XMLHttpRequest();
  16992. xhr.open("GET", configFileUrl, true);
  16993. xhr.addEventListener("load", function () {
  16994. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16995. try {
  16996. _this._config = JSON.parse(xhr.response);
  16997. _this.updateShaderUniforms();
  16998. _this.updateTextures();
  16999. _this.setFragment(_this._texturePath + "/custom");
  17000. _this._animate = _this._config.animate;
  17001. _this.refreshRate = _this._config.refreshrate;
  17002. }
  17003. catch (ex) {
  17004. noConfigFile();
  17005. }
  17006. }
  17007. else {
  17008. noConfigFile();
  17009. }
  17010. }, false);
  17011. xhr.addEventListener("error", function () {
  17012. noConfigFile();
  17013. }, false);
  17014. try {
  17015. xhr.send();
  17016. }
  17017. catch (ex) {
  17018. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17019. }
  17020. };
  17021. CustomProceduralTexture.prototype.isReady = function () {
  17022. if (!_super.prototype.isReady.call(this)) {
  17023. return false;
  17024. }
  17025. for (var name in this._textures) {
  17026. var texture = this._textures[name];
  17027. if (!texture.isReady()) {
  17028. return false;
  17029. }
  17030. }
  17031. return true;
  17032. };
  17033. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17034. if (this._animate) {
  17035. this._time += this.getScene().getAnimationRatio() * 0.03;
  17036. this.updateShaderUniforms();
  17037. }
  17038. _super.prototype.render.call(this, useCameraPostProcess);
  17039. };
  17040. CustomProceduralTexture.prototype.updateTextures = function () {
  17041. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17042. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17043. }
  17044. };
  17045. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17046. if (this._config) {
  17047. for (var j = 0; j < this._config.uniforms.length; j++) {
  17048. var uniform = this._config.uniforms[j];
  17049. switch (uniform.type) {
  17050. case "float":
  17051. this.setFloat(uniform.name, uniform.value);
  17052. break;
  17053. case "color3":
  17054. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17055. break;
  17056. case "color4":
  17057. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17058. break;
  17059. case "vector2":
  17060. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17061. break;
  17062. case "vector3":
  17063. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17064. break;
  17065. }
  17066. }
  17067. }
  17068. this.setFloat("time", this._time);
  17069. };
  17070. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17071. get: function () {
  17072. return this._animate;
  17073. },
  17074. set: function (value) {
  17075. this._animate = value;
  17076. },
  17077. enumerable: true,
  17078. configurable: true
  17079. });
  17080. return CustomProceduralTexture;
  17081. })(BABYLON.ProceduralTexture);
  17082. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17083. })(BABYLON || (BABYLON = {}));
  17084. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  17085. var __extends = (this && this.__extends) || function (d, b) {
  17086. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17087. function __() { this.constructor = d; }
  17088. __.prototype = b.prototype;
  17089. d.prototype = new __();
  17090. };
  17091. var BABYLON;
  17092. (function (BABYLON) {
  17093. var WoodProceduralTexture = (function (_super) {
  17094. __extends(WoodProceduralTexture, _super);
  17095. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17096. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17097. this._ampScale = 100.0;
  17098. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17099. this.updateShaderUniforms();
  17100. this.refreshRate = 0;
  17101. }
  17102. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17103. this.setFloat("ampScale", this._ampScale);
  17104. this.setColor3("woodColor", this._woodColor);
  17105. };
  17106. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17107. get: function () {
  17108. return this._ampScale;
  17109. },
  17110. set: function (value) {
  17111. this._ampScale = value;
  17112. this.updateShaderUniforms();
  17113. },
  17114. enumerable: true,
  17115. configurable: true
  17116. });
  17117. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17118. get: function () {
  17119. return this._woodColor;
  17120. },
  17121. set: function (value) {
  17122. this._woodColor = value;
  17123. this.updateShaderUniforms();
  17124. },
  17125. enumerable: true,
  17126. configurable: true
  17127. });
  17128. return WoodProceduralTexture;
  17129. })(BABYLON.ProceduralTexture);
  17130. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17131. var FireProceduralTexture = (function (_super) {
  17132. __extends(FireProceduralTexture, _super);
  17133. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17134. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17135. this._time = 0.0;
  17136. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17137. this._autoGenerateTime = true;
  17138. this._alphaThreshold = 0.5;
  17139. this._fireColors = FireProceduralTexture.RedFireColors;
  17140. this.updateShaderUniforms();
  17141. this.refreshRate = 1;
  17142. }
  17143. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17144. this.setFloat("time", this._time);
  17145. this.setVector2("speed", this._speed);
  17146. this.setColor3("c1", this._fireColors[0]);
  17147. this.setColor3("c2", this._fireColors[1]);
  17148. this.setColor3("c3", this._fireColors[2]);
  17149. this.setColor3("c4", this._fireColors[3]);
  17150. this.setColor3("c5", this._fireColors[4]);
  17151. this.setColor3("c6", this._fireColors[5]);
  17152. this.setFloat("alphaThreshold", this._alphaThreshold);
  17153. };
  17154. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17155. if (this._autoGenerateTime) {
  17156. this._time += this.getScene().getAnimationRatio() * 0.03;
  17157. this.updateShaderUniforms();
  17158. }
  17159. _super.prototype.render.call(this, useCameraPostProcess);
  17160. };
  17161. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17162. get: function () {
  17163. return [
  17164. new BABYLON.Color3(0.5, 0.0, 1.0),
  17165. new BABYLON.Color3(0.9, 0.0, 1.0),
  17166. new BABYLON.Color3(0.2, 0.0, 1.0),
  17167. new BABYLON.Color3(1.0, 0.9, 1.0),
  17168. new BABYLON.Color3(0.1, 0.1, 1.0),
  17169. new BABYLON.Color3(0.9, 0.9, 1.0)
  17170. ];
  17171. },
  17172. enumerable: true,
  17173. configurable: true
  17174. });
  17175. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17176. get: function () {
  17177. return [
  17178. new BABYLON.Color3(0.5, 1.0, 0.0),
  17179. new BABYLON.Color3(0.5, 1.0, 0.0),
  17180. new BABYLON.Color3(0.3, 0.4, 0.0),
  17181. new BABYLON.Color3(0.5, 1.0, 0.0),
  17182. new BABYLON.Color3(0.2, 0.0, 0.0),
  17183. new BABYLON.Color3(0.5, 1.0, 0.0)
  17184. ];
  17185. },
  17186. enumerable: true,
  17187. configurable: true
  17188. });
  17189. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17190. get: function () {
  17191. return [
  17192. new BABYLON.Color3(0.5, 0.0, 0.1),
  17193. new BABYLON.Color3(0.9, 0.0, 0.0),
  17194. new BABYLON.Color3(0.2, 0.0, 0.0),
  17195. new BABYLON.Color3(1.0, 0.9, 0.0),
  17196. new BABYLON.Color3(0.1, 0.1, 0.1),
  17197. new BABYLON.Color3(0.9, 0.9, 0.9)
  17198. ];
  17199. },
  17200. enumerable: true,
  17201. configurable: true
  17202. });
  17203. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17204. get: function () {
  17205. return [
  17206. new BABYLON.Color3(0.1, 0.0, 0.5),
  17207. new BABYLON.Color3(0.0, 0.0, 0.5),
  17208. new BABYLON.Color3(0.1, 0.0, 0.2),
  17209. new BABYLON.Color3(0.0, 0.0, 1.0),
  17210. new BABYLON.Color3(0.1, 0.2, 0.3),
  17211. new BABYLON.Color3(0.0, 0.2, 0.9)
  17212. ];
  17213. },
  17214. enumerable: true,
  17215. configurable: true
  17216. });
  17217. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17218. get: function () {
  17219. return this._fireColors;
  17220. },
  17221. set: function (value) {
  17222. this._fireColors = value;
  17223. this.updateShaderUniforms();
  17224. },
  17225. enumerable: true,
  17226. configurable: true
  17227. });
  17228. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17229. get: function () {
  17230. return this._time;
  17231. },
  17232. set: function (value) {
  17233. this._time = value;
  17234. this.updateShaderUniforms();
  17235. },
  17236. enumerable: true,
  17237. configurable: true
  17238. });
  17239. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17240. get: function () {
  17241. return this._speed;
  17242. },
  17243. set: function (value) {
  17244. this._speed = value;
  17245. this.updateShaderUniforms();
  17246. },
  17247. enumerable: true,
  17248. configurable: true
  17249. });
  17250. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17251. get: function () {
  17252. return this._alphaThreshold;
  17253. },
  17254. set: function (value) {
  17255. this._alphaThreshold = value;
  17256. this.updateShaderUniforms();
  17257. },
  17258. enumerable: true,
  17259. configurable: true
  17260. });
  17261. return FireProceduralTexture;
  17262. })(BABYLON.ProceduralTexture);
  17263. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17264. var CloudProceduralTexture = (function (_super) {
  17265. __extends(CloudProceduralTexture, _super);
  17266. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17267. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17268. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17269. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17270. this.updateShaderUniforms();
  17271. this.refreshRate = 0;
  17272. }
  17273. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17274. this.setColor3("skyColor", this._skyColor);
  17275. this.setColor3("cloudColor", this._cloudColor);
  17276. };
  17277. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17278. get: function () {
  17279. return this._skyColor;
  17280. },
  17281. set: function (value) {
  17282. this._skyColor = value;
  17283. this.updateShaderUniforms();
  17284. },
  17285. enumerable: true,
  17286. configurable: true
  17287. });
  17288. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17289. get: function () {
  17290. return this._cloudColor;
  17291. },
  17292. set: function (value) {
  17293. this._cloudColor = value;
  17294. this.updateShaderUniforms();
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. return CloudProceduralTexture;
  17300. })(BABYLON.ProceduralTexture);
  17301. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17302. var GrassProceduralTexture = (function (_super) {
  17303. __extends(GrassProceduralTexture, _super);
  17304. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17305. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17306. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17307. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17308. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17309. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17310. this._grassColors = [
  17311. new BABYLON.Color3(0.29, 0.38, 0.02),
  17312. new BABYLON.Color3(0.36, 0.49, 0.09),
  17313. new BABYLON.Color3(0.51, 0.6, 0.28)
  17314. ];
  17315. this.updateShaderUniforms();
  17316. this.refreshRate = 0;
  17317. }
  17318. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17319. this.setColor3("herb1Color", this._grassColors[0]);
  17320. this.setColor3("herb2Color", this._grassColors[1]);
  17321. this.setColor3("herb3Color", this._grassColors[2]);
  17322. this.setColor3("groundColor", this._groundColor);
  17323. };
  17324. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17325. get: function () {
  17326. return this._grassColors;
  17327. },
  17328. set: function (value) {
  17329. this._grassColors = value;
  17330. this.updateShaderUniforms();
  17331. },
  17332. enumerable: true,
  17333. configurable: true
  17334. });
  17335. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17336. get: function () {
  17337. return this._groundColor;
  17338. },
  17339. set: function (value) {
  17340. this.groundColor = value;
  17341. this.updateShaderUniforms();
  17342. },
  17343. enumerable: true,
  17344. configurable: true
  17345. });
  17346. return GrassProceduralTexture;
  17347. })(BABYLON.ProceduralTexture);
  17348. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17349. var RoadProceduralTexture = (function (_super) {
  17350. __extends(RoadProceduralTexture, _super);
  17351. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17352. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17353. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17354. this.updateShaderUniforms();
  17355. this.refreshRate = 0;
  17356. }
  17357. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17358. this.setColor3("roadColor", this._roadColor);
  17359. };
  17360. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17361. get: function () {
  17362. return this._roadColor;
  17363. },
  17364. set: function (value) {
  17365. this._roadColor = value;
  17366. this.updateShaderUniforms();
  17367. },
  17368. enumerable: true,
  17369. configurable: true
  17370. });
  17371. return RoadProceduralTexture;
  17372. })(BABYLON.ProceduralTexture);
  17373. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17374. var BrickProceduralTexture = (function (_super) {
  17375. __extends(BrickProceduralTexture, _super);
  17376. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17377. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17378. this._numberOfBricksHeight = 15;
  17379. this._numberOfBricksWidth = 5;
  17380. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17381. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17382. this.updateShaderUniforms();
  17383. this.refreshRate = 0;
  17384. }
  17385. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17386. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17387. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17388. this.setColor3("brickColor", this._brickColor);
  17389. this.setColor3("jointColor", this._jointColor);
  17390. };
  17391. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17392. get: function () {
  17393. return this._numberOfBricksHeight;
  17394. },
  17395. set: function (value) {
  17396. this._numberOfBricksHeight = value;
  17397. this.updateShaderUniforms();
  17398. },
  17399. enumerable: true,
  17400. configurable: true
  17401. });
  17402. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17403. get: function () {
  17404. return this._numberOfBricksWidth;
  17405. },
  17406. set: function (value) {
  17407. this._numberOfBricksHeight = value;
  17408. this.updateShaderUniforms();
  17409. },
  17410. enumerable: true,
  17411. configurable: true
  17412. });
  17413. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17414. get: function () {
  17415. return this._jointColor;
  17416. },
  17417. set: function (value) {
  17418. this._jointColor = value;
  17419. this.updateShaderUniforms();
  17420. },
  17421. enumerable: true,
  17422. configurable: true
  17423. });
  17424. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17425. get: function () {
  17426. return this._brickColor;
  17427. },
  17428. set: function (value) {
  17429. this._brickColor = value;
  17430. this.updateShaderUniforms();
  17431. },
  17432. enumerable: true,
  17433. configurable: true
  17434. });
  17435. return BrickProceduralTexture;
  17436. })(BABYLON.ProceduralTexture);
  17437. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17438. var MarbleProceduralTexture = (function (_super) {
  17439. __extends(MarbleProceduralTexture, _super);
  17440. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17441. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17442. this._numberOfTilesHeight = 3;
  17443. this._numberOfTilesWidth = 3;
  17444. this._amplitude = 9.0;
  17445. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17446. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17447. this.updateShaderUniforms();
  17448. this.refreshRate = 0;
  17449. }
  17450. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17451. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17452. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17453. this.setFloat("amplitude", this._amplitude);
  17454. this.setColor3("marbleColor", this._marbleColor);
  17455. this.setColor3("jointColor", this._jointColor);
  17456. };
  17457. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17458. get: function () {
  17459. return this._numberOfTilesHeight;
  17460. },
  17461. set: function (value) {
  17462. this._numberOfTilesHeight = value;
  17463. this.updateShaderUniforms();
  17464. },
  17465. enumerable: true,
  17466. configurable: true
  17467. });
  17468. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17469. get: function () {
  17470. return this._numberOfTilesWidth;
  17471. },
  17472. set: function (value) {
  17473. this._numberOfTilesWidth = value;
  17474. this.updateShaderUniforms();
  17475. },
  17476. enumerable: true,
  17477. configurable: true
  17478. });
  17479. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17480. get: function () {
  17481. return this._jointColor;
  17482. },
  17483. set: function (value) {
  17484. this._jointColor = value;
  17485. this.updateShaderUniforms();
  17486. },
  17487. enumerable: true,
  17488. configurable: true
  17489. });
  17490. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17491. get: function () {
  17492. return this._marbleColor;
  17493. },
  17494. set: function (value) {
  17495. this._marbleColor = value;
  17496. this.updateShaderUniforms();
  17497. },
  17498. enumerable: true,
  17499. configurable: true
  17500. });
  17501. return MarbleProceduralTexture;
  17502. })(BABYLON.ProceduralTexture);
  17503. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17504. })(BABYLON || (BABYLON = {}));
  17505. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17506. var BABYLON;
  17507. (function (BABYLON) {
  17508. var EffectFallbacks = (function () {
  17509. function EffectFallbacks() {
  17510. this._defines = {};
  17511. this._currentRank = 32;
  17512. this._maxRank = -1;
  17513. }
  17514. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17515. if (!this._defines[rank]) {
  17516. if (rank < this._currentRank) {
  17517. this._currentRank = rank;
  17518. }
  17519. if (rank > this._maxRank) {
  17520. this._maxRank = rank;
  17521. }
  17522. this._defines[rank] = new Array();
  17523. }
  17524. this._defines[rank].push(define);
  17525. };
  17526. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17527. get: function () {
  17528. return this._currentRank <= this._maxRank;
  17529. },
  17530. enumerable: true,
  17531. configurable: true
  17532. });
  17533. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17534. var currentFallbacks = this._defines[this._currentRank];
  17535. for (var index = 0; index < currentFallbacks.length; index++) {
  17536. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17537. }
  17538. this._currentRank++;
  17539. return currentDefines;
  17540. };
  17541. return EffectFallbacks;
  17542. })();
  17543. BABYLON.EffectFallbacks = EffectFallbacks;
  17544. var Effect = (function () {
  17545. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17546. var _this = this;
  17547. this._isReady = false;
  17548. this._compilationError = "";
  17549. this._valueCache = [];
  17550. this._engine = engine;
  17551. this.name = baseName;
  17552. this.defines = defines;
  17553. this._uniformsNames = uniformsNames.concat(samplers);
  17554. this._samplers = samplers;
  17555. this._attributesNames = attributesNames;
  17556. this.onError = onError;
  17557. this.onCompiled = onCompiled;
  17558. var vertexSource;
  17559. var fragmentSource;
  17560. if (baseName.vertexElement) {
  17561. vertexSource = document.getElementById(baseName.vertexElement);
  17562. if (!vertexSource) {
  17563. vertexSource = baseName.vertexElement;
  17564. }
  17565. }
  17566. else {
  17567. vertexSource = baseName.vertex || baseName;
  17568. }
  17569. if (baseName.fragmentElement) {
  17570. fragmentSource = document.getElementById(baseName.fragmentElement);
  17571. if (!fragmentSource) {
  17572. fragmentSource = baseName.fragmentElement;
  17573. }
  17574. }
  17575. else {
  17576. fragmentSource = baseName.fragment || baseName;
  17577. }
  17578. this._loadVertexShader(vertexSource, function (vertexCode) {
  17579. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17580. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17581. });
  17582. });
  17583. }
  17584. // Properties
  17585. Effect.prototype.isReady = function () {
  17586. return this._isReady;
  17587. };
  17588. Effect.prototype.getProgram = function () {
  17589. return this._program;
  17590. };
  17591. Effect.prototype.getAttributesNames = function () {
  17592. return this._attributesNames;
  17593. };
  17594. Effect.prototype.getAttributeLocation = function (index) {
  17595. return this._attributes[index];
  17596. };
  17597. Effect.prototype.getAttributeLocationByName = function (name) {
  17598. var index = this._attributesNames.indexOf(name);
  17599. return this._attributes[index];
  17600. };
  17601. Effect.prototype.getAttributesCount = function () {
  17602. return this._attributes.length;
  17603. };
  17604. Effect.prototype.getUniformIndex = function (uniformName) {
  17605. return this._uniformsNames.indexOf(uniformName);
  17606. };
  17607. Effect.prototype.getUniform = function (uniformName) {
  17608. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17609. };
  17610. Effect.prototype.getSamplers = function () {
  17611. return this._samplers;
  17612. };
  17613. Effect.prototype.getCompilationError = function () {
  17614. return this._compilationError;
  17615. };
  17616. // Methods
  17617. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17618. // DOM element ?
  17619. if (vertex instanceof HTMLElement) {
  17620. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17621. callback(vertexCode);
  17622. return;
  17623. }
  17624. // Is in local store ?
  17625. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17626. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17627. return;
  17628. }
  17629. var vertexShaderUrl;
  17630. if (vertex[0] === ".") {
  17631. vertexShaderUrl = vertex;
  17632. }
  17633. else {
  17634. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17635. }
  17636. // Vertex shader
  17637. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17638. };
  17639. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17640. // DOM element ?
  17641. if (fragment instanceof HTMLElement) {
  17642. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17643. callback(fragmentCode);
  17644. return;
  17645. }
  17646. // Is in local store ?
  17647. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17648. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17649. return;
  17650. }
  17651. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17652. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17653. return;
  17654. }
  17655. var fragmentShaderUrl;
  17656. if (fragment[0] === ".") {
  17657. fragmentShaderUrl = fragment;
  17658. }
  17659. else {
  17660. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17661. }
  17662. // Fragment shader
  17663. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17664. };
  17665. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17666. try {
  17667. var engine = this._engine;
  17668. if (!engine.getCaps().highPrecisionShaderSupported) {
  17669. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17670. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17671. }
  17672. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17673. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17674. this._attributes = engine.getAttributes(this._program, attributesNames);
  17675. for (var index = 0; index < this._samplers.length; index++) {
  17676. var sampler = this.getUniform(this._samplers[index]);
  17677. if (sampler == null) {
  17678. this._samplers.splice(index, 1);
  17679. index--;
  17680. }
  17681. }
  17682. engine.bindSamplers(this);
  17683. this._isReady = true;
  17684. if (this.onCompiled) {
  17685. this.onCompiled(this);
  17686. }
  17687. }
  17688. catch (e) {
  17689. // Is it a problem with precision?
  17690. if (e.message.indexOf("highp") !== -1) {
  17691. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17692. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17693. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17694. return;
  17695. }
  17696. // Let's go through fallbacks then
  17697. if (fallbacks && fallbacks.isMoreFallbacks) {
  17698. defines = fallbacks.reduce(defines);
  17699. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17700. }
  17701. else {
  17702. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  17703. BABYLON.Tools.Error("Defines: " + defines);
  17704. BABYLON.Tools.Error("Error: " + e.message);
  17705. this._compilationError = e.message;
  17706. if (this.onError) {
  17707. this.onError(this, this._compilationError);
  17708. }
  17709. }
  17710. }
  17711. };
  17712. Effect.prototype._bindTexture = function (channel, texture) {
  17713. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17714. };
  17715. Effect.prototype.setTexture = function (channel, texture) {
  17716. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17717. };
  17718. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17719. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17720. };
  17721. //public _cacheMatrix(uniformName, matrix) {
  17722. // if (!this._valueCache[uniformName]) {
  17723. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17724. // }
  17725. // for (var index = 0; index < 16; index++) {
  17726. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17727. // }
  17728. //};
  17729. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17730. if (!this._valueCache[uniformName]) {
  17731. this._valueCache[uniformName] = [x, y];
  17732. return;
  17733. }
  17734. this._valueCache[uniformName][0] = x;
  17735. this._valueCache[uniformName][1] = y;
  17736. };
  17737. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17738. if (!this._valueCache[uniformName]) {
  17739. this._valueCache[uniformName] = [x, y, z];
  17740. return;
  17741. }
  17742. this._valueCache[uniformName][0] = x;
  17743. this._valueCache[uniformName][1] = y;
  17744. this._valueCache[uniformName][2] = z;
  17745. };
  17746. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17747. if (!this._valueCache[uniformName]) {
  17748. this._valueCache[uniformName] = [x, y, z, w];
  17749. return;
  17750. }
  17751. this._valueCache[uniformName][0] = x;
  17752. this._valueCache[uniformName][1] = y;
  17753. this._valueCache[uniformName][2] = z;
  17754. this._valueCache[uniformName][3] = w;
  17755. };
  17756. Effect.prototype.setArray = function (uniformName, array) {
  17757. this._engine.setArray(this.getUniform(uniformName), array);
  17758. return this;
  17759. };
  17760. Effect.prototype.setArray2 = function (uniformName, array) {
  17761. this._engine.setArray2(this.getUniform(uniformName), array);
  17762. return this;
  17763. };
  17764. Effect.prototype.setArray3 = function (uniformName, array) {
  17765. this._engine.setArray3(this.getUniform(uniformName), array);
  17766. return this;
  17767. };
  17768. Effect.prototype.setArray4 = function (uniformName, array) {
  17769. this._engine.setArray4(this.getUniform(uniformName), array);
  17770. return this;
  17771. };
  17772. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17773. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17774. return this;
  17775. };
  17776. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17777. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17778. // return;
  17779. //this._cacheMatrix(uniformName, matrix);
  17780. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17781. return this;
  17782. };
  17783. Effect.prototype.setFloat = function (uniformName, value) {
  17784. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17785. return this;
  17786. this._valueCache[uniformName] = value;
  17787. this._engine.setFloat(this.getUniform(uniformName), value);
  17788. return this;
  17789. };
  17790. Effect.prototype.setBool = function (uniformName, bool) {
  17791. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17792. return this;
  17793. this._valueCache[uniformName] = bool;
  17794. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17795. return this;
  17796. };
  17797. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17798. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17799. return this;
  17800. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17801. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17802. return this;
  17803. };
  17804. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17805. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17806. return this;
  17807. this._cacheFloat2(uniformName, x, y);
  17808. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17809. return this;
  17810. };
  17811. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17812. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17813. return this;
  17814. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17815. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17816. return this;
  17817. };
  17818. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17819. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17820. return this;
  17821. this._cacheFloat3(uniformName, x, y, z);
  17822. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17823. return this;
  17824. };
  17825. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17826. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17827. return this;
  17828. this._cacheFloat4(uniformName, x, y, z, w);
  17829. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17830. return this;
  17831. };
  17832. Effect.prototype.setColor3 = function (uniformName, color3) {
  17833. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17834. return this;
  17835. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17836. this._engine.setColor3(this.getUniform(uniformName), color3);
  17837. return this;
  17838. };
  17839. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17840. 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)
  17841. return this;
  17842. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17843. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17844. return this;
  17845. };
  17846. // Statics
  17847. Effect.ShadersStore = {};
  17848. return Effect;
  17849. })();
  17850. BABYLON.Effect = Effect;
  17851. })(BABYLON || (BABYLON = {}));
  17852. //# sourceMappingURL=babylon.effect.js.map
  17853. var BABYLON;
  17854. (function (BABYLON) {
  17855. var Material = (function () {
  17856. function Material(name, scene, doNotAdd) {
  17857. this.name = name;
  17858. this.checkReadyOnEveryCall = true;
  17859. this.checkReadyOnlyOnce = false;
  17860. this.state = "";
  17861. this.alpha = 1.0;
  17862. this.backFaceCulling = true;
  17863. this._wasPreviouslyReady = false;
  17864. this._fillMode = Material.TriangleFillMode;
  17865. this.pointSize = 1.0;
  17866. this.zOffset = 0;
  17867. this.id = name;
  17868. this._scene = scene;
  17869. if (!doNotAdd) {
  17870. scene.materials.push(this);
  17871. }
  17872. }
  17873. Object.defineProperty(Material, "TriangleFillMode", {
  17874. get: function () {
  17875. return Material._TriangleFillMode;
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(Material, "WireFrameFillMode", {
  17881. get: function () {
  17882. return Material._WireFrameFillMode;
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Object.defineProperty(Material, "PointFillMode", {
  17888. get: function () {
  17889. return Material._PointFillMode;
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(Material.prototype, "wireframe", {
  17895. get: function () {
  17896. return this._fillMode === Material.WireFrameFillMode;
  17897. },
  17898. set: function (value) {
  17899. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17900. },
  17901. enumerable: true,
  17902. configurable: true
  17903. });
  17904. Object.defineProperty(Material.prototype, "pointsCloud", {
  17905. get: function () {
  17906. return this._fillMode === Material.PointFillMode;
  17907. },
  17908. set: function (value) {
  17909. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17910. },
  17911. enumerable: true,
  17912. configurable: true
  17913. });
  17914. Object.defineProperty(Material.prototype, "fillMode", {
  17915. get: function () {
  17916. return this._fillMode;
  17917. },
  17918. set: function (value) {
  17919. this._fillMode = value;
  17920. },
  17921. enumerable: true,
  17922. configurable: true
  17923. });
  17924. Material.prototype.isReady = function (mesh, useInstances) {
  17925. return true;
  17926. };
  17927. Material.prototype.getEffect = function () {
  17928. return this._effect;
  17929. };
  17930. Material.prototype.getScene = function () {
  17931. return this._scene;
  17932. };
  17933. Material.prototype.needAlphaBlending = function () {
  17934. return (this.alpha < 1.0);
  17935. };
  17936. Material.prototype.needAlphaTesting = function () {
  17937. return false;
  17938. };
  17939. Material.prototype.getAlphaTestTexture = function () {
  17940. return null;
  17941. };
  17942. Material.prototype.trackCreation = function (onCompiled, onError) {
  17943. };
  17944. Material.prototype._preBind = function () {
  17945. var engine = this._scene.getEngine();
  17946. engine.enableEffect(this._effect);
  17947. engine.setState(this.backFaceCulling, this.zOffset);
  17948. };
  17949. Material.prototype.bind = function (world, mesh) {
  17950. this._scene._cachedMaterial = this;
  17951. if (this.onBind) {
  17952. this.onBind(this, mesh);
  17953. }
  17954. };
  17955. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17956. };
  17957. Material.prototype.unbind = function () {
  17958. };
  17959. Material.prototype.dispose = function (forceDisposeEffect) {
  17960. // Remove from scene
  17961. var index = this._scene.materials.indexOf(this);
  17962. this._scene.materials.splice(index, 1);
  17963. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17964. if (forceDisposeEffect && this._effect) {
  17965. this._scene.getEngine()._releaseEffect(this._effect);
  17966. this._effect = null;
  17967. }
  17968. // Callback
  17969. if (this.onDispose) {
  17970. this.onDispose();
  17971. }
  17972. };
  17973. Material._TriangleFillMode = 0;
  17974. Material._WireFrameFillMode = 1;
  17975. Material._PointFillMode = 2;
  17976. return Material;
  17977. })();
  17978. BABYLON.Material = Material;
  17979. })(BABYLON || (BABYLON = {}));
  17980. //# sourceMappingURL=babylon.material.js.map
  17981. var __extends = (this && this.__extends) || function (d, b) {
  17982. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17983. function __() { this.constructor = d; }
  17984. __.prototype = b.prototype;
  17985. d.prototype = new __();
  17986. };
  17987. var BABYLON;
  17988. (function (BABYLON) {
  17989. var maxSimultaneousLights = 4;
  17990. var FresnelParameters = (function () {
  17991. function FresnelParameters() {
  17992. this.isEnabled = true;
  17993. this.leftColor = BABYLON.Color3.White();
  17994. this.rightColor = BABYLON.Color3.Black();
  17995. this.bias = 0;
  17996. this.power = 1;
  17997. }
  17998. return FresnelParameters;
  17999. })();
  18000. BABYLON.FresnelParameters = FresnelParameters;
  18001. var StandardMaterial = (function (_super) {
  18002. __extends(StandardMaterial, _super);
  18003. function StandardMaterial(name, scene) {
  18004. var _this = this;
  18005. _super.call(this, name, scene);
  18006. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18007. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18008. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18009. this.specularPower = 64;
  18010. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18011. this.useAlphaFromDiffuseTexture = false;
  18012. this.useSpecularOverAlpha = true;
  18013. this.fogEnabled = true;
  18014. this._cachedDefines = null;
  18015. this._renderTargets = new BABYLON.SmartArray(16);
  18016. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18017. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18018. this._scaledDiffuse = new BABYLON.Color3();
  18019. this._scaledSpecular = new BABYLON.Color3();
  18020. this.getRenderTargetTextures = function () {
  18021. _this._renderTargets.reset();
  18022. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18023. _this._renderTargets.push(_this.reflectionTexture);
  18024. }
  18025. return _this._renderTargets;
  18026. };
  18027. }
  18028. StandardMaterial.prototype.needAlphaBlending = function () {
  18029. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18030. };
  18031. StandardMaterial.prototype.needAlphaTesting = function () {
  18032. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18033. };
  18034. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18035. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18036. };
  18037. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18038. return this.diffuseTexture;
  18039. };
  18040. // Methods
  18041. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18042. if (this.checkReadyOnlyOnce) {
  18043. if (this._wasPreviouslyReady) {
  18044. return true;
  18045. }
  18046. }
  18047. var scene = this.getScene();
  18048. if (!this.checkReadyOnEveryCall) {
  18049. if (this._renderId === scene.getRenderId()) {
  18050. return true;
  18051. }
  18052. }
  18053. var engine = scene.getEngine();
  18054. var defines = [];
  18055. var fallbacks = new BABYLON.EffectFallbacks();
  18056. var needNormals = false;
  18057. var needUVs = false;
  18058. // Textures
  18059. if (scene.texturesEnabled) {
  18060. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18061. if (!this.diffuseTexture.isReady()) {
  18062. return false;
  18063. }
  18064. else {
  18065. needUVs = true;
  18066. defines.push("#define DIFFUSE");
  18067. }
  18068. }
  18069. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18070. if (!this.ambientTexture.isReady()) {
  18071. return false;
  18072. }
  18073. else {
  18074. needUVs = true;
  18075. defines.push("#define AMBIENT");
  18076. }
  18077. }
  18078. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18079. if (!this.opacityTexture.isReady()) {
  18080. return false;
  18081. }
  18082. else {
  18083. needUVs = true;
  18084. defines.push("#define OPACITY");
  18085. if (this.opacityTexture.getAlphaFromRGB) {
  18086. defines.push("#define OPACITYRGB");
  18087. }
  18088. }
  18089. }
  18090. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18091. if (!this.reflectionTexture.isReady()) {
  18092. return false;
  18093. }
  18094. else {
  18095. needNormals = true;
  18096. needUVs = true;
  18097. defines.push("#define REFLECTION");
  18098. fallbacks.addFallback(0, "REFLECTION");
  18099. }
  18100. }
  18101. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18102. if (!this.emissiveTexture.isReady()) {
  18103. return false;
  18104. }
  18105. else {
  18106. needUVs = true;
  18107. defines.push("#define EMISSIVE");
  18108. }
  18109. }
  18110. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18111. if (!this.specularTexture.isReady()) {
  18112. return false;
  18113. }
  18114. else {
  18115. needUVs = true;
  18116. defines.push("#define SPECULAR");
  18117. fallbacks.addFallback(0, "SPECULAR");
  18118. }
  18119. }
  18120. }
  18121. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18122. if (!this.bumpTexture.isReady()) {
  18123. return false;
  18124. }
  18125. else {
  18126. needUVs = true;
  18127. defines.push("#define BUMP");
  18128. fallbacks.addFallback(0, "BUMP");
  18129. }
  18130. }
  18131. // Effect
  18132. if (this.useSpecularOverAlpha) {
  18133. defines.push("#define SPECULAROVERALPHA");
  18134. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18135. }
  18136. if (scene.clipPlane) {
  18137. defines.push("#define CLIPPLANE");
  18138. }
  18139. if (engine.getAlphaTesting()) {
  18140. defines.push("#define ALPHATEST");
  18141. }
  18142. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18143. defines.push("#define ALPHAFROMDIFFUSE");
  18144. }
  18145. // Point size
  18146. if (this.pointsCloud || scene.forcePointsCloud) {
  18147. defines.push("#define POINTSIZE");
  18148. }
  18149. // Fog
  18150. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18151. defines.push("#define FOG");
  18152. fallbacks.addFallback(1, "FOG");
  18153. }
  18154. var shadowsActivated = false;
  18155. var lightIndex = 0;
  18156. if (scene.lightsEnabled) {
  18157. for (var index = 0; index < scene.lights.length; index++) {
  18158. var light = scene.lights[index];
  18159. if (!light.isEnabled()) {
  18160. continue;
  18161. }
  18162. // Excluded check
  18163. if (light._excludedMeshesIds.length > 0) {
  18164. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18165. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18166. if (excludedMesh) {
  18167. light.excludedMeshes.push(excludedMesh);
  18168. }
  18169. }
  18170. light._excludedMeshesIds = [];
  18171. }
  18172. // Included check
  18173. if (light._includedOnlyMeshesIds.length > 0) {
  18174. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18175. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18176. if (includedOnlyMesh) {
  18177. light.includedOnlyMeshes.push(includedOnlyMesh);
  18178. }
  18179. }
  18180. light._includedOnlyMeshesIds = [];
  18181. }
  18182. if (!light.canAffectMesh(mesh)) {
  18183. continue;
  18184. }
  18185. needNormals = true;
  18186. defines.push("#define LIGHT" + lightIndex);
  18187. if (lightIndex > 0) {
  18188. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18189. }
  18190. var type;
  18191. if (light instanceof BABYLON.SpotLight) {
  18192. type = "#define SPOTLIGHT" + lightIndex;
  18193. }
  18194. else if (light instanceof BABYLON.HemisphericLight) {
  18195. type = "#define HEMILIGHT" + lightIndex;
  18196. }
  18197. else {
  18198. type = "#define POINTDIRLIGHT" + lightIndex;
  18199. }
  18200. defines.push(type);
  18201. if (lightIndex > 0) {
  18202. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18203. }
  18204. // Shadows
  18205. if (scene.shadowsEnabled) {
  18206. var shadowGenerator = light.getShadowGenerator();
  18207. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18208. defines.push("#define SHADOW" + lightIndex);
  18209. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18210. if (!shadowsActivated) {
  18211. defines.push("#define SHADOWS");
  18212. shadowsActivated = true;
  18213. }
  18214. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18215. defines.push("#define SHADOWVSM" + lightIndex);
  18216. if (lightIndex > 0) {
  18217. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18218. }
  18219. }
  18220. if (shadowGenerator.usePoissonSampling) {
  18221. defines.push("#define SHADOWPCF" + lightIndex);
  18222. if (lightIndex > 0) {
  18223. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18224. }
  18225. }
  18226. }
  18227. }
  18228. lightIndex++;
  18229. if (lightIndex === maxSimultaneousLights)
  18230. break;
  18231. }
  18232. }
  18233. if (StandardMaterial.FresnelEnabled) {
  18234. // Fresnel
  18235. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18236. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18237. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18238. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18239. var fresnelRank = 1;
  18240. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18241. defines.push("#define DIFFUSEFRESNEL");
  18242. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18243. fresnelRank++;
  18244. }
  18245. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18246. defines.push("#define OPACITYFRESNEL");
  18247. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18248. fresnelRank++;
  18249. }
  18250. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18251. defines.push("#define REFLECTIONFRESNEL");
  18252. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18253. fresnelRank++;
  18254. }
  18255. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18256. defines.push("#define EMISSIVEFRESNEL");
  18257. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18258. fresnelRank++;
  18259. }
  18260. needNormals = true;
  18261. defines.push("#define FRESNEL");
  18262. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18263. }
  18264. }
  18265. // Attribs
  18266. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18267. if (mesh) {
  18268. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18269. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18270. defines.push("#define NORMAL");
  18271. }
  18272. if (needUVs) {
  18273. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18274. attribs.push(BABYLON.VertexBuffer.UVKind);
  18275. defines.push("#define UV1");
  18276. }
  18277. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18278. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18279. defines.push("#define UV2");
  18280. }
  18281. }
  18282. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18283. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18284. defines.push("#define VERTEXCOLOR");
  18285. if (mesh.hasVertexAlpha) {
  18286. defines.push("#define VERTEXALPHA");
  18287. }
  18288. }
  18289. if (mesh.useBones) {
  18290. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18291. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18292. defines.push("#define BONES");
  18293. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18294. defines.push("#define BONES4");
  18295. fallbacks.addFallback(0, "BONES4");
  18296. }
  18297. // Instances
  18298. if (useInstances) {
  18299. defines.push("#define INSTANCES");
  18300. attribs.push("world0");
  18301. attribs.push("world1");
  18302. attribs.push("world2");
  18303. attribs.push("world3");
  18304. }
  18305. }
  18306. // Get correct effect
  18307. var join = defines.join("\n");
  18308. if (this._cachedDefines !== join) {
  18309. this._cachedDefines = join;
  18310. scene.resetCachedMaterial();
  18311. // Legacy browser patch
  18312. var shaderName = "default";
  18313. if (!scene.getEngine().getCaps().standardDerivatives) {
  18314. shaderName = "legacydefault";
  18315. }
  18316. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18317. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18318. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18319. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18320. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18321. "vFogInfos", "vFogColor", "pointSize",
  18322. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18323. "mBones",
  18324. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18325. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18326. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18327. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18328. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18329. ], join, fallbacks, this.onCompiled, this.onError);
  18330. }
  18331. if (!this._effect.isReady()) {
  18332. return false;
  18333. }
  18334. this._renderId = scene.getRenderId();
  18335. this._wasPreviouslyReady = true;
  18336. return true;
  18337. };
  18338. StandardMaterial.prototype.unbind = function () {
  18339. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18340. this._effect.setTexture("reflection2DSampler", null);
  18341. }
  18342. };
  18343. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18344. this._effect.setMatrix("world", world);
  18345. };
  18346. StandardMaterial.prototype.bind = function (world, mesh) {
  18347. var scene = this.getScene();
  18348. // Matrices
  18349. this.bindOnlyWorldMatrix(world);
  18350. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18351. // Bones
  18352. if (mesh && mesh.useBones) {
  18353. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18354. }
  18355. if (scene.getCachedMaterial() !== this) {
  18356. if (StandardMaterial.FresnelEnabled) {
  18357. // Fresnel
  18358. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18359. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18360. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18361. }
  18362. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18363. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18364. }
  18365. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18366. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18367. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18368. }
  18369. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18370. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18371. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18372. }
  18373. }
  18374. // Textures
  18375. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18376. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18377. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18378. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18379. }
  18380. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18381. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18382. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18383. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18384. }
  18385. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18386. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18387. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18388. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18389. }
  18390. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18391. if (this.reflectionTexture.isCube) {
  18392. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18393. }
  18394. else {
  18395. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18396. }
  18397. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18398. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18399. }
  18400. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18401. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18402. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18403. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18404. }
  18405. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18406. this._effect.setTexture("specularSampler", this.specularTexture);
  18407. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18408. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18409. }
  18410. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18411. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18412. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18413. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18414. }
  18415. // Clip plane
  18416. if (scene.clipPlane) {
  18417. var clipPlane = scene.clipPlane;
  18418. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18419. }
  18420. // Point size
  18421. if (this.pointsCloud) {
  18422. this._effect.setFloat("pointSize", this.pointSize);
  18423. }
  18424. // Colors
  18425. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18426. // Scaling down color according to emissive
  18427. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18428. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18429. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18430. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18431. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18432. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18433. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18434. }
  18435. // Scaling down color according to emissive
  18436. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18437. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18438. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18439. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18440. if (scene.lightsEnabled) {
  18441. var lightIndex = 0;
  18442. for (var index = 0; index < scene.lights.length; index++) {
  18443. var light = scene.lights[index];
  18444. if (!light.isEnabled()) {
  18445. continue;
  18446. }
  18447. if (!light.canAffectMesh(mesh)) {
  18448. continue;
  18449. }
  18450. if (light instanceof BABYLON.PointLight) {
  18451. // Point Light
  18452. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18453. }
  18454. else if (light instanceof BABYLON.DirectionalLight) {
  18455. // Directional Light
  18456. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18457. }
  18458. else if (light instanceof BABYLON.SpotLight) {
  18459. // Spot Light
  18460. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18461. }
  18462. else if (light instanceof BABYLON.HemisphericLight) {
  18463. // Hemispheric Light
  18464. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18465. }
  18466. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18467. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18468. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18469. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18470. // Shadows
  18471. if (scene.shadowsEnabled) {
  18472. var shadowGenerator = light.getShadowGenerator();
  18473. if (mesh.receiveShadows && shadowGenerator) {
  18474. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18475. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18476. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18477. }
  18478. }
  18479. lightIndex++;
  18480. if (lightIndex === maxSimultaneousLights)
  18481. break;
  18482. }
  18483. }
  18484. // View
  18485. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18486. this._effect.setMatrix("view", scene.getViewMatrix());
  18487. }
  18488. // Fog
  18489. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18490. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18491. this._effect.setColor3("vFogColor", scene.fogColor);
  18492. }
  18493. _super.prototype.bind.call(this, world, mesh);
  18494. };
  18495. StandardMaterial.prototype.getAnimatables = function () {
  18496. var results = [];
  18497. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18498. results.push(this.diffuseTexture);
  18499. }
  18500. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18501. results.push(this.ambientTexture);
  18502. }
  18503. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18504. results.push(this.opacityTexture);
  18505. }
  18506. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18507. results.push(this.reflectionTexture);
  18508. }
  18509. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18510. results.push(this.emissiveTexture);
  18511. }
  18512. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18513. results.push(this.specularTexture);
  18514. }
  18515. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18516. results.push(this.bumpTexture);
  18517. }
  18518. return results;
  18519. };
  18520. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18521. if (this.diffuseTexture) {
  18522. this.diffuseTexture.dispose();
  18523. }
  18524. if (this.ambientTexture) {
  18525. this.ambientTexture.dispose();
  18526. }
  18527. if (this.opacityTexture) {
  18528. this.opacityTexture.dispose();
  18529. }
  18530. if (this.reflectionTexture) {
  18531. this.reflectionTexture.dispose();
  18532. }
  18533. if (this.emissiveTexture) {
  18534. this.emissiveTexture.dispose();
  18535. }
  18536. if (this.specularTexture) {
  18537. this.specularTexture.dispose();
  18538. }
  18539. if (this.bumpTexture) {
  18540. this.bumpTexture.dispose();
  18541. }
  18542. _super.prototype.dispose.call(this, forceDisposeEffect);
  18543. };
  18544. StandardMaterial.prototype.clone = function (name) {
  18545. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18546. // Base material
  18547. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18548. newStandardMaterial.alpha = this.alpha;
  18549. newStandardMaterial.fillMode = this.fillMode;
  18550. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18551. // Standard material
  18552. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18553. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18554. }
  18555. if (this.ambientTexture && this.ambientTexture.clone) {
  18556. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18557. }
  18558. if (this.opacityTexture && this.opacityTexture.clone) {
  18559. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18560. }
  18561. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18562. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18563. }
  18564. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18565. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18566. }
  18567. if (this.specularTexture && this.specularTexture.clone) {
  18568. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18569. }
  18570. if (this.bumpTexture && this.bumpTexture.clone) {
  18571. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18572. }
  18573. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18574. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18575. newStandardMaterial.specularColor = this.specularColor.clone();
  18576. newStandardMaterial.specularPower = this.specularPower;
  18577. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18578. return newStandardMaterial;
  18579. };
  18580. // Statics
  18581. // Flags used to enable or disable a type of texture for all Standard Materials
  18582. StandardMaterial.DiffuseTextureEnabled = true;
  18583. StandardMaterial.AmbientTextureEnabled = true;
  18584. StandardMaterial.OpacityTextureEnabled = true;
  18585. StandardMaterial.ReflectionTextureEnabled = true;
  18586. StandardMaterial.EmissiveTextureEnabled = true;
  18587. StandardMaterial.SpecularTextureEnabled = true;
  18588. StandardMaterial.BumpTextureEnabled = true;
  18589. StandardMaterial.FresnelEnabled = true;
  18590. return StandardMaterial;
  18591. })(BABYLON.Material);
  18592. BABYLON.StandardMaterial = StandardMaterial;
  18593. })(BABYLON || (BABYLON = {}));
  18594. //# sourceMappingURL=babylon.standardMaterial.js.map
  18595. var __extends = (this && this.__extends) || function (d, b) {
  18596. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18597. function __() { this.constructor = d; }
  18598. __.prototype = b.prototype;
  18599. d.prototype = new __();
  18600. };
  18601. var BABYLON;
  18602. (function (BABYLON) {
  18603. var MultiMaterial = (function (_super) {
  18604. __extends(MultiMaterial, _super);
  18605. function MultiMaterial(name, scene) {
  18606. _super.call(this, name, scene, true);
  18607. this.subMaterials = new Array();
  18608. scene.multiMaterials.push(this);
  18609. }
  18610. // Properties
  18611. MultiMaterial.prototype.getSubMaterial = function (index) {
  18612. if (index < 0 || index >= this.subMaterials.length) {
  18613. return this.getScene().defaultMaterial;
  18614. }
  18615. return this.subMaterials[index];
  18616. };
  18617. // Methods
  18618. MultiMaterial.prototype.isReady = function (mesh) {
  18619. for (var index = 0; index < this.subMaterials.length; index++) {
  18620. var subMaterial = this.subMaterials[index];
  18621. if (subMaterial) {
  18622. if (!this.subMaterials[index].isReady(mesh)) {
  18623. return false;
  18624. }
  18625. }
  18626. }
  18627. return true;
  18628. };
  18629. MultiMaterial.prototype.clone = function (name) {
  18630. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18631. for (var index = 0; index < this.subMaterials.length; index++) {
  18632. var subMaterial = this.subMaterials[index];
  18633. newMultiMaterial.subMaterials.push(subMaterial);
  18634. }
  18635. return newMultiMaterial;
  18636. };
  18637. return MultiMaterial;
  18638. })(BABYLON.Material);
  18639. BABYLON.MultiMaterial = MultiMaterial;
  18640. })(BABYLON || (BABYLON = {}));
  18641. //# sourceMappingURL=babylon.multiMaterial.js.map
  18642. var BABYLON;
  18643. (function (BABYLON) {
  18644. var SceneLoader = (function () {
  18645. function SceneLoader() {
  18646. }
  18647. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18648. get: function () {
  18649. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18650. },
  18651. set: function (value) {
  18652. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18653. },
  18654. enumerable: true,
  18655. configurable: true
  18656. });
  18657. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18658. get: function () {
  18659. return SceneLoader._ShowLoadingScreen;
  18660. },
  18661. set: function (value) {
  18662. SceneLoader._ShowLoadingScreen = value;
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18668. var dotPosition = sceneFilename.lastIndexOf(".");
  18669. var queryStringPosition = sceneFilename.indexOf("?");
  18670. if (queryStringPosition === -1) {
  18671. queryStringPosition = sceneFilename.length;
  18672. }
  18673. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18674. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18675. var plugin = this._registeredPlugins[index];
  18676. if (plugin.extensions.indexOf(extension) !== -1) {
  18677. return plugin;
  18678. }
  18679. }
  18680. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18681. };
  18682. // Public functions
  18683. SceneLoader.RegisterPlugin = function (plugin) {
  18684. plugin.extensions = plugin.extensions.toLowerCase();
  18685. SceneLoader._registeredPlugins.push(plugin);
  18686. };
  18687. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18688. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18689. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18690. return;
  18691. }
  18692. var manifestChecked = function (success) {
  18693. scene.database = database;
  18694. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18695. var importMeshFromData = function (data) {
  18696. var meshes = [];
  18697. var particleSystems = [];
  18698. var skeletons = [];
  18699. try {
  18700. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18701. if (onerror) {
  18702. onerror(scene, 'unable to load the scene');
  18703. }
  18704. return;
  18705. }
  18706. }
  18707. catch (e) {
  18708. if (onerror) {
  18709. onerror(scene, e);
  18710. }
  18711. return;
  18712. }
  18713. if (onsuccess) {
  18714. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18715. onsuccess(meshes, particleSystems, skeletons);
  18716. }
  18717. };
  18718. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18719. // Direct load
  18720. importMeshFromData(sceneFilename.substr(5));
  18721. return;
  18722. }
  18723. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18724. importMeshFromData(data);
  18725. }, progressCallBack, database);
  18726. };
  18727. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18728. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18729. };
  18730. /**
  18731. * Load a scene
  18732. * @param rootUrl a string that defines the root url for scene and resources
  18733. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18734. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18735. */
  18736. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18737. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18738. };
  18739. /**
  18740. * Append a scene
  18741. * @param rootUrl a string that defines the root url for scene and resources
  18742. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18743. * @param scene is the instance of BABYLON.Scene to append to
  18744. */
  18745. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18746. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18747. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18748. return;
  18749. }
  18750. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18751. var database;
  18752. if (SceneLoader.ShowLoadingScreen) {
  18753. scene.getEngine().displayLoadingUI();
  18754. }
  18755. var loadSceneFromData = function (data) {
  18756. scene.database = database;
  18757. if (!plugin.load(scene, data, rootUrl)) {
  18758. if (onerror) {
  18759. onerror(scene);
  18760. }
  18761. scene.getEngine().hideLoadingUI();
  18762. return;
  18763. }
  18764. if (onsuccess) {
  18765. onsuccess(scene);
  18766. }
  18767. if (SceneLoader.ShowLoadingScreen) {
  18768. scene.executeWhenReady(function () {
  18769. scene.getEngine().hideLoadingUI();
  18770. });
  18771. }
  18772. };
  18773. var manifestChecked = function (success) {
  18774. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18775. };
  18776. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18777. // Direct load
  18778. loadSceneFromData(sceneFilename.substr(5));
  18779. return;
  18780. }
  18781. if (rootUrl.indexOf("file:") === -1) {
  18782. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18783. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18784. }
  18785. else {
  18786. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18787. }
  18788. };
  18789. // Flags
  18790. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18791. SceneLoader._ShowLoadingScreen = true;
  18792. // Members
  18793. SceneLoader._registeredPlugins = new Array();
  18794. return SceneLoader;
  18795. })();
  18796. BABYLON.SceneLoader = SceneLoader;
  18797. ;
  18798. })(BABYLON || (BABYLON = {}));
  18799. //# sourceMappingURL=babylon.sceneLoader.js.map
  18800. var BABYLON;
  18801. (function (BABYLON) {
  18802. var Internals;
  18803. (function (Internals) {
  18804. var checkColors4 = function (colors, count) {
  18805. // Check if color3 was used
  18806. if (colors.length === count * 3) {
  18807. var colors4 = [];
  18808. for (var index = 0; index < colors.length; index += 3) {
  18809. var newIndex = (index / 3) * 4;
  18810. colors4[newIndex] = colors[index];
  18811. colors4[newIndex + 1] = colors[index + 1];
  18812. colors4[newIndex + 2] = colors[index + 2];
  18813. colors4[newIndex + 3] = 1.0;
  18814. }
  18815. return colors4;
  18816. }
  18817. return colors;
  18818. };
  18819. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18820. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18821. texture.name = parsedTexture.name;
  18822. texture.hasAlpha = parsedTexture.hasAlpha;
  18823. texture.level = parsedTexture.level;
  18824. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18825. return texture;
  18826. };
  18827. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18828. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18829. return null;
  18830. }
  18831. if (parsedTexture.isCube) {
  18832. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18833. }
  18834. var texture;
  18835. if (parsedTexture.mirrorPlane) {
  18836. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18837. texture._waitingRenderList = parsedTexture.renderList;
  18838. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18839. }
  18840. else if (parsedTexture.isRenderTarget) {
  18841. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18842. texture._waitingRenderList = parsedTexture.renderList;
  18843. }
  18844. else {
  18845. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18846. }
  18847. texture.name = parsedTexture.name;
  18848. texture.hasAlpha = parsedTexture.hasAlpha;
  18849. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18850. texture.level = parsedTexture.level;
  18851. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18852. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18853. texture.uOffset = parsedTexture.uOffset;
  18854. texture.vOffset = parsedTexture.vOffset;
  18855. texture.uScale = parsedTexture.uScale;
  18856. texture.vScale = parsedTexture.vScale;
  18857. texture.uAng = parsedTexture.uAng;
  18858. texture.vAng = parsedTexture.vAng;
  18859. texture.wAng = parsedTexture.wAng;
  18860. texture.wrapU = parsedTexture.wrapU;
  18861. texture.wrapV = parsedTexture.wrapV;
  18862. // Animations
  18863. if (parsedTexture.animations) {
  18864. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18865. var parsedAnimation = parsedTexture.animations[animationIndex];
  18866. texture.animations.push(parseAnimation(parsedAnimation));
  18867. }
  18868. }
  18869. return texture;
  18870. };
  18871. var parseSkeleton = function (parsedSkeleton, scene) {
  18872. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18873. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18874. var parsedBone = parsedSkeleton.bones[index];
  18875. var parentBone = null;
  18876. if (parsedBone.parentBoneIndex > -1) {
  18877. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18878. }
  18879. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18880. if (parsedBone.animation) {
  18881. bone.animations.push(parseAnimation(parsedBone.animation));
  18882. }
  18883. }
  18884. return skeleton;
  18885. };
  18886. var parseFresnelParameters = function (parsedFresnelParameters) {
  18887. var fresnelParameters = new BABYLON.FresnelParameters();
  18888. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18889. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18890. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18891. fresnelParameters.bias = parsedFresnelParameters.bias;
  18892. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18893. return fresnelParameters;
  18894. };
  18895. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18896. var material;
  18897. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18898. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18899. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18900. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18901. material.specularPower = parsedMaterial.specularPower;
  18902. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18903. material.alpha = parsedMaterial.alpha;
  18904. material.id = parsedMaterial.id;
  18905. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18906. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18907. material.wireframe = parsedMaterial.wireframe;
  18908. if (parsedMaterial.diffuseTexture) {
  18909. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18910. }
  18911. if (parsedMaterial.diffuseFresnelParameters) {
  18912. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18913. }
  18914. if (parsedMaterial.ambientTexture) {
  18915. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18916. }
  18917. if (parsedMaterial.opacityTexture) {
  18918. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18919. }
  18920. if (parsedMaterial.opacityFresnelParameters) {
  18921. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18922. }
  18923. if (parsedMaterial.reflectionTexture) {
  18924. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18925. }
  18926. if (parsedMaterial.reflectionFresnelParameters) {
  18927. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18928. }
  18929. if (parsedMaterial.emissiveTexture) {
  18930. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18931. }
  18932. if (parsedMaterial.emissiveFresnelParameters) {
  18933. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18934. }
  18935. if (parsedMaterial.specularTexture) {
  18936. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18937. }
  18938. if (parsedMaterial.bumpTexture) {
  18939. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18940. }
  18941. return material;
  18942. };
  18943. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18944. for (var index = 0; index < parsedData.materials.length; index++) {
  18945. var parsedMaterial = parsedData.materials[index];
  18946. if (parsedMaterial.id === id) {
  18947. return parseMaterial(parsedMaterial, scene, rootUrl);
  18948. }
  18949. }
  18950. return null;
  18951. };
  18952. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18953. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18954. multiMaterial.id = parsedMultiMaterial.id;
  18955. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18956. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18957. var subMatId = parsedMultiMaterial.materials[matIndex];
  18958. if (subMatId) {
  18959. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18960. }
  18961. else {
  18962. multiMaterial.subMaterials.push(null);
  18963. }
  18964. }
  18965. return multiMaterial;
  18966. };
  18967. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18968. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18969. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18970. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18971. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18972. var parsedFlare = parsedLensFlareSystem.flares[index];
  18973. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18974. }
  18975. return lensFlareSystem;
  18976. };
  18977. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18978. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18979. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18980. if (parsedParticleSystem.textureName) {
  18981. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18982. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18983. }
  18984. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18985. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18986. particleSystem.minSize = parsedParticleSystem.minSize;
  18987. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18988. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18989. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18990. particleSystem.emitter = emitter;
  18991. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18992. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18993. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18994. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18995. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18996. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18997. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18998. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18999. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19000. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19001. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19002. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19003. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19004. particleSystem.start();
  19005. return particleSystem;
  19006. };
  19007. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19008. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19009. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19010. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19011. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19012. shadowGenerator.getShadowMap().renderList.push(mesh);
  19013. }
  19014. if (parsedShadowGenerator.usePoissonSampling) {
  19015. shadowGenerator.usePoissonSampling = true;
  19016. }
  19017. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19018. shadowGenerator.useVarianceShadowMap = true;
  19019. }
  19020. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19021. shadowGenerator.useBlurVarianceShadowMap = true;
  19022. if (parsedShadowGenerator.blurScale) {
  19023. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19024. }
  19025. if (parsedShadowGenerator.blurBoxOffset) {
  19026. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19027. }
  19028. }
  19029. if (parsedShadowGenerator.bias !== undefined) {
  19030. shadowGenerator.bias = parsedShadowGenerator.bias;
  19031. }
  19032. return shadowGenerator;
  19033. };
  19034. var parseAnimation = function (parsedAnimation) {
  19035. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19036. var dataType = parsedAnimation.dataType;
  19037. var keys = [];
  19038. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19039. var key = parsedAnimation.keys[index];
  19040. var data;
  19041. switch (dataType) {
  19042. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19043. data = key.values[0];
  19044. break;
  19045. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19046. data = BABYLON.Quaternion.FromArray(key.values);
  19047. break;
  19048. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19049. data = BABYLON.Matrix.FromArray(key.values);
  19050. break;
  19051. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19052. default:
  19053. data = BABYLON.Vector3.FromArray(key.values);
  19054. break;
  19055. }
  19056. keys.push({
  19057. frame: key.frame,
  19058. value: data
  19059. });
  19060. }
  19061. animation.setKeys(keys);
  19062. return animation;
  19063. };
  19064. var parseLight = function (parsedLight, scene) {
  19065. var light;
  19066. switch (parsedLight.type) {
  19067. case 0:
  19068. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19069. break;
  19070. case 1:
  19071. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19072. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19073. break;
  19074. case 2:
  19075. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19076. break;
  19077. case 3:
  19078. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19079. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19080. break;
  19081. }
  19082. light.id = parsedLight.id;
  19083. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19084. if (parsedLight.intensity !== undefined) {
  19085. light.intensity = parsedLight.intensity;
  19086. }
  19087. if (parsedLight.range) {
  19088. light.range = parsedLight.range;
  19089. }
  19090. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19091. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19092. if (parsedLight.excludedMeshesIds) {
  19093. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19094. }
  19095. // Parent
  19096. if (parsedLight.parentId) {
  19097. light._waitingParentId = parsedLight.parentId;
  19098. }
  19099. if (parsedLight.includedOnlyMeshesIds) {
  19100. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19101. }
  19102. // Animations
  19103. if (parsedLight.animations) {
  19104. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19105. var parsedAnimation = parsedLight.animations[animationIndex];
  19106. light.animations.push(parseAnimation(parsedAnimation));
  19107. }
  19108. }
  19109. if (parsedLight.autoAnimate) {
  19110. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19111. }
  19112. };
  19113. var parseCamera = function (parsedCamera, scene) {
  19114. var camera;
  19115. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19116. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19117. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19118. var alpha = parsedCamera.alpha;
  19119. var beta = parsedCamera.beta;
  19120. var radius = parsedCamera.radius;
  19121. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19122. var eye_space = parsedCamera.eye_space;
  19123. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19124. }
  19125. else {
  19126. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19127. }
  19128. }
  19129. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19130. eye_space = parsedCamera.eye_space;
  19131. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19132. }
  19133. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19134. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19135. }
  19136. else if (parsedCamera.type === "FollowCamera") {
  19137. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19138. camera.heightOffset = parsedCamera.heightOffset;
  19139. camera.radius = parsedCamera.radius;
  19140. camera.rotationOffset = parsedCamera.rotationOffset;
  19141. if (lockedTargetMesh)
  19142. camera.target = lockedTargetMesh;
  19143. }
  19144. else if (parsedCamera.type === "GamepadCamera") {
  19145. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19146. }
  19147. else if (parsedCamera.type === "TouchCamera") {
  19148. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19149. }
  19150. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19151. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19152. }
  19153. else if (parsedCamera.type === "WebVRFreeCamera") {
  19154. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19155. }
  19156. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19157. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19158. }
  19159. else {
  19160. // Free Camera is the default value
  19161. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19162. }
  19163. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19164. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19165. camera.lockedTarget = lockedTargetMesh;
  19166. }
  19167. camera.id = parsedCamera.id;
  19168. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19169. // Parent
  19170. if (parsedCamera.parentId) {
  19171. camera._waitingParentId = parsedCamera.parentId;
  19172. }
  19173. // Target
  19174. if (parsedCamera.target) {
  19175. if (camera.setTarget) {
  19176. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19177. }
  19178. else {
  19179. //For ArcRotate
  19180. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19181. }
  19182. }
  19183. else {
  19184. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19185. }
  19186. camera.fov = parsedCamera.fov;
  19187. camera.minZ = parsedCamera.minZ;
  19188. camera.maxZ = parsedCamera.maxZ;
  19189. camera.speed = parsedCamera.speed;
  19190. camera.inertia = parsedCamera.inertia;
  19191. camera.checkCollisions = parsedCamera.checkCollisions;
  19192. camera.applyGravity = parsedCamera.applyGravity;
  19193. if (parsedCamera.ellipsoid) {
  19194. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19195. }
  19196. // Animations
  19197. if (parsedCamera.animations) {
  19198. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19199. var parsedAnimation = parsedCamera.animations[animationIndex];
  19200. camera.animations.push(parseAnimation(parsedAnimation));
  19201. }
  19202. }
  19203. if (parsedCamera.autoAnimate) {
  19204. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19205. }
  19206. // Layer Mask
  19207. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19208. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19209. }
  19210. else {
  19211. camera.layerMask = 0xFFFFFFFF;
  19212. }
  19213. return camera;
  19214. };
  19215. var parseGeometry = function (parsedGeometry, scene) {
  19216. var id = parsedGeometry.id;
  19217. return scene.getGeometryByID(id);
  19218. };
  19219. var parseBox = function (parsedBox, scene) {
  19220. if (parseGeometry(parsedBox, scene)) {
  19221. return null; // null since geometry could be something else than a box...
  19222. }
  19223. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19224. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19225. scene.pushGeometry(box, true);
  19226. return box;
  19227. };
  19228. var parseSphere = function (parsedSphere, scene) {
  19229. if (parseGeometry(parsedSphere, scene)) {
  19230. return null; // null since geometry could be something else than a sphere...
  19231. }
  19232. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19233. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19234. scene.pushGeometry(sphere, true);
  19235. return sphere;
  19236. };
  19237. var parseCylinder = function (parsedCylinder, scene) {
  19238. if (parseGeometry(parsedCylinder, scene)) {
  19239. return null; // null since geometry could be something else than a cylinder...
  19240. }
  19241. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19242. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19243. scene.pushGeometry(cylinder, true);
  19244. return cylinder;
  19245. };
  19246. var parseTorus = function (parsedTorus, scene) {
  19247. if (parseGeometry(parsedTorus, scene)) {
  19248. return null; // null since geometry could be something else than a torus...
  19249. }
  19250. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19251. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19252. scene.pushGeometry(torus, true);
  19253. return torus;
  19254. };
  19255. var parseGround = function (parsedGround, scene) {
  19256. if (parseGeometry(parsedGround, scene)) {
  19257. return null; // null since geometry could be something else than a ground...
  19258. }
  19259. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19260. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19261. scene.pushGeometry(ground, true);
  19262. return ground;
  19263. };
  19264. var parsePlane = function (parsedPlane, scene) {
  19265. if (parseGeometry(parsedPlane, scene)) {
  19266. return null; // null since geometry could be something else than a plane...
  19267. }
  19268. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19269. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19270. scene.pushGeometry(plane, true);
  19271. return plane;
  19272. };
  19273. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19274. if (parseGeometry(parsedTorusKnot, scene)) {
  19275. return null; // null since geometry could be something else than a torusKnot...
  19276. }
  19277. 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);
  19278. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19279. scene.pushGeometry(torusKnot, true);
  19280. return torusKnot;
  19281. };
  19282. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19283. if (parseGeometry(parsedVertexData, scene)) {
  19284. return null; // null since geometry could be a primitive
  19285. }
  19286. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19287. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19288. if (parsedVertexData.delayLoadingFile) {
  19289. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19290. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19291. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19292. geometry._delayInfo = [];
  19293. if (parsedVertexData.hasUVs) {
  19294. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19295. }
  19296. if (parsedVertexData.hasUVs2) {
  19297. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19298. }
  19299. if (parsedVertexData.hasColors) {
  19300. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19301. }
  19302. if (parsedVertexData.hasMatricesIndices) {
  19303. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19304. }
  19305. if (parsedVertexData.hasMatricesWeights) {
  19306. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19307. }
  19308. geometry._delayLoadingFunction = importVertexData;
  19309. }
  19310. else {
  19311. importVertexData(parsedVertexData, geometry);
  19312. }
  19313. scene.pushGeometry(geometry, true);
  19314. return geometry;
  19315. };
  19316. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19317. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19318. mesh.id = parsedMesh.id;
  19319. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19320. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19321. if (parsedMesh.rotationQuaternion) {
  19322. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19323. }
  19324. else if (parsedMesh.rotation) {
  19325. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19326. }
  19327. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19328. if (parsedMesh.localMatrix) {
  19329. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19330. }
  19331. else if (parsedMesh.pivotMatrix) {
  19332. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19333. }
  19334. mesh.setEnabled(parsedMesh.isEnabled);
  19335. mesh.isVisible = parsedMesh.isVisible;
  19336. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19337. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19338. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19339. if (parsedMesh.applyFog !== undefined) {
  19340. mesh.applyFog = parsedMesh.applyFog;
  19341. }
  19342. if (parsedMesh.pickable !== undefined) {
  19343. mesh.isPickable = parsedMesh.pickable;
  19344. }
  19345. if (parsedMesh.alphaIndex !== undefined) {
  19346. mesh.alphaIndex = parsedMesh.alphaIndex;
  19347. }
  19348. mesh.receiveShadows = parsedMesh.receiveShadows;
  19349. mesh.billboardMode = parsedMesh.billboardMode;
  19350. if (parsedMesh.visibility !== undefined) {
  19351. mesh.visibility = parsedMesh.visibility;
  19352. }
  19353. mesh.checkCollisions = parsedMesh.checkCollisions;
  19354. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19355. // Parent
  19356. if (parsedMesh.parentId) {
  19357. mesh._waitingParentId = parsedMesh.parentId;
  19358. }
  19359. // Actions
  19360. if (parsedMesh.actions !== undefined) {
  19361. mesh._waitingActions = parsedMesh.actions;
  19362. }
  19363. // Geometry
  19364. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19365. if (parsedMesh.delayLoadingFile) {
  19366. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19367. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19368. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19369. if (parsedMesh._binaryInfo) {
  19370. mesh._binaryInfo = parsedMesh._binaryInfo;
  19371. }
  19372. mesh._delayInfo = [];
  19373. if (parsedMesh.hasUVs) {
  19374. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19375. }
  19376. if (parsedMesh.hasUVs2) {
  19377. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19378. }
  19379. if (parsedMesh.hasColors) {
  19380. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19381. }
  19382. if (parsedMesh.hasMatricesIndices) {
  19383. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19384. }
  19385. if (parsedMesh.hasMatricesWeights) {
  19386. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19387. }
  19388. mesh._delayLoadingFunction = importGeometry;
  19389. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19390. mesh._checkDelayState();
  19391. }
  19392. }
  19393. else {
  19394. importGeometry(parsedMesh, mesh);
  19395. }
  19396. // Material
  19397. if (parsedMesh.materialId) {
  19398. mesh.setMaterialByID(parsedMesh.materialId);
  19399. }
  19400. else {
  19401. mesh.material = null;
  19402. }
  19403. // Skeleton
  19404. if (parsedMesh.skeletonId > -1) {
  19405. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19406. }
  19407. // Physics
  19408. if (parsedMesh.physicsImpostor) {
  19409. if (!scene.isPhysicsEnabled()) {
  19410. scene.enablePhysics();
  19411. }
  19412. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19413. }
  19414. // Animations
  19415. if (parsedMesh.animations) {
  19416. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19417. var parsedAnimation = parsedMesh.animations[animationIndex];
  19418. mesh.animations.push(parseAnimation(parsedAnimation));
  19419. }
  19420. }
  19421. if (parsedMesh.autoAnimate) {
  19422. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19423. }
  19424. // Layer Mask
  19425. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19426. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19427. }
  19428. else {
  19429. mesh.layerMask = 0xFFFFFFFF;
  19430. }
  19431. // Instances
  19432. if (parsedMesh.instances) {
  19433. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19434. var parsedInstance = parsedMesh.instances[index];
  19435. var instance = mesh.createInstance(parsedInstance.name);
  19436. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19437. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19438. if (parsedInstance.rotationQuaternion) {
  19439. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19440. }
  19441. else if (parsedInstance.rotation) {
  19442. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19443. }
  19444. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19445. instance.checkCollisions = mesh.checkCollisions;
  19446. if (parsedMesh.animations) {
  19447. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19448. parsedAnimation = parsedMesh.animations[animationIndex];
  19449. instance.animations.push(parseAnimation(parsedAnimation));
  19450. }
  19451. }
  19452. }
  19453. }
  19454. return mesh;
  19455. };
  19456. var parseActions = function (parsedActions, object, scene) {
  19457. var actionManager = new BABYLON.ActionManager(scene);
  19458. if (object === null)
  19459. scene.actionManager = actionManager;
  19460. else
  19461. object.actionManager = actionManager;
  19462. // instanciate a new object
  19463. var instanciate = function (name, params) {
  19464. var newInstance = Object.create(BABYLON[name].prototype);
  19465. newInstance.constructor.apply(newInstance, params);
  19466. return newInstance;
  19467. };
  19468. var parseParameter = function (name, value, target, propertyPath) {
  19469. if (propertyPath === null) {
  19470. // String, boolean or float
  19471. var floatValue = parseFloat(value);
  19472. if (value === "true" || value === "false")
  19473. return value === "true";
  19474. else
  19475. return isNaN(floatValue) ? value : floatValue;
  19476. }
  19477. var effectiveTarget = propertyPath.split(".");
  19478. var values = value.split(",");
  19479. // Get effective Target
  19480. for (var i = 0; i < effectiveTarget.length; i++) {
  19481. target = target[effectiveTarget[i]];
  19482. }
  19483. // Return appropriate value with its type
  19484. if (typeof (target) === "boolean")
  19485. return values[0] === "true";
  19486. if (typeof (target) === "string")
  19487. return values[0];
  19488. // Parameters with multiple values such as Vector3 etc.
  19489. var split = new Array();
  19490. for (var i = 0; i < values.length; i++)
  19491. split.push(parseFloat(values[i]));
  19492. if (target instanceof BABYLON.Vector3)
  19493. return BABYLON.Vector3.FromArray(split);
  19494. if (target instanceof BABYLON.Vector4)
  19495. return BABYLON.Vector4.FromArray(split);
  19496. if (target instanceof BABYLON.Color3)
  19497. return BABYLON.Color3.FromArray(split);
  19498. if (target instanceof BABYLON.Color4)
  19499. return BABYLON.Color4.FromArray(split);
  19500. return parseFloat(values[0]);
  19501. };
  19502. // traverse graph per trigger
  19503. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19504. if (combineArray === void 0) { combineArray = null; }
  19505. if (parsedAction.detached)
  19506. return;
  19507. var parameters = new Array();
  19508. var target = null;
  19509. var propertyPath = null;
  19510. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19511. // Parameters
  19512. if (parsedAction.type === 2)
  19513. parameters.push(actionManager);
  19514. else
  19515. parameters.push(trigger);
  19516. if (combine) {
  19517. var actions = new Array();
  19518. for (var j = 0; j < parsedAction.combine.length; j++) {
  19519. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19520. }
  19521. parameters.push(actions);
  19522. }
  19523. else {
  19524. for (var i = 0; i < parsedAction.properties.length; i++) {
  19525. var value = parsedAction.properties[i].value;
  19526. var name = parsedAction.properties[i].name;
  19527. var targetType = parsedAction.properties[i].targetType;
  19528. if (name === "target")
  19529. if (targetType !== null && targetType === "SceneProperties")
  19530. value = target = scene;
  19531. else
  19532. value = target = scene.getNodeByName(value);
  19533. else if (name === "parent")
  19534. value = scene.getNodeByName(value);
  19535. else if (name === "sound")
  19536. value = scene.getSoundByName(value);
  19537. else if (name !== "propertyPath") {
  19538. if (parsedAction.type === 2 && name === "operator")
  19539. value = BABYLON.ValueCondition[value];
  19540. else
  19541. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19542. }
  19543. else {
  19544. propertyPath = value;
  19545. }
  19546. parameters.push(value);
  19547. }
  19548. }
  19549. if (combineArray === null) {
  19550. parameters.push(condition);
  19551. }
  19552. else {
  19553. parameters.push(null);
  19554. }
  19555. // If interpolate value action
  19556. if (parsedAction.name === "InterpolateValueAction") {
  19557. var param = parameters[parameters.length - 2];
  19558. parameters[parameters.length - 1] = param;
  19559. parameters[parameters.length - 2] = condition;
  19560. }
  19561. // Action or condition(s) and not CombineAction
  19562. var newAction = instanciate(parsedAction.name, parameters);
  19563. if (combineArray === null) {
  19564. if (newAction instanceof BABYLON.Condition) {
  19565. condition = newAction;
  19566. newAction = action;
  19567. }
  19568. else {
  19569. condition = null;
  19570. if (action)
  19571. action.then(newAction);
  19572. else
  19573. actionManager.registerAction(newAction);
  19574. }
  19575. }
  19576. else {
  19577. combineArray.push(newAction);
  19578. }
  19579. for (var i = 0; i < parsedAction.children.length; i++)
  19580. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19581. };
  19582. // triggers
  19583. for (var i = 0; i < parsedActions.children.length; i++) {
  19584. var triggerParams;
  19585. var trigger = parsedActions.children[i];
  19586. if (trigger.properties.length > 0) {
  19587. var param = trigger.properties[0].value;
  19588. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19589. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19590. }
  19591. else
  19592. triggerParams = BABYLON.ActionManager[trigger.name];
  19593. for (var j = 0; j < trigger.children.length; j++) {
  19594. if (!trigger.detached)
  19595. traverse(trigger.children[j], triggerParams, null, null);
  19596. }
  19597. }
  19598. };
  19599. var parseSound = function (parsedSound, scene, rootUrl) {
  19600. var soundName = parsedSound.name;
  19601. var soundUrl = rootUrl + soundName;
  19602. var options = {
  19603. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19604. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19605. rolloffFactor: parsedSound.rolloffFactor,
  19606. refDistance: parsedSound.refDistance,
  19607. distanceModel: parsedSound.distanceModel,
  19608. playbackRate: parsedSound.playbackRate
  19609. };
  19610. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19611. scene._addPendingData(newSound);
  19612. if (parsedSound.position) {
  19613. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19614. newSound.setPosition(soundPosition);
  19615. }
  19616. if (parsedSound.isDirectional) {
  19617. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19618. if (parsedSound.localDirectionToMesh) {
  19619. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19620. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19621. }
  19622. }
  19623. if (parsedSound.connectedMeshId) {
  19624. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19625. if (connectedMesh) {
  19626. newSound.attachToMesh(connectedMesh);
  19627. }
  19628. }
  19629. };
  19630. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19631. names = (names instanceof Array) ? names : [names];
  19632. for (var i in names) {
  19633. if (mesh.name === names[i]) {
  19634. hierarchyIds.push(mesh.id);
  19635. return true;
  19636. }
  19637. }
  19638. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19639. hierarchyIds.push(mesh.id);
  19640. return true;
  19641. }
  19642. return false;
  19643. };
  19644. var importVertexData = function (parsedVertexData, geometry) {
  19645. var vertexData = new BABYLON.VertexData();
  19646. // positions
  19647. var positions = parsedVertexData.positions;
  19648. if (positions) {
  19649. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19650. }
  19651. // normals
  19652. var normals = parsedVertexData.normals;
  19653. if (normals) {
  19654. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19655. }
  19656. // uvs
  19657. var uvs = parsedVertexData.uvs;
  19658. if (uvs) {
  19659. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19660. }
  19661. // uv2s
  19662. var uv2s = parsedVertexData.uv2s;
  19663. if (uv2s) {
  19664. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19665. }
  19666. // colors
  19667. var colors = parsedVertexData.colors;
  19668. if (colors) {
  19669. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19670. }
  19671. // matricesIndices
  19672. var matricesIndices = parsedVertexData.matricesIndices;
  19673. if (matricesIndices) {
  19674. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19675. }
  19676. // matricesWeights
  19677. var matricesWeights = parsedVertexData.matricesWeights;
  19678. if (matricesWeights) {
  19679. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19680. }
  19681. // indices
  19682. var indices = parsedVertexData.indices;
  19683. if (indices) {
  19684. vertexData.indices = indices;
  19685. }
  19686. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19687. };
  19688. var importGeometry = function (parsedGeometry, mesh) {
  19689. var scene = mesh.getScene();
  19690. // Geometry
  19691. var geometryId = parsedGeometry.geometryId;
  19692. if (geometryId) {
  19693. var geometry = scene.getGeometryByID(geometryId);
  19694. if (geometry) {
  19695. geometry.applyToMesh(mesh);
  19696. }
  19697. }
  19698. else if (parsedGeometry instanceof ArrayBuffer) {
  19699. var binaryInfo = mesh._binaryInfo;
  19700. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19701. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19702. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19703. }
  19704. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19705. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19706. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19707. }
  19708. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19709. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19710. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19711. }
  19712. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19713. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19714. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19715. }
  19716. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19717. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19718. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19719. }
  19720. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19721. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19722. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19723. }
  19724. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19725. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19726. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19727. }
  19728. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19729. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19730. mesh.setIndices(indicesData);
  19731. }
  19732. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19733. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19734. mesh.subMeshes = [];
  19735. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19736. var materialIndex = subMeshesData[(i * 5) + 0];
  19737. var verticesStart = subMeshesData[(i * 5) + 1];
  19738. var verticesCount = subMeshesData[(i * 5) + 2];
  19739. var indexStart = subMeshesData[(i * 5) + 3];
  19740. var indexCount = subMeshesData[(i * 5) + 4];
  19741. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19742. }
  19743. }
  19744. }
  19745. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19746. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19747. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19748. if (parsedGeometry.uvs) {
  19749. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19750. }
  19751. if (parsedGeometry.uvs2) {
  19752. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19753. }
  19754. if (parsedGeometry.colors) {
  19755. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19756. }
  19757. if (parsedGeometry.matricesIndices) {
  19758. if (!parsedGeometry.matricesIndices._isExpanded) {
  19759. var floatIndices = [];
  19760. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19761. var matricesIndex = parsedGeometry.matricesIndices[i];
  19762. floatIndices.push(matricesIndex & 0x000000FF);
  19763. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19764. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19765. floatIndices.push(matricesIndex >> 24);
  19766. }
  19767. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19768. }
  19769. else {
  19770. delete parsedGeometry.matricesIndices._isExpanded;
  19771. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19772. }
  19773. }
  19774. if (parsedGeometry.matricesWeights) {
  19775. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19776. }
  19777. mesh.setIndices(parsedGeometry.indices);
  19778. // SubMeshes
  19779. if (parsedGeometry.subMeshes) {
  19780. mesh.subMeshes = [];
  19781. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19782. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19783. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19784. }
  19785. }
  19786. }
  19787. // Flat shading
  19788. if (mesh._shouldGenerateFlatShading) {
  19789. mesh.convertToFlatShadedMesh();
  19790. delete mesh._shouldGenerateFlatShading;
  19791. }
  19792. // Update
  19793. mesh.computeWorldMatrix(true);
  19794. // Octree
  19795. if (scene._selectionOctree) {
  19796. scene._selectionOctree.addMesh(mesh);
  19797. }
  19798. };
  19799. BABYLON.SceneLoader.RegisterPlugin({
  19800. extensions: ".babylon",
  19801. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19802. var parsedData = JSON.parse(data);
  19803. var loadedSkeletonsIds = [];
  19804. var loadedMaterialsIds = [];
  19805. var hierarchyIds = [];
  19806. for (var index = 0; index < parsedData.meshes.length; index++) {
  19807. var parsedMesh = parsedData.meshes[index];
  19808. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19809. if (meshesNames instanceof Array) {
  19810. // Remove found mesh name from list.
  19811. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19812. }
  19813. //Geometry?
  19814. if (parsedMesh.geometryId) {
  19815. //does the file contain geometries?
  19816. if (parsedData.geometries) {
  19817. //find the correct geometry and add it to the scene
  19818. var found = false;
  19819. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19820. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19821. return;
  19822. }
  19823. else {
  19824. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19825. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19826. switch (geometryType) {
  19827. case "boxes":
  19828. parseBox(parsedGeometryData, scene);
  19829. break;
  19830. case "spheres":
  19831. parseSphere(parsedGeometryData, scene);
  19832. break;
  19833. case "cylinders":
  19834. parseCylinder(parsedGeometryData, scene);
  19835. break;
  19836. case "toruses":
  19837. parseTorus(parsedGeometryData, scene);
  19838. break;
  19839. case "grounds":
  19840. parseGround(parsedGeometryData, scene);
  19841. break;
  19842. case "planes":
  19843. parsePlane(parsedGeometryData, scene);
  19844. break;
  19845. case "torusKnots":
  19846. parseTorusKnot(parsedGeometryData, scene);
  19847. break;
  19848. case "vertexData":
  19849. parseVertexData(parsedGeometryData, scene, rootUrl);
  19850. break;
  19851. }
  19852. found = true;
  19853. }
  19854. });
  19855. }
  19856. });
  19857. }
  19858. }
  19859. // Material ?
  19860. if (parsedMesh.materialId) {
  19861. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19862. if (!materialFound) {
  19863. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19864. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19865. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19866. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19867. var subMatId = parsedMultiMaterial.materials[matIndex];
  19868. loadedMaterialsIds.push(subMatId);
  19869. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19870. }
  19871. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19872. parseMultiMaterial(parsedMultiMaterial, scene);
  19873. materialFound = true;
  19874. break;
  19875. }
  19876. }
  19877. }
  19878. if (!materialFound) {
  19879. loadedMaterialsIds.push(parsedMesh.materialId);
  19880. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19881. }
  19882. }
  19883. // Skeleton ?
  19884. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19885. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19886. if (!skeletonAlreadyLoaded) {
  19887. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19888. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19889. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19890. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19891. loadedSkeletonsIds.push(parsedSkeleton.id);
  19892. }
  19893. }
  19894. }
  19895. }
  19896. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19897. meshes.push(mesh);
  19898. }
  19899. }
  19900. // Connecting parents
  19901. for (index = 0; index < scene.meshes.length; index++) {
  19902. var currentMesh = scene.meshes[index];
  19903. if (currentMesh._waitingParentId) {
  19904. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19905. currentMesh._waitingParentId = undefined;
  19906. }
  19907. }
  19908. // Particles
  19909. if (parsedData.particleSystems) {
  19910. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19911. var parsedParticleSystem = parsedData.particleSystems[index];
  19912. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19913. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19914. }
  19915. }
  19916. }
  19917. return true;
  19918. },
  19919. load: function (scene, data, rootUrl) {
  19920. var parsedData = JSON.parse(data);
  19921. // Scene
  19922. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19923. scene.autoClear = parsedData.autoClear;
  19924. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19925. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19926. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19927. // Fog
  19928. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19929. scene.fogMode = parsedData.fogMode;
  19930. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19931. scene.fogStart = parsedData.fogStart;
  19932. scene.fogEnd = parsedData.fogEnd;
  19933. scene.fogDensity = parsedData.fogDensity;
  19934. }
  19935. // Lights
  19936. for (var index = 0; index < parsedData.lights.length; index++) {
  19937. var parsedLight = parsedData.lights[index];
  19938. parseLight(parsedLight, scene);
  19939. }
  19940. // Materials
  19941. if (parsedData.materials) {
  19942. for (index = 0; index < parsedData.materials.length; index++) {
  19943. var parsedMaterial = parsedData.materials[index];
  19944. parseMaterial(parsedMaterial, scene, rootUrl);
  19945. }
  19946. }
  19947. if (parsedData.multiMaterials) {
  19948. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19949. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19950. parseMultiMaterial(parsedMultiMaterial, scene);
  19951. }
  19952. }
  19953. // Skeletons
  19954. if (parsedData.skeletons) {
  19955. for (index = 0; index < parsedData.skeletons.length; index++) {
  19956. var parsedSkeleton = parsedData.skeletons[index];
  19957. parseSkeleton(parsedSkeleton, scene);
  19958. }
  19959. }
  19960. // Geometries
  19961. var geometries = parsedData.geometries;
  19962. if (geometries) {
  19963. // Boxes
  19964. var boxes = geometries.boxes;
  19965. if (boxes) {
  19966. for (index = 0; index < boxes.length; index++) {
  19967. var parsedBox = boxes[index];
  19968. parseBox(parsedBox, scene);
  19969. }
  19970. }
  19971. // Spheres
  19972. var spheres = geometries.spheres;
  19973. if (spheres) {
  19974. for (index = 0; index < spheres.length; index++) {
  19975. var parsedSphere = spheres[index];
  19976. parseSphere(parsedSphere, scene);
  19977. }
  19978. }
  19979. // Cylinders
  19980. var cylinders = geometries.cylinders;
  19981. if (cylinders) {
  19982. for (index = 0; index < cylinders.length; index++) {
  19983. var parsedCylinder = cylinders[index];
  19984. parseCylinder(parsedCylinder, scene);
  19985. }
  19986. }
  19987. // Toruses
  19988. var toruses = geometries.toruses;
  19989. if (toruses) {
  19990. for (index = 0; index < toruses.length; index++) {
  19991. var parsedTorus = toruses[index];
  19992. parseTorus(parsedTorus, scene);
  19993. }
  19994. }
  19995. // Grounds
  19996. var grounds = geometries.grounds;
  19997. if (grounds) {
  19998. for (index = 0; index < grounds.length; index++) {
  19999. var parsedGround = grounds[index];
  20000. parseGround(parsedGround, scene);
  20001. }
  20002. }
  20003. // Planes
  20004. var planes = geometries.planes;
  20005. if (planes) {
  20006. for (index = 0; index < planes.length; index++) {
  20007. var parsedPlane = planes[index];
  20008. parsePlane(parsedPlane, scene);
  20009. }
  20010. }
  20011. // TorusKnots
  20012. var torusKnots = geometries.torusKnots;
  20013. if (torusKnots) {
  20014. for (index = 0; index < torusKnots.length; index++) {
  20015. var parsedTorusKnot = torusKnots[index];
  20016. parseTorusKnot(parsedTorusKnot, scene);
  20017. }
  20018. }
  20019. // VertexData
  20020. var vertexData = geometries.vertexData;
  20021. if (vertexData) {
  20022. for (index = 0; index < vertexData.length; index++) {
  20023. var parsedVertexData = vertexData[index];
  20024. parseVertexData(parsedVertexData, scene, rootUrl);
  20025. }
  20026. }
  20027. }
  20028. // Meshes
  20029. for (index = 0; index < parsedData.meshes.length; index++) {
  20030. var parsedMesh = parsedData.meshes[index];
  20031. parseMesh(parsedMesh, scene, rootUrl);
  20032. }
  20033. // Cameras
  20034. for (index = 0; index < parsedData.cameras.length; index++) {
  20035. var parsedCamera = parsedData.cameras[index];
  20036. parseCamera(parsedCamera, scene);
  20037. }
  20038. if (parsedData.activeCameraID) {
  20039. scene.setActiveCameraByID(parsedData.activeCameraID);
  20040. }
  20041. // Browsing all the graph to connect the dots
  20042. for (index = 0; index < scene.cameras.length; index++) {
  20043. var camera = scene.cameras[index];
  20044. if (camera._waitingParentId) {
  20045. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20046. camera._waitingParentId = undefined;
  20047. }
  20048. }
  20049. for (index = 0; index < scene.lights.length; index++) {
  20050. var light = scene.lights[index];
  20051. if (light._waitingParentId) {
  20052. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20053. light._waitingParentId = undefined;
  20054. }
  20055. }
  20056. // Sounds
  20057. if (parsedData.sounds) {
  20058. for (index = 0; index < parsedData.sounds.length; index++) {
  20059. var parsedSound = parsedData.sounds[index];
  20060. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20061. parseSound(parsedSound, scene, rootUrl);
  20062. }
  20063. else {
  20064. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20065. }
  20066. }
  20067. }
  20068. // Connect parents & children and parse actions
  20069. for (index = 0; index < scene.meshes.length; index++) {
  20070. var mesh = scene.meshes[index];
  20071. if (mesh._waitingParentId) {
  20072. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20073. mesh._waitingParentId = undefined;
  20074. }
  20075. if (mesh._waitingActions) {
  20076. parseActions(mesh._waitingActions, mesh, scene);
  20077. mesh._waitingActions = undefined;
  20078. }
  20079. }
  20080. // Particles Systems
  20081. if (parsedData.particleSystems) {
  20082. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20083. var parsedParticleSystem = parsedData.particleSystems[index];
  20084. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20085. }
  20086. }
  20087. // Lens flares
  20088. if (parsedData.lensFlareSystems) {
  20089. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20090. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20091. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20092. }
  20093. }
  20094. // Shadows
  20095. if (parsedData.shadowGenerators) {
  20096. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20097. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20098. parseShadowGenerator(parsedShadowGenerator, scene);
  20099. }
  20100. }
  20101. // Actions (scene)
  20102. if (parsedData.actions) {
  20103. parseActions(parsedData.actions, null, scene);
  20104. }
  20105. // Finish
  20106. return true;
  20107. }
  20108. });
  20109. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20110. })(BABYLON || (BABYLON = {}));
  20111. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  20112. var BABYLON;
  20113. (function (BABYLON) {
  20114. var SpriteManager = (function () {
  20115. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20117. this.name = name;
  20118. this.cellSize = cellSize;
  20119. this.sprites = new Array();
  20120. this.renderingGroupId = 0;
  20121. this.fogEnabled = true;
  20122. this._vertexDeclaration = [4, 4, 4, 4];
  20123. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20124. this._capacity = capacity;
  20125. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20126. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20127. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20128. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20129. this._scene = scene;
  20130. this._scene.spriteManagers.push(this);
  20131. // VBO
  20132. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20133. var indices = [];
  20134. var index = 0;
  20135. for (var count = 0; count < capacity; count++) {
  20136. indices.push(index);
  20137. indices.push(index + 1);
  20138. indices.push(index + 2);
  20139. indices.push(index);
  20140. indices.push(index + 2);
  20141. indices.push(index + 3);
  20142. index += 4;
  20143. }
  20144. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20145. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20146. // Effects
  20147. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20148. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20149. }
  20150. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20151. var arrayOffset = index * 16;
  20152. if (offsetX === 0)
  20153. offsetX = this._epsilon;
  20154. else if (offsetX === 1)
  20155. offsetX = 1 - this._epsilon;
  20156. if (offsetY === 0)
  20157. offsetY = this._epsilon;
  20158. else if (offsetY === 1)
  20159. offsetY = 1 - this._epsilon;
  20160. this._vertices[arrayOffset] = sprite.position.x;
  20161. this._vertices[arrayOffset + 1] = sprite.position.y;
  20162. this._vertices[arrayOffset + 2] = sprite.position.z;
  20163. this._vertices[arrayOffset + 3] = sprite.angle;
  20164. this._vertices[arrayOffset + 4] = sprite.width;
  20165. this._vertices[arrayOffset + 5] = sprite.height;
  20166. this._vertices[arrayOffset + 6] = offsetX;
  20167. this._vertices[arrayOffset + 7] = offsetY;
  20168. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20169. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20170. var offset = (sprite.cellIndex / rowSize) >> 0;
  20171. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20172. this._vertices[arrayOffset + 11] = offset;
  20173. // Color
  20174. this._vertices[arrayOffset + 12] = sprite.color.r;
  20175. this._vertices[arrayOffset + 13] = sprite.color.g;
  20176. this._vertices[arrayOffset + 14] = sprite.color.b;
  20177. this._vertices[arrayOffset + 15] = sprite.color.a;
  20178. };
  20179. SpriteManager.prototype.render = function () {
  20180. // Check
  20181. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20182. return;
  20183. var engine = this._scene.getEngine();
  20184. var baseSize = this._spriteTexture.getBaseSize();
  20185. // Sprites
  20186. var deltaTime = engine.getDeltaTime();
  20187. var max = Math.min(this._capacity, this.sprites.length);
  20188. var rowSize = baseSize.width / this.cellSize;
  20189. var offset = 0;
  20190. for (var index = 0; index < max; index++) {
  20191. var sprite = this.sprites[index];
  20192. if (!sprite) {
  20193. continue;
  20194. }
  20195. sprite._animate(deltaTime);
  20196. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20197. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20198. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20199. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20200. }
  20201. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20202. // Render
  20203. var effect = this._effectBase;
  20204. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20205. effect = this._effectFog;
  20206. }
  20207. engine.enableEffect(effect);
  20208. var viewMatrix = this._scene.getViewMatrix();
  20209. effect.setTexture("diffuseSampler", this._spriteTexture);
  20210. effect.setMatrix("view", viewMatrix);
  20211. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20212. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20213. // Fog
  20214. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20215. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20216. effect.setColor3("vFogColor", this._scene.fogColor);
  20217. }
  20218. // VBOs
  20219. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20220. // Draw order
  20221. engine.setDepthFunctionToLessOrEqual();
  20222. effect.setBool("alphaTest", true);
  20223. engine.setColorWrite(false);
  20224. engine.draw(true, 0, max * 6);
  20225. engine.setColorWrite(true);
  20226. effect.setBool("alphaTest", false);
  20227. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20228. engine.draw(true, 0, max * 6);
  20229. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20230. };
  20231. SpriteManager.prototype.dispose = function () {
  20232. if (this._vertexBuffer) {
  20233. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20234. this._vertexBuffer = null;
  20235. }
  20236. if (this._indexBuffer) {
  20237. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20238. this._indexBuffer = null;
  20239. }
  20240. if (this._spriteTexture) {
  20241. this._spriteTexture.dispose();
  20242. this._spriteTexture = null;
  20243. }
  20244. // Remove from scene
  20245. var index = this._scene.spriteManagers.indexOf(this);
  20246. this._scene.spriteManagers.splice(index, 1);
  20247. // Callback
  20248. if (this.onDispose) {
  20249. this.onDispose();
  20250. }
  20251. };
  20252. return SpriteManager;
  20253. })();
  20254. BABYLON.SpriteManager = SpriteManager;
  20255. })(BABYLON || (BABYLON = {}));
  20256. //# sourceMappingURL=babylon.spriteManager.js.map
  20257. var BABYLON;
  20258. (function (BABYLON) {
  20259. var Sprite = (function () {
  20260. function Sprite(name, manager) {
  20261. this.name = name;
  20262. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20263. this.width = 1.0;
  20264. this.height = 1.0;
  20265. this.angle = 0;
  20266. this.cellIndex = 0;
  20267. this.invertU = 0;
  20268. this.invertV = 0;
  20269. this.animations = new Array();
  20270. this._animationStarted = false;
  20271. this._loopAnimation = false;
  20272. this._fromIndex = 0;
  20273. this._toIndex = 0;
  20274. this._delay = 0;
  20275. this._direction = 1;
  20276. this._frameCount = 0;
  20277. this._time = 0;
  20278. this._manager = manager;
  20279. this._manager.sprites.push(this);
  20280. this.position = BABYLON.Vector3.Zero();
  20281. }
  20282. Object.defineProperty(Sprite.prototype, "size", {
  20283. get: function () {
  20284. return this.width;
  20285. },
  20286. set: function (value) {
  20287. this.width = value;
  20288. this.height = value;
  20289. },
  20290. enumerable: true,
  20291. configurable: true
  20292. });
  20293. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20294. this._fromIndex = from;
  20295. this._toIndex = to;
  20296. this._loopAnimation = loop;
  20297. this._delay = delay;
  20298. this._animationStarted = true;
  20299. this._direction = from < to ? 1 : -1;
  20300. this.cellIndex = from;
  20301. this._time = 0;
  20302. };
  20303. Sprite.prototype.stopAnimation = function () {
  20304. this._animationStarted = false;
  20305. };
  20306. Sprite.prototype._animate = function (deltaTime) {
  20307. if (!this._animationStarted)
  20308. return;
  20309. this._time += deltaTime;
  20310. if (this._time > this._delay) {
  20311. this._time = this._time % this._delay;
  20312. this.cellIndex += this._direction;
  20313. if (this.cellIndex == this._toIndex) {
  20314. if (this._loopAnimation) {
  20315. this.cellIndex = this._fromIndex;
  20316. }
  20317. else {
  20318. this._animationStarted = false;
  20319. if (this.disposeWhenFinishedAnimating) {
  20320. this.dispose();
  20321. }
  20322. }
  20323. }
  20324. }
  20325. };
  20326. Sprite.prototype.dispose = function () {
  20327. for (var i = 0; i < this._manager.sprites.length; i++) {
  20328. if (this._manager.sprites[i] == this) {
  20329. this._manager.sprites.splice(i, 1);
  20330. }
  20331. }
  20332. };
  20333. return Sprite;
  20334. })();
  20335. BABYLON.Sprite = Sprite;
  20336. })(BABYLON || (BABYLON = {}));
  20337. //# sourceMappingURL=babylon.sprite.js.map
  20338. var BABYLON;
  20339. (function (BABYLON) {
  20340. var Layer = (function () {
  20341. function Layer(name, imgUrl, scene, isBackground, color) {
  20342. this.name = name;
  20343. this._vertexDeclaration = [2];
  20344. this._vertexStrideSize = 2 * 4;
  20345. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20346. this.isBackground = isBackground === undefined ? true : isBackground;
  20347. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20348. this._scene = scene;
  20349. this._scene.layers.push(this);
  20350. // VBO
  20351. var vertices = [];
  20352. vertices.push(1, 1);
  20353. vertices.push(-1, 1);
  20354. vertices.push(-1, -1);
  20355. vertices.push(1, -1);
  20356. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20357. // Indices
  20358. var indices = [];
  20359. indices.push(0);
  20360. indices.push(1);
  20361. indices.push(2);
  20362. indices.push(0);
  20363. indices.push(2);
  20364. indices.push(3);
  20365. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20366. // Effects
  20367. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20368. }
  20369. Layer.prototype.render = function () {
  20370. // Check
  20371. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20372. return;
  20373. var engine = this._scene.getEngine();
  20374. // Render
  20375. engine.enableEffect(this._effect);
  20376. engine.setState(false);
  20377. // Texture
  20378. this._effect.setTexture("textureSampler", this.texture);
  20379. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20380. // Color
  20381. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20382. // VBOs
  20383. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20384. // Draw order
  20385. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20386. engine.draw(true, 0, 6);
  20387. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20388. };
  20389. Layer.prototype.dispose = function () {
  20390. if (this._vertexBuffer) {
  20391. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20392. this._vertexBuffer = null;
  20393. }
  20394. if (this._indexBuffer) {
  20395. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20396. this._indexBuffer = null;
  20397. }
  20398. if (this.texture) {
  20399. this.texture.dispose();
  20400. this.texture = null;
  20401. }
  20402. // Remove from scene
  20403. var index = this._scene.layers.indexOf(this);
  20404. this._scene.layers.splice(index, 1);
  20405. // Callback
  20406. if (this.onDispose) {
  20407. this.onDispose();
  20408. }
  20409. };
  20410. return Layer;
  20411. })();
  20412. BABYLON.Layer = Layer;
  20413. })(BABYLON || (BABYLON = {}));
  20414. //# sourceMappingURL=babylon.layer.js.map
  20415. var BABYLON;
  20416. (function (BABYLON) {
  20417. var Particle = (function () {
  20418. function Particle() {
  20419. this.position = BABYLON.Vector3.Zero();
  20420. this.direction = BABYLON.Vector3.Zero();
  20421. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20422. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20423. this.lifeTime = 1.0;
  20424. this.age = 0;
  20425. this.size = 0;
  20426. this.angle = 0;
  20427. this.angularSpeed = 0;
  20428. }
  20429. Particle.prototype.copyTo = function (other) {
  20430. other.position.copyFrom(this.position);
  20431. other.direction.copyFrom(this.direction);
  20432. other.color.copyFrom(this.color);
  20433. other.colorStep.copyFrom(this.colorStep);
  20434. other.lifeTime = this.lifeTime;
  20435. other.age = this.age;
  20436. other.size = this.size;
  20437. other.angle = this.angle;
  20438. other.angularSpeed = this.angularSpeed;
  20439. };
  20440. return Particle;
  20441. })();
  20442. BABYLON.Particle = Particle;
  20443. })(BABYLON || (BABYLON = {}));
  20444. //# sourceMappingURL=babylon.particle.js.map
  20445. var BABYLON;
  20446. (function (BABYLON) {
  20447. var randomNumber = function (min, max) {
  20448. if (min === max) {
  20449. return (min);
  20450. }
  20451. var random = Math.random();
  20452. return ((random * (max - min)) + min);
  20453. };
  20454. var ParticleSystem = (function () {
  20455. function ParticleSystem(name, capacity, scene, customEffect) {
  20456. var _this = this;
  20457. this.name = name;
  20458. this.renderingGroupId = 0;
  20459. this.emitter = null;
  20460. this.emitRate = 10;
  20461. this.manualEmitCount = -1;
  20462. this.updateSpeed = 0.01;
  20463. this.targetStopDuration = 0;
  20464. this.disposeOnStop = false;
  20465. this.minEmitPower = 1;
  20466. this.maxEmitPower = 1;
  20467. this.minLifeTime = 1;
  20468. this.maxLifeTime = 1;
  20469. this.minSize = 1;
  20470. this.maxSize = 1;
  20471. this.minAngularSpeed = 0;
  20472. this.maxAngularSpeed = 0;
  20473. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20474. this.forceDepthWrite = false;
  20475. this.gravity = BABYLON.Vector3.Zero();
  20476. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20477. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20478. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20479. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20480. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20481. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20482. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20483. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20484. this.particles = new Array();
  20485. this._vertexDeclaration = [3, 4, 4];
  20486. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20487. this._stockParticles = new Array();
  20488. this._newPartsExcess = 0;
  20489. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20490. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20491. this._scaledDirection = BABYLON.Vector3.Zero();
  20492. this._scaledGravity = BABYLON.Vector3.Zero();
  20493. this._currentRenderId = -1;
  20494. this._started = false;
  20495. this._stopped = false;
  20496. this._actualFrame = 0;
  20497. this.id = name;
  20498. this._capacity = capacity;
  20499. this._scene = scene;
  20500. this._customEffect = customEffect;
  20501. scene.particleSystems.push(this);
  20502. // VBO
  20503. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20504. var indices = [];
  20505. var index = 0;
  20506. for (var count = 0; count < capacity; count++) {
  20507. indices.push(index);
  20508. indices.push(index + 1);
  20509. indices.push(index + 2);
  20510. indices.push(index);
  20511. indices.push(index + 2);
  20512. indices.push(index + 3);
  20513. index += 4;
  20514. }
  20515. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20516. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20517. // Default behaviors
  20518. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20519. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20520. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20521. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20522. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20523. };
  20524. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20525. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20526. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20527. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20528. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20529. };
  20530. this.updateFunction = function (particles) {
  20531. for (var index = 0; index < particles.length; index++) {
  20532. var particle = particles[index];
  20533. particle.age += _this._scaledUpdateSpeed;
  20534. if (particle.age >= particle.lifeTime) {
  20535. _this.recycleParticle(particle);
  20536. index--;
  20537. continue;
  20538. }
  20539. else {
  20540. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20541. particle.color.addInPlace(_this._scaledColorStep);
  20542. if (particle.color.a < 0)
  20543. particle.color.a = 0;
  20544. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20545. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20546. particle.position.addInPlace(_this._scaledDirection);
  20547. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20548. particle.direction.addInPlace(_this._scaledGravity);
  20549. }
  20550. }
  20551. };
  20552. }
  20553. ParticleSystem.prototype.recycleParticle = function (particle) {
  20554. var lastParticle = this.particles.pop();
  20555. if (lastParticle !== particle) {
  20556. lastParticle.copyTo(particle);
  20557. this._stockParticles.push(lastParticle);
  20558. }
  20559. };
  20560. ParticleSystem.prototype.getCapacity = function () {
  20561. return this._capacity;
  20562. };
  20563. ParticleSystem.prototype.isAlive = function () {
  20564. return this._alive;
  20565. };
  20566. ParticleSystem.prototype.isStarted = function () {
  20567. return this._started;
  20568. };
  20569. ParticleSystem.prototype.start = function () {
  20570. this._started = true;
  20571. this._stopped = false;
  20572. this._actualFrame = 0;
  20573. };
  20574. ParticleSystem.prototype.stop = function () {
  20575. this._stopped = true;
  20576. };
  20577. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20578. var offset = index * 11;
  20579. this._vertices[offset] = particle.position.x;
  20580. this._vertices[offset + 1] = particle.position.y;
  20581. this._vertices[offset + 2] = particle.position.z;
  20582. this._vertices[offset + 3] = particle.color.r;
  20583. this._vertices[offset + 4] = particle.color.g;
  20584. this._vertices[offset + 5] = particle.color.b;
  20585. this._vertices[offset + 6] = particle.color.a;
  20586. this._vertices[offset + 7] = particle.angle;
  20587. this._vertices[offset + 8] = particle.size;
  20588. this._vertices[offset + 9] = offsetX;
  20589. this._vertices[offset + 10] = offsetY;
  20590. };
  20591. ParticleSystem.prototype._update = function (newParticles) {
  20592. // Update current
  20593. this._alive = this.particles.length > 0;
  20594. this.updateFunction(this.particles);
  20595. // Add new ones
  20596. var worldMatrix;
  20597. if (this.emitter.position) {
  20598. worldMatrix = this.emitter.getWorldMatrix();
  20599. }
  20600. else {
  20601. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20602. }
  20603. for (var index = 0; index < newParticles; index++) {
  20604. if (this.particles.length === this._capacity) {
  20605. break;
  20606. }
  20607. if (this._stockParticles.length !== 0) {
  20608. var particle = this._stockParticles.pop();
  20609. particle.age = 0;
  20610. }
  20611. else {
  20612. particle = new BABYLON.Particle();
  20613. }
  20614. this.particles.push(particle);
  20615. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20616. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20617. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20618. particle.size = randomNumber(this.minSize, this.maxSize);
  20619. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20620. this.startPositionFunction(worldMatrix, particle.position);
  20621. var step = randomNumber(0, 1.0);
  20622. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20623. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20624. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20625. }
  20626. };
  20627. ParticleSystem.prototype._getEffect = function () {
  20628. if (this._customEffect) {
  20629. return this._customEffect;
  20630. }
  20631. ;
  20632. var defines = [];
  20633. if (this._scene.clipPlane) {
  20634. defines.push("#define CLIPPLANE");
  20635. }
  20636. // Effect
  20637. var join = defines.join("\n");
  20638. if (this._cachedDefines !== join) {
  20639. this._cachedDefines = join;
  20640. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20641. }
  20642. return this._effect;
  20643. };
  20644. ParticleSystem.prototype.animate = function () {
  20645. if (!this._started)
  20646. return;
  20647. var effect = this._getEffect();
  20648. // Check
  20649. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20650. return;
  20651. if (this._currentRenderId === this._scene.getRenderId()) {
  20652. return;
  20653. }
  20654. this._currentRenderId = this._scene.getRenderId();
  20655. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20656. // determine the number of particles we need to create
  20657. var emitCout;
  20658. if (this.manualEmitCount > -1) {
  20659. emitCout = this.manualEmitCount;
  20660. this.manualEmitCount = 0;
  20661. }
  20662. else {
  20663. emitCout = this.emitRate;
  20664. }
  20665. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20666. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20667. if (this._newPartsExcess > 1.0) {
  20668. newParticles += this._newPartsExcess >> 0;
  20669. this._newPartsExcess -= this._newPartsExcess >> 0;
  20670. }
  20671. this._alive = false;
  20672. if (!this._stopped) {
  20673. this._actualFrame += this._scaledUpdateSpeed;
  20674. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20675. this.stop();
  20676. }
  20677. else {
  20678. newParticles = 0;
  20679. }
  20680. this._update(newParticles);
  20681. // Stopped?
  20682. if (this._stopped) {
  20683. if (!this._alive) {
  20684. this._started = false;
  20685. if (this.disposeOnStop) {
  20686. this._scene._toBeDisposed.push(this);
  20687. }
  20688. }
  20689. }
  20690. // Update VBO
  20691. var offset = 0;
  20692. for (var index = 0; index < this.particles.length; index++) {
  20693. var particle = this.particles[index];
  20694. this._appendParticleVertex(offset++, particle, 0, 0);
  20695. this._appendParticleVertex(offset++, particle, 1, 0);
  20696. this._appendParticleVertex(offset++, particle, 1, 1);
  20697. this._appendParticleVertex(offset++, particle, 0, 1);
  20698. }
  20699. var engine = this._scene.getEngine();
  20700. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20701. };
  20702. ParticleSystem.prototype.render = function () {
  20703. var effect = this._getEffect();
  20704. // Check
  20705. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20706. return 0;
  20707. var engine = this._scene.getEngine();
  20708. // Render
  20709. engine.enableEffect(effect);
  20710. engine.setState(false);
  20711. var viewMatrix = this._scene.getViewMatrix();
  20712. effect.setTexture("diffuseSampler", this.particleTexture);
  20713. effect.setMatrix("view", viewMatrix);
  20714. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20715. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20716. if (this._scene.clipPlane) {
  20717. var clipPlane = this._scene.clipPlane;
  20718. var invView = viewMatrix.clone();
  20719. invView.invert();
  20720. effect.setMatrix("invView", invView);
  20721. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20722. }
  20723. // VBOs
  20724. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20725. // Draw order
  20726. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20727. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20728. }
  20729. else {
  20730. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20731. }
  20732. if (this.forceDepthWrite) {
  20733. engine.setDepthWrite(true);
  20734. }
  20735. engine.draw(true, 0, this.particles.length * 6);
  20736. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20737. return this.particles.length;
  20738. };
  20739. ParticleSystem.prototype.dispose = function () {
  20740. if (this._vertexBuffer) {
  20741. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20742. this._vertexBuffer = null;
  20743. }
  20744. if (this._indexBuffer) {
  20745. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20746. this._indexBuffer = null;
  20747. }
  20748. if (this.particleTexture) {
  20749. this.particleTexture.dispose();
  20750. this.particleTexture = null;
  20751. }
  20752. // Remove from scene
  20753. var index = this._scene.particleSystems.indexOf(this);
  20754. this._scene.particleSystems.splice(index, 1);
  20755. // Callback
  20756. if (this.onDispose) {
  20757. this.onDispose();
  20758. }
  20759. };
  20760. // Clone
  20761. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20762. var result = new ParticleSystem(name, this._capacity, this._scene);
  20763. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20764. if (newEmitter === undefined) {
  20765. newEmitter = this.emitter;
  20766. }
  20767. result.emitter = newEmitter;
  20768. if (this.particleTexture) {
  20769. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20770. }
  20771. result.start();
  20772. return result;
  20773. };
  20774. // Statics
  20775. ParticleSystem.BLENDMODE_ONEONE = 0;
  20776. ParticleSystem.BLENDMODE_STANDARD = 1;
  20777. return ParticleSystem;
  20778. })();
  20779. BABYLON.ParticleSystem = ParticleSystem;
  20780. })(BABYLON || (BABYLON = {}));
  20781. //# sourceMappingURL=babylon.particleSystem.js.map
  20782. var BABYLON;
  20783. (function (BABYLON) {
  20784. var Animation = (function () {
  20785. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20786. this.name = name;
  20787. this.targetProperty = targetProperty;
  20788. this.framePerSecond = framePerSecond;
  20789. this.dataType = dataType;
  20790. this.loopMode = loopMode;
  20791. this._offsetsCache = {};
  20792. this._highLimitsCache = {};
  20793. this._stopped = false;
  20794. this.targetPropertyPath = targetProperty.split(".");
  20795. this.dataType = dataType;
  20796. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20797. }
  20798. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20799. var dataType = undefined;
  20800. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20801. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20802. }
  20803. else if (from instanceof BABYLON.Quaternion) {
  20804. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20805. }
  20806. else if (from instanceof BABYLON.Vector3) {
  20807. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20808. }
  20809. else if (from instanceof BABYLON.Vector2) {
  20810. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20811. }
  20812. else if (from instanceof BABYLON.Color3) {
  20813. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20814. }
  20815. if (dataType == undefined) {
  20816. return null;
  20817. }
  20818. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20819. var keys = [];
  20820. keys.push({ frame: 0, value: from });
  20821. keys.push({ frame: totalFrame, value: to });
  20822. animation.setKeys(keys);
  20823. mesh.animations.push(animation);
  20824. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20825. };
  20826. // Methods
  20827. Animation.prototype.isStopped = function () {
  20828. return this._stopped;
  20829. };
  20830. Animation.prototype.getKeys = function () {
  20831. return this._keys;
  20832. };
  20833. Animation.prototype.getEasingFunction = function () {
  20834. return this._easingFunction;
  20835. };
  20836. Animation.prototype.setEasingFunction = function (easingFunction) {
  20837. this._easingFunction = easingFunction;
  20838. };
  20839. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20840. return startValue + (endValue - startValue) * gradient;
  20841. };
  20842. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20843. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20844. };
  20845. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20846. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20847. };
  20848. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20849. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20850. };
  20851. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20852. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20853. };
  20854. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20855. var startScale = new BABYLON.Vector3(0, 0, 0);
  20856. var startRotation = new BABYLON.Quaternion();
  20857. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20858. startValue.decompose(startScale, startRotation, startTranslation);
  20859. var endScale = new BABYLON.Vector3(0, 0, 0);
  20860. var endRotation = new BABYLON.Quaternion();
  20861. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20862. endValue.decompose(endScale, endRotation, endTranslation);
  20863. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20864. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20865. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20866. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20867. return result;
  20868. };
  20869. Animation.prototype.clone = function () {
  20870. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20871. clone.setKeys(this._keys);
  20872. return clone;
  20873. };
  20874. Animation.prototype.setKeys = function (values) {
  20875. this._keys = values.slice(0);
  20876. this._offsetsCache = {};
  20877. this._highLimitsCache = {};
  20878. };
  20879. Animation.prototype._getKeyValue = function (value) {
  20880. if (typeof value === "function") {
  20881. return value();
  20882. }
  20883. return value;
  20884. };
  20885. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20886. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20887. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20888. }
  20889. this.currentFrame = currentFrame;
  20890. // Try to get a hash to find the right key
  20891. 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));
  20892. if (this._keys[startKey].frame >= currentFrame) {
  20893. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20894. startKey--;
  20895. }
  20896. }
  20897. for (var key = startKey; key < this._keys.length; key++) {
  20898. if (this._keys[key + 1].frame >= currentFrame) {
  20899. var startValue = this._getKeyValue(this._keys[key].value);
  20900. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20901. // gradient : percent of currentFrame between the frame inf and the frame sup
  20902. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20903. // check for easingFunction and correction of gradient
  20904. if (this._easingFunction != null) {
  20905. gradient = this._easingFunction.ease(gradient);
  20906. }
  20907. switch (this.dataType) {
  20908. // Float
  20909. case Animation.ANIMATIONTYPE_FLOAT:
  20910. switch (loopMode) {
  20911. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20912. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20913. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20914. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20915. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20916. }
  20917. break;
  20918. // Quaternion
  20919. case Animation.ANIMATIONTYPE_QUATERNION:
  20920. var quaternion = null;
  20921. switch (loopMode) {
  20922. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20923. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20924. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20925. break;
  20926. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20927. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20928. break;
  20929. }
  20930. return quaternion;
  20931. // Vector3
  20932. case Animation.ANIMATIONTYPE_VECTOR3:
  20933. switch (loopMode) {
  20934. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20935. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20936. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20937. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20938. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20939. }
  20940. // Vector2
  20941. case Animation.ANIMATIONTYPE_VECTOR2:
  20942. switch (loopMode) {
  20943. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20944. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20945. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20946. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20947. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20948. }
  20949. // Color3
  20950. case Animation.ANIMATIONTYPE_COLOR3:
  20951. switch (loopMode) {
  20952. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20953. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20954. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20955. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20956. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20957. }
  20958. // Matrix
  20959. case Animation.ANIMATIONTYPE_MATRIX:
  20960. switch (loopMode) {
  20961. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20962. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20963. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  20964. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20965. return startValue;
  20966. }
  20967. default:
  20968. break;
  20969. }
  20970. break;
  20971. }
  20972. }
  20973. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20974. };
  20975. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20976. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20977. this._stopped = true;
  20978. return false;
  20979. }
  20980. var returnValue = true;
  20981. // Adding a start key at frame 0 if missing
  20982. if (this._keys[0].frame !== 0) {
  20983. var newKey = { frame: 0, value: this._keys[0].value };
  20984. this._keys.splice(0, 0, newKey);
  20985. }
  20986. // Check limits
  20987. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20988. from = this._keys[0].frame;
  20989. }
  20990. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20991. to = this._keys[this._keys.length - 1].frame;
  20992. }
  20993. // Compute ratio
  20994. var range = to - from;
  20995. var offsetValue;
  20996. // ratio represents the frame delta between from and to
  20997. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20998. var highLimitValue = 0;
  20999. if (ratio > range && !loop) {
  21000. returnValue = false;
  21001. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21002. }
  21003. else {
  21004. // Get max value if required
  21005. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21006. var keyOffset = to.toString() + from.toString();
  21007. if (!this._offsetsCache[keyOffset]) {
  21008. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21009. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21010. switch (this.dataType) {
  21011. // Float
  21012. case Animation.ANIMATIONTYPE_FLOAT:
  21013. this._offsetsCache[keyOffset] = toValue - fromValue;
  21014. break;
  21015. // Quaternion
  21016. case Animation.ANIMATIONTYPE_QUATERNION:
  21017. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21018. break;
  21019. // Vector3
  21020. case Animation.ANIMATIONTYPE_VECTOR3:
  21021. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21022. // Vector2
  21023. case Animation.ANIMATIONTYPE_VECTOR2:
  21024. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21025. // Color3
  21026. case Animation.ANIMATIONTYPE_COLOR3:
  21027. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21028. default:
  21029. break;
  21030. }
  21031. this._highLimitsCache[keyOffset] = toValue;
  21032. }
  21033. highLimitValue = this._highLimitsCache[keyOffset];
  21034. offsetValue = this._offsetsCache[keyOffset];
  21035. }
  21036. }
  21037. if (offsetValue === undefined) {
  21038. switch (this.dataType) {
  21039. // Float
  21040. case Animation.ANIMATIONTYPE_FLOAT:
  21041. offsetValue = 0;
  21042. break;
  21043. // Quaternion
  21044. case Animation.ANIMATIONTYPE_QUATERNION:
  21045. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21046. break;
  21047. // Vector3
  21048. case Animation.ANIMATIONTYPE_VECTOR3:
  21049. offsetValue = BABYLON.Vector3.Zero();
  21050. break;
  21051. // Vector2
  21052. case Animation.ANIMATIONTYPE_VECTOR2:
  21053. offsetValue = BABYLON.Vector2.Zero();
  21054. break;
  21055. // Color3
  21056. case Animation.ANIMATIONTYPE_COLOR3:
  21057. offsetValue = BABYLON.Color3.Black();
  21058. }
  21059. }
  21060. // Compute value
  21061. var repeatCount = (ratio / range) >> 0;
  21062. var currentFrame = returnValue ? from + ratio % range : to;
  21063. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21064. // Set value
  21065. if (this.targetPropertyPath.length > 1) {
  21066. var property = this._target[this.targetPropertyPath[0]];
  21067. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21068. property = property[this.targetPropertyPath[index]];
  21069. }
  21070. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21071. }
  21072. else {
  21073. this._target[this.targetPropertyPath[0]] = currentValue;
  21074. }
  21075. if (this._target.markAsDirty) {
  21076. this._target.markAsDirty(this.targetProperty);
  21077. }
  21078. if (!returnValue) {
  21079. this._stopped = true;
  21080. }
  21081. return returnValue;
  21082. };
  21083. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21084. get: function () {
  21085. return Animation._ANIMATIONTYPE_FLOAT;
  21086. },
  21087. enumerable: true,
  21088. configurable: true
  21089. });
  21090. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21091. get: function () {
  21092. return Animation._ANIMATIONTYPE_VECTOR3;
  21093. },
  21094. enumerable: true,
  21095. configurable: true
  21096. });
  21097. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21098. get: function () {
  21099. return Animation._ANIMATIONTYPE_VECTOR2;
  21100. },
  21101. enumerable: true,
  21102. configurable: true
  21103. });
  21104. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21105. get: function () {
  21106. return Animation._ANIMATIONTYPE_QUATERNION;
  21107. },
  21108. enumerable: true,
  21109. configurable: true
  21110. });
  21111. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21112. get: function () {
  21113. return Animation._ANIMATIONTYPE_MATRIX;
  21114. },
  21115. enumerable: true,
  21116. configurable: true
  21117. });
  21118. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21119. get: function () {
  21120. return Animation._ANIMATIONTYPE_COLOR3;
  21121. },
  21122. enumerable: true,
  21123. configurable: true
  21124. });
  21125. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21126. get: function () {
  21127. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21128. },
  21129. enumerable: true,
  21130. configurable: true
  21131. });
  21132. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21133. get: function () {
  21134. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21135. },
  21136. enumerable: true,
  21137. configurable: true
  21138. });
  21139. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21140. get: function () {
  21141. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21142. },
  21143. enumerable: true,
  21144. configurable: true
  21145. });
  21146. // Statics
  21147. Animation._ANIMATIONTYPE_FLOAT = 0;
  21148. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21149. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21150. Animation._ANIMATIONTYPE_MATRIX = 3;
  21151. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21152. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21153. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21154. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21155. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21156. return Animation;
  21157. })();
  21158. BABYLON.Animation = Animation;
  21159. })(BABYLON || (BABYLON = {}));
  21160. //# sourceMappingURL=babylon.animation.js.map
  21161. var BABYLON;
  21162. (function (BABYLON) {
  21163. var Animatable = (function () {
  21164. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21165. if (fromFrame === void 0) { fromFrame = 0; }
  21166. if (toFrame === void 0) { toFrame = 100; }
  21167. if (loopAnimation === void 0) { loopAnimation = false; }
  21168. if (speedRatio === void 0) { speedRatio = 1.0; }
  21169. this.target = target;
  21170. this.fromFrame = fromFrame;
  21171. this.toFrame = toFrame;
  21172. this.loopAnimation = loopAnimation;
  21173. this.speedRatio = speedRatio;
  21174. this.onAnimationEnd = onAnimationEnd;
  21175. this._animations = new Array();
  21176. this._paused = false;
  21177. this.animationStarted = false;
  21178. if (animations) {
  21179. this.appendAnimations(target, animations);
  21180. }
  21181. this._scene = scene;
  21182. scene._activeAnimatables.push(this);
  21183. }
  21184. // Methods
  21185. Animatable.prototype.appendAnimations = function (target, animations) {
  21186. for (var index = 0; index < animations.length; index++) {
  21187. var animation = animations[index];
  21188. animation._target = target;
  21189. this._animations.push(animation);
  21190. }
  21191. };
  21192. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21193. var animations = this._animations;
  21194. for (var index = 0; index < animations.length; index++) {
  21195. if (animations[index].targetProperty === property) {
  21196. return animations[index];
  21197. }
  21198. }
  21199. return null;
  21200. };
  21201. Animatable.prototype.pause = function () {
  21202. if (this._paused) {
  21203. return;
  21204. }
  21205. this._paused = true;
  21206. };
  21207. Animatable.prototype.restart = function () {
  21208. this._paused = false;
  21209. };
  21210. Animatable.prototype.stop = function () {
  21211. var index = this._scene._activeAnimatables.indexOf(this);
  21212. if (index > -1) {
  21213. this._scene._activeAnimatables.splice(index, 1);
  21214. }
  21215. if (this.onAnimationEnd) {
  21216. this.onAnimationEnd();
  21217. }
  21218. };
  21219. Animatable.prototype._animate = function (delay) {
  21220. if (this._paused) {
  21221. if (!this._pausedDelay) {
  21222. this._pausedDelay = delay;
  21223. }
  21224. return true;
  21225. }
  21226. if (!this._localDelayOffset) {
  21227. this._localDelayOffset = delay;
  21228. }
  21229. else if (this._pausedDelay) {
  21230. this._localDelayOffset += delay - this._pausedDelay;
  21231. this._pausedDelay = null;
  21232. }
  21233. // Animating
  21234. var running = false;
  21235. var animations = this._animations;
  21236. for (var index = 0; index < animations.length; index++) {
  21237. var animation = animations[index];
  21238. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21239. running = running || isRunning;
  21240. }
  21241. if (!running) {
  21242. // Remove from active animatables
  21243. index = this._scene._activeAnimatables.indexOf(this);
  21244. this._scene._activeAnimatables.splice(index, 1);
  21245. }
  21246. if (!running && this.onAnimationEnd) {
  21247. this.onAnimationEnd();
  21248. }
  21249. return running;
  21250. };
  21251. return Animatable;
  21252. })();
  21253. BABYLON.Animatable = Animatable;
  21254. })(BABYLON || (BABYLON = {}));
  21255. //# sourceMappingURL=babylon.animatable.js.map
  21256. var __extends = (this && this.__extends) || function (d, b) {
  21257. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21258. function __() { this.constructor = d; }
  21259. __.prototype = b.prototype;
  21260. d.prototype = new __();
  21261. };
  21262. var BABYLON;
  21263. (function (BABYLON) {
  21264. var EasingFunction = (function () {
  21265. function EasingFunction() {
  21266. // Properties
  21267. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21268. }
  21269. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21270. get: function () {
  21271. return EasingFunction._EASINGMODE_EASEIN;
  21272. },
  21273. enumerable: true,
  21274. configurable: true
  21275. });
  21276. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21277. get: function () {
  21278. return EasingFunction._EASINGMODE_EASEOUT;
  21279. },
  21280. enumerable: true,
  21281. configurable: true
  21282. });
  21283. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21284. get: function () {
  21285. return EasingFunction._EASINGMODE_EASEINOUT;
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21291. var n = Math.min(Math.max(easingMode, 0), 2);
  21292. this._easingMode = n;
  21293. };
  21294. EasingFunction.prototype.getEasingMode = function () {
  21295. return this._easingMode;
  21296. };
  21297. EasingFunction.prototype.easeInCore = function (gradient) {
  21298. throw new Error('You must implement this method');
  21299. };
  21300. EasingFunction.prototype.ease = function (gradient) {
  21301. switch (this._easingMode) {
  21302. case EasingFunction.EASINGMODE_EASEIN:
  21303. return this.easeInCore(gradient);
  21304. case EasingFunction.EASINGMODE_EASEOUT:
  21305. return (1 - this.easeInCore(1 - gradient));
  21306. }
  21307. if (gradient >= 0.5) {
  21308. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21309. }
  21310. return (this.easeInCore(gradient * 2) * 0.5);
  21311. };
  21312. //Statics
  21313. EasingFunction._EASINGMODE_EASEIN = 0;
  21314. EasingFunction._EASINGMODE_EASEOUT = 1;
  21315. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21316. return EasingFunction;
  21317. })();
  21318. BABYLON.EasingFunction = EasingFunction;
  21319. var CircleEase = (function (_super) {
  21320. __extends(CircleEase, _super);
  21321. function CircleEase() {
  21322. _super.apply(this, arguments);
  21323. }
  21324. CircleEase.prototype.easeInCore = function (gradient) {
  21325. gradient = Math.max(0, Math.min(1, gradient));
  21326. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21327. };
  21328. return CircleEase;
  21329. })(EasingFunction);
  21330. BABYLON.CircleEase = CircleEase;
  21331. var BackEase = (function (_super) {
  21332. __extends(BackEase, _super);
  21333. function BackEase(amplitude) {
  21334. if (amplitude === void 0) { amplitude = 1; }
  21335. _super.call(this);
  21336. this.amplitude = amplitude;
  21337. }
  21338. BackEase.prototype.easeInCore = function (gradient) {
  21339. var num = Math.max(0, this.amplitude);
  21340. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21341. };
  21342. return BackEase;
  21343. })(EasingFunction);
  21344. BABYLON.BackEase = BackEase;
  21345. var BounceEase = (function (_super) {
  21346. __extends(BounceEase, _super);
  21347. function BounceEase(bounces, bounciness) {
  21348. if (bounces === void 0) { bounces = 3; }
  21349. if (bounciness === void 0) { bounciness = 2; }
  21350. _super.call(this);
  21351. this.bounces = bounces;
  21352. this.bounciness = bounciness;
  21353. }
  21354. BounceEase.prototype.easeInCore = function (gradient) {
  21355. var y = Math.max(0.0, this.bounces);
  21356. var bounciness = this.bounciness;
  21357. if (bounciness <= 1.0) {
  21358. bounciness = 1.001;
  21359. }
  21360. var num9 = Math.pow(bounciness, y);
  21361. var num5 = 1.0 - bounciness;
  21362. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21363. var num15 = gradient * num4;
  21364. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21365. var num3 = Math.floor(num65);
  21366. var num13 = num3 + 1.0;
  21367. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21368. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21369. var num7 = (num8 + num12) * 0.5;
  21370. var num6 = gradient - num7;
  21371. var num2 = num7 - num8;
  21372. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21373. };
  21374. return BounceEase;
  21375. })(EasingFunction);
  21376. BABYLON.BounceEase = BounceEase;
  21377. var CubicEase = (function (_super) {
  21378. __extends(CubicEase, _super);
  21379. function CubicEase() {
  21380. _super.apply(this, arguments);
  21381. }
  21382. CubicEase.prototype.easeInCore = function (gradient) {
  21383. return (gradient * gradient * gradient);
  21384. };
  21385. return CubicEase;
  21386. })(EasingFunction);
  21387. BABYLON.CubicEase = CubicEase;
  21388. var ElasticEase = (function (_super) {
  21389. __extends(ElasticEase, _super);
  21390. function ElasticEase(oscillations, springiness) {
  21391. if (oscillations === void 0) { oscillations = 3; }
  21392. if (springiness === void 0) { springiness = 3; }
  21393. _super.call(this);
  21394. this.oscillations = oscillations;
  21395. this.springiness = springiness;
  21396. }
  21397. ElasticEase.prototype.easeInCore = function (gradient) {
  21398. var num2;
  21399. var num3 = Math.max(0.0, this.oscillations);
  21400. var num = Math.max(0.0, this.springiness);
  21401. if (num == 0) {
  21402. num2 = gradient;
  21403. }
  21404. else {
  21405. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21406. }
  21407. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21408. };
  21409. return ElasticEase;
  21410. })(EasingFunction);
  21411. BABYLON.ElasticEase = ElasticEase;
  21412. var ExponentialEase = (function (_super) {
  21413. __extends(ExponentialEase, _super);
  21414. function ExponentialEase(exponent) {
  21415. if (exponent === void 0) { exponent = 2; }
  21416. _super.call(this);
  21417. this.exponent = exponent;
  21418. }
  21419. ExponentialEase.prototype.easeInCore = function (gradient) {
  21420. if (this.exponent <= 0) {
  21421. return gradient;
  21422. }
  21423. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21424. };
  21425. return ExponentialEase;
  21426. })(EasingFunction);
  21427. BABYLON.ExponentialEase = ExponentialEase;
  21428. var PowerEase = (function (_super) {
  21429. __extends(PowerEase, _super);
  21430. function PowerEase(power) {
  21431. if (power === void 0) { power = 2; }
  21432. _super.call(this);
  21433. this.power = power;
  21434. }
  21435. PowerEase.prototype.easeInCore = function (gradient) {
  21436. var y = Math.max(0.0, this.power);
  21437. return Math.pow(gradient, y);
  21438. };
  21439. return PowerEase;
  21440. })(EasingFunction);
  21441. BABYLON.PowerEase = PowerEase;
  21442. var QuadraticEase = (function (_super) {
  21443. __extends(QuadraticEase, _super);
  21444. function QuadraticEase() {
  21445. _super.apply(this, arguments);
  21446. }
  21447. QuadraticEase.prototype.easeInCore = function (gradient) {
  21448. return (gradient * gradient);
  21449. };
  21450. return QuadraticEase;
  21451. })(EasingFunction);
  21452. BABYLON.QuadraticEase = QuadraticEase;
  21453. var QuarticEase = (function (_super) {
  21454. __extends(QuarticEase, _super);
  21455. function QuarticEase() {
  21456. _super.apply(this, arguments);
  21457. }
  21458. QuarticEase.prototype.easeInCore = function (gradient) {
  21459. return (gradient * gradient * gradient * gradient);
  21460. };
  21461. return QuarticEase;
  21462. })(EasingFunction);
  21463. BABYLON.QuarticEase = QuarticEase;
  21464. var QuinticEase = (function (_super) {
  21465. __extends(QuinticEase, _super);
  21466. function QuinticEase() {
  21467. _super.apply(this, arguments);
  21468. }
  21469. QuinticEase.prototype.easeInCore = function (gradient) {
  21470. return (gradient * gradient * gradient * gradient * gradient);
  21471. };
  21472. return QuinticEase;
  21473. })(EasingFunction);
  21474. BABYLON.QuinticEase = QuinticEase;
  21475. var SineEase = (function (_super) {
  21476. __extends(SineEase, _super);
  21477. function SineEase() {
  21478. _super.apply(this, arguments);
  21479. }
  21480. SineEase.prototype.easeInCore = function (gradient) {
  21481. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21482. };
  21483. return SineEase;
  21484. })(EasingFunction);
  21485. BABYLON.SineEase = SineEase;
  21486. var BezierCurveEase = (function (_super) {
  21487. __extends(BezierCurveEase, _super);
  21488. function BezierCurveEase(x1, y1, x2, y2) {
  21489. if (x1 === void 0) { x1 = 0; }
  21490. if (y1 === void 0) { y1 = 0; }
  21491. if (x2 === void 0) { x2 = 1; }
  21492. if (y2 === void 0) { y2 = 1; }
  21493. _super.call(this);
  21494. this.x1 = x1;
  21495. this.y1 = y1;
  21496. this.x2 = x2;
  21497. this.y2 = y2;
  21498. }
  21499. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21500. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21501. };
  21502. return BezierCurveEase;
  21503. })(EasingFunction);
  21504. BABYLON.BezierCurveEase = BezierCurveEase;
  21505. })(BABYLON || (BABYLON = {}));
  21506. //# sourceMappingURL=babylon.easing.js.map
  21507. var BABYLON;
  21508. (function (BABYLON) {
  21509. var Octree = (function () {
  21510. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21511. if (maxDepth === void 0) { maxDepth = 2; }
  21512. this.maxDepth = maxDepth;
  21513. this.dynamicContent = new Array();
  21514. this._maxBlockCapacity = maxBlockCapacity || 64;
  21515. this._selectionContent = new BABYLON.SmartArray(1024);
  21516. this._creationFunc = creationFunc;
  21517. }
  21518. // Methods
  21519. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21520. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21521. };
  21522. Octree.prototype.addMesh = function (entry) {
  21523. for (var index = 0; index < this.blocks.length; index++) {
  21524. var block = this.blocks[index];
  21525. block.addEntry(entry);
  21526. }
  21527. };
  21528. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21529. this._selectionContent.reset();
  21530. for (var index = 0; index < this.blocks.length; index++) {
  21531. var block = this.blocks[index];
  21532. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21533. }
  21534. if (allowDuplicate) {
  21535. this._selectionContent.concat(this.dynamicContent);
  21536. }
  21537. else {
  21538. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21539. }
  21540. return this._selectionContent;
  21541. };
  21542. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21543. this._selectionContent.reset();
  21544. for (var index = 0; index < this.blocks.length; index++) {
  21545. var block = this.blocks[index];
  21546. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21547. }
  21548. if (allowDuplicate) {
  21549. this._selectionContent.concat(this.dynamicContent);
  21550. }
  21551. else {
  21552. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21553. }
  21554. return this._selectionContent;
  21555. };
  21556. Octree.prototype.intersectsRay = function (ray) {
  21557. this._selectionContent.reset();
  21558. for (var index = 0; index < this.blocks.length; index++) {
  21559. var block = this.blocks[index];
  21560. block.intersectsRay(ray, this._selectionContent);
  21561. }
  21562. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21563. return this._selectionContent;
  21564. };
  21565. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21566. target.blocks = new Array();
  21567. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21568. // Segmenting space
  21569. for (var x = 0; x < 2; x++) {
  21570. for (var y = 0; y < 2; y++) {
  21571. for (var z = 0; z < 2; z++) {
  21572. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21573. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21574. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21575. block.addEntries(entries);
  21576. target.blocks.push(block);
  21577. }
  21578. }
  21579. }
  21580. };
  21581. Octree.CreationFuncForMeshes = function (entry, block) {
  21582. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21583. block.entries.push(entry);
  21584. }
  21585. };
  21586. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21587. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21588. block.entries.push(entry);
  21589. }
  21590. };
  21591. return Octree;
  21592. })();
  21593. BABYLON.Octree = Octree;
  21594. })(BABYLON || (BABYLON = {}));
  21595. //# sourceMappingURL=babylon.octree.js.map
  21596. var BABYLON;
  21597. (function (BABYLON) {
  21598. var OctreeBlock = (function () {
  21599. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21600. this.entries = new Array();
  21601. this._boundingVectors = new Array();
  21602. this._capacity = capacity;
  21603. this._depth = depth;
  21604. this._maxDepth = maxDepth;
  21605. this._creationFunc = creationFunc;
  21606. this._minPoint = minPoint;
  21607. this._maxPoint = maxPoint;
  21608. this._boundingVectors.push(minPoint.clone());
  21609. this._boundingVectors.push(maxPoint.clone());
  21610. this._boundingVectors.push(minPoint.clone());
  21611. this._boundingVectors[2].x = maxPoint.x;
  21612. this._boundingVectors.push(minPoint.clone());
  21613. this._boundingVectors[3].y = maxPoint.y;
  21614. this._boundingVectors.push(minPoint.clone());
  21615. this._boundingVectors[4].z = maxPoint.z;
  21616. this._boundingVectors.push(maxPoint.clone());
  21617. this._boundingVectors[5].z = minPoint.z;
  21618. this._boundingVectors.push(maxPoint.clone());
  21619. this._boundingVectors[6].x = minPoint.x;
  21620. this._boundingVectors.push(maxPoint.clone());
  21621. this._boundingVectors[7].y = minPoint.y;
  21622. }
  21623. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21624. // Property
  21625. get: function () {
  21626. return this._capacity;
  21627. },
  21628. enumerable: true,
  21629. configurable: true
  21630. });
  21631. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21632. get: function () {
  21633. return this._minPoint;
  21634. },
  21635. enumerable: true,
  21636. configurable: true
  21637. });
  21638. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21639. get: function () {
  21640. return this._maxPoint;
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. // Methods
  21646. OctreeBlock.prototype.addEntry = function (entry) {
  21647. if (this.blocks) {
  21648. for (var index = 0; index < this.blocks.length; index++) {
  21649. var block = this.blocks[index];
  21650. block.addEntry(entry);
  21651. }
  21652. return;
  21653. }
  21654. this._creationFunc(entry, this);
  21655. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21656. this.createInnerBlocks();
  21657. }
  21658. };
  21659. OctreeBlock.prototype.addEntries = function (entries) {
  21660. for (var index = 0; index < entries.length; index++) {
  21661. var mesh = entries[index];
  21662. this.addEntry(mesh);
  21663. }
  21664. };
  21665. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21666. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21667. if (this.blocks) {
  21668. for (var index = 0; index < this.blocks.length; index++) {
  21669. var block = this.blocks[index];
  21670. block.select(frustumPlanes, selection, allowDuplicate);
  21671. }
  21672. return;
  21673. }
  21674. if (allowDuplicate) {
  21675. selection.concat(this.entries);
  21676. }
  21677. else {
  21678. selection.concatWithNoDuplicate(this.entries);
  21679. }
  21680. }
  21681. };
  21682. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21683. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21684. if (this.blocks) {
  21685. for (var index = 0; index < this.blocks.length; index++) {
  21686. var block = this.blocks[index];
  21687. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21688. }
  21689. return;
  21690. }
  21691. if (allowDuplicate) {
  21692. selection.concat(this.entries);
  21693. }
  21694. else {
  21695. selection.concatWithNoDuplicate(this.entries);
  21696. }
  21697. }
  21698. };
  21699. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21700. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21701. if (this.blocks) {
  21702. for (var index = 0; index < this.blocks.length; index++) {
  21703. var block = this.blocks[index];
  21704. block.intersectsRay(ray, selection);
  21705. }
  21706. return;
  21707. }
  21708. selection.concatWithNoDuplicate(this.entries);
  21709. }
  21710. };
  21711. OctreeBlock.prototype.createInnerBlocks = function () {
  21712. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21713. };
  21714. return OctreeBlock;
  21715. })();
  21716. BABYLON.OctreeBlock = OctreeBlock;
  21717. })(BABYLON || (BABYLON = {}));
  21718. //# sourceMappingURL=babylon.octreeBlock.js.map
  21719. var BABYLON;
  21720. (function (BABYLON) {
  21721. var Bone = (function () {
  21722. function Bone(name, skeleton, parentBone, matrix) {
  21723. this.name = name;
  21724. this.children = new Array();
  21725. this.animations = new Array();
  21726. this._worldTransform = new BABYLON.Matrix();
  21727. this._absoluteTransform = new BABYLON.Matrix();
  21728. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21729. this._skeleton = skeleton;
  21730. this._matrix = matrix;
  21731. this._baseMatrix = matrix;
  21732. skeleton.bones.push(this);
  21733. if (parentBone) {
  21734. this._parent = parentBone;
  21735. parentBone.children.push(this);
  21736. }
  21737. else {
  21738. this._parent = null;
  21739. }
  21740. this._updateDifferenceMatrix();
  21741. }
  21742. // Members
  21743. Bone.prototype.getParent = function () {
  21744. return this._parent;
  21745. };
  21746. Bone.prototype.getLocalMatrix = function () {
  21747. return this._matrix;
  21748. };
  21749. Bone.prototype.getBaseMatrix = function () {
  21750. return this._baseMatrix;
  21751. };
  21752. Bone.prototype.getWorldMatrix = function () {
  21753. return this._worldTransform;
  21754. };
  21755. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21756. return this._invertedAbsoluteTransform;
  21757. };
  21758. Bone.prototype.getAbsoluteMatrix = function () {
  21759. var matrix = this._matrix.clone();
  21760. var parent = this._parent;
  21761. while (parent) {
  21762. matrix = matrix.multiply(parent.getLocalMatrix());
  21763. parent = parent.getParent();
  21764. }
  21765. return matrix;
  21766. };
  21767. // Methods
  21768. Bone.prototype.updateMatrix = function (matrix) {
  21769. this._matrix = matrix;
  21770. this._skeleton._markAsDirty();
  21771. this._updateDifferenceMatrix();
  21772. };
  21773. Bone.prototype._updateDifferenceMatrix = function () {
  21774. if (this._parent) {
  21775. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21776. }
  21777. else {
  21778. this._absoluteTransform.copyFrom(this._matrix);
  21779. }
  21780. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21781. for (var index = 0; index < this.children.length; index++) {
  21782. this.children[index]._updateDifferenceMatrix();
  21783. }
  21784. };
  21785. Bone.prototype.markAsDirty = function () {
  21786. this._skeleton._markAsDirty();
  21787. };
  21788. return Bone;
  21789. })();
  21790. BABYLON.Bone = Bone;
  21791. })(BABYLON || (BABYLON = {}));
  21792. //# sourceMappingURL=babylon.bone.js.map
  21793. var BABYLON;
  21794. (function (BABYLON) {
  21795. var Skeleton = (function () {
  21796. function Skeleton(name, id, scene) {
  21797. this.name = name;
  21798. this.id = id;
  21799. this.bones = new Array();
  21800. this._isDirty = true;
  21801. this._identity = BABYLON.Matrix.Identity();
  21802. this.bones = [];
  21803. this._scene = scene;
  21804. scene.skeletons.push(this);
  21805. this.prepare();
  21806. //make sure it will recalculate the matrix next time prepare is called.
  21807. this._isDirty = true;
  21808. }
  21809. // Members
  21810. Skeleton.prototype.getTransformMatrices = function () {
  21811. return this._transformMatrices;
  21812. };
  21813. // Methods
  21814. Skeleton.prototype._markAsDirty = function () {
  21815. this._isDirty = true;
  21816. };
  21817. Skeleton.prototype.prepare = function () {
  21818. if (!this._isDirty) {
  21819. return;
  21820. }
  21821. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21822. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21823. }
  21824. for (var index = 0; index < this.bones.length; index++) {
  21825. var bone = this.bones[index];
  21826. var parentBone = bone.getParent();
  21827. if (parentBone) {
  21828. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21829. }
  21830. else {
  21831. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21832. }
  21833. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21834. }
  21835. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21836. this._isDirty = false;
  21837. this._scene._activeBones += this.bones.length;
  21838. };
  21839. Skeleton.prototype.getAnimatables = function () {
  21840. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21841. this._animatables = [];
  21842. for (var index = 0; index < this.bones.length; index++) {
  21843. this._animatables.push(this.bones[index]);
  21844. }
  21845. }
  21846. return this._animatables;
  21847. };
  21848. Skeleton.prototype.clone = function (name, id) {
  21849. var result = new Skeleton(name, id || name, this._scene);
  21850. for (var index = 0; index < this.bones.length; index++) {
  21851. var source = this.bones[index];
  21852. var parentBone = null;
  21853. if (source.getParent()) {
  21854. var parentIndex = this.bones.indexOf(source.getParent());
  21855. parentBone = result.bones[parentIndex];
  21856. }
  21857. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21858. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21859. }
  21860. return result;
  21861. };
  21862. return Skeleton;
  21863. })();
  21864. BABYLON.Skeleton = Skeleton;
  21865. })(BABYLON || (BABYLON = {}));
  21866. //# sourceMappingURL=babylon.skeleton.js.map
  21867. var BABYLON;
  21868. (function (BABYLON) {
  21869. var PostProcess = (function () {
  21870. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  21871. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21872. this.name = name;
  21873. this.width = -1;
  21874. this.height = -1;
  21875. this._reusable = false;
  21876. this._textures = new BABYLON.SmartArray(2);
  21877. this._currentRenderTextureInd = 0;
  21878. if (camera != null) {
  21879. this._camera = camera;
  21880. this._scene = camera.getScene();
  21881. camera.attachPostProcess(this);
  21882. this._engine = this._scene.getEngine();
  21883. }
  21884. else {
  21885. this._engine = engine;
  21886. }
  21887. this._renderRatio = ratio;
  21888. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21889. this._reusable = reusable || false;
  21890. samplers = samplers || [];
  21891. samplers.push("textureSampler");
  21892. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21893. }
  21894. PostProcess.prototype.isReusable = function () {
  21895. return this._reusable;
  21896. };
  21897. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21898. camera = camera || this._camera;
  21899. var scene = camera.getScene();
  21900. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21901. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21902. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21903. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21904. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21905. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21906. if (this._textures.length > 0) {
  21907. for (var i = 0; i < this._textures.length; i++) {
  21908. this._engine._releaseTexture(this._textures.data[i]);
  21909. }
  21910. this._textures.reset();
  21911. }
  21912. this.width = desiredWidth;
  21913. this.height = desiredHeight;
  21914. 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 }));
  21915. if (this._reusable) {
  21916. 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 }));
  21917. }
  21918. if (this.onSizeChanged) {
  21919. this.onSizeChanged();
  21920. }
  21921. }
  21922. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21923. if (this.onActivate) {
  21924. this.onActivate(camera);
  21925. }
  21926. // Clear
  21927. if (this.clearColor) {
  21928. this._engine.clear(this.clearColor, true, true);
  21929. }
  21930. else {
  21931. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21932. }
  21933. if (this._reusable) {
  21934. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21935. }
  21936. };
  21937. PostProcess.prototype.apply = function () {
  21938. // Check
  21939. if (!this._effect.isReady())
  21940. return null;
  21941. // States
  21942. this._engine.enableEffect(this._effect);
  21943. this._engine.setState(false);
  21944. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21945. this._engine.setDepthBuffer(false);
  21946. this._engine.setDepthWrite(false);
  21947. // Texture
  21948. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21949. // Parameters
  21950. if (this.onApply) {
  21951. this.onApply(this._effect);
  21952. }
  21953. return this._effect;
  21954. };
  21955. PostProcess.prototype.dispose = function (camera) {
  21956. camera = camera || this._camera;
  21957. if (this._textures.length > 0) {
  21958. for (var i = 0; i < this._textures.length; i++) {
  21959. this._engine._releaseTexture(this._textures.data[i]);
  21960. }
  21961. this._textures.reset();
  21962. }
  21963. if (!camera) {
  21964. return;
  21965. }
  21966. camera.detachPostProcess(this);
  21967. var index = camera._postProcesses.indexOf(this);
  21968. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21969. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21970. }
  21971. };
  21972. return PostProcess;
  21973. })();
  21974. BABYLON.PostProcess = PostProcess;
  21975. })(BABYLON || (BABYLON = {}));
  21976. //# sourceMappingURL=babylon.postProcess.js.map
  21977. var BABYLON;
  21978. (function (BABYLON) {
  21979. var PostProcessManager = (function () {
  21980. function PostProcessManager(scene) {
  21981. this._vertexDeclaration = [2];
  21982. this._vertexStrideSize = 2 * 4;
  21983. this._scene = scene;
  21984. }
  21985. PostProcessManager.prototype._prepareBuffers = function () {
  21986. if (this._vertexBuffer) {
  21987. return;
  21988. }
  21989. // VBO
  21990. var vertices = [];
  21991. vertices.push(1, 1);
  21992. vertices.push(-1, 1);
  21993. vertices.push(-1, -1);
  21994. vertices.push(1, -1);
  21995. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21996. // Indices
  21997. var indices = [];
  21998. indices.push(0);
  21999. indices.push(1);
  22000. indices.push(2);
  22001. indices.push(0);
  22002. indices.push(2);
  22003. indices.push(3);
  22004. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22005. };
  22006. // Methods
  22007. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22008. var postProcesses = this._scene.activeCamera._postProcesses;
  22009. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22010. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22011. return false;
  22012. }
  22013. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22014. return true;
  22015. };
  22016. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22017. var engine = this._scene.getEngine();
  22018. for (var index = 0; index < postProcesses.length; index++) {
  22019. if (index < postProcesses.length - 1) {
  22020. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22021. }
  22022. else {
  22023. if (targetTexture) {
  22024. engine.bindFramebuffer(targetTexture);
  22025. }
  22026. else {
  22027. engine.restoreDefaultFramebuffer();
  22028. }
  22029. }
  22030. var pp = postProcesses[index];
  22031. var effect = pp.apply();
  22032. if (effect) {
  22033. if (pp.onBeforeRender) {
  22034. pp.onBeforeRender(effect);
  22035. }
  22036. // VBOs
  22037. this._prepareBuffers();
  22038. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22039. // Draw order
  22040. engine.draw(true, 0, 6);
  22041. }
  22042. }
  22043. // Restore depth buffer
  22044. engine.setDepthBuffer(true);
  22045. engine.setDepthWrite(true);
  22046. };
  22047. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22048. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22049. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22050. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22051. return;
  22052. }
  22053. var engine = this._scene.getEngine();
  22054. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22055. if (index < postProcessesTakenIndices.length - 1) {
  22056. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22057. }
  22058. else {
  22059. if (targetTexture) {
  22060. engine.bindFramebuffer(targetTexture);
  22061. }
  22062. else {
  22063. engine.restoreDefaultFramebuffer();
  22064. }
  22065. }
  22066. if (doNotPresent) {
  22067. break;
  22068. }
  22069. var pp = postProcesses[postProcessesTakenIndices[index]];
  22070. var effect = pp.apply();
  22071. if (effect) {
  22072. if (pp.onBeforeRender) {
  22073. pp.onBeforeRender(effect);
  22074. }
  22075. // VBOs
  22076. this._prepareBuffers();
  22077. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22078. // Draw order
  22079. engine.draw(true, 0, 6);
  22080. }
  22081. }
  22082. // Restore depth buffer
  22083. engine.setDepthBuffer(true);
  22084. engine.setDepthWrite(true);
  22085. };
  22086. PostProcessManager.prototype.dispose = function () {
  22087. if (this._vertexBuffer) {
  22088. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22089. this._vertexBuffer = null;
  22090. }
  22091. if (this._indexBuffer) {
  22092. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22093. this._indexBuffer = null;
  22094. }
  22095. };
  22096. return PostProcessManager;
  22097. })();
  22098. BABYLON.PostProcessManager = PostProcessManager;
  22099. })(BABYLON || (BABYLON = {}));
  22100. //# sourceMappingURL=babylon.postProcessManager.js.map
  22101. var __extends = (this && this.__extends) || function (d, b) {
  22102. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22103. function __() { this.constructor = d; }
  22104. __.prototype = b.prototype;
  22105. d.prototype = new __();
  22106. };
  22107. var BABYLON;
  22108. (function (BABYLON) {
  22109. var PassPostProcess = (function (_super) {
  22110. __extends(PassPostProcess, _super);
  22111. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22112. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22113. }
  22114. return PassPostProcess;
  22115. })(BABYLON.PostProcess);
  22116. BABYLON.PassPostProcess = PassPostProcess;
  22117. })(BABYLON || (BABYLON = {}));
  22118. //# sourceMappingURL=babylon.passPostProcess.js.map
  22119. var __extends = (this && this.__extends) || function (d, b) {
  22120. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22121. function __() { this.constructor = d; }
  22122. __.prototype = b.prototype;
  22123. d.prototype = new __();
  22124. };
  22125. var BABYLON;
  22126. (function (BABYLON) {
  22127. var BlurPostProcess = (function (_super) {
  22128. __extends(BlurPostProcess, _super);
  22129. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22130. var _this = this;
  22131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22132. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22133. this.direction = direction;
  22134. this.blurWidth = blurWidth;
  22135. this.onApply = function (effect) {
  22136. effect.setFloat2("screenSize", _this.width, _this.height);
  22137. effect.setVector2("direction", _this.direction);
  22138. effect.setFloat("blurWidth", _this.blurWidth);
  22139. };
  22140. }
  22141. return BlurPostProcess;
  22142. })(BABYLON.PostProcess);
  22143. BABYLON.BlurPostProcess = BlurPostProcess;
  22144. })(BABYLON || (BABYLON = {}));
  22145. //# sourceMappingURL=babylon.blurPostProcess.js.map
  22146. var __extends = (this && this.__extends) || function (d, b) {
  22147. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22148. function __() { this.constructor = d; }
  22149. __.prototype = b.prototype;
  22150. d.prototype = new __();
  22151. };
  22152. var BABYLON;
  22153. (function (BABYLON) {
  22154. var RefractionPostProcess = (function (_super) {
  22155. __extends(RefractionPostProcess, _super);
  22156. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22157. var _this = this;
  22158. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22159. this.color = color;
  22160. this.depth = depth;
  22161. this.colorLevel = colorLevel;
  22162. this.onActivate = function (cam) {
  22163. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22164. };
  22165. this.onApply = function (effect) {
  22166. effect.setColor3("baseColor", _this.color);
  22167. effect.setFloat("depth", _this.depth);
  22168. effect.setFloat("colorLevel", _this.colorLevel);
  22169. effect.setTexture("refractionSampler", _this._refRexture);
  22170. };
  22171. }
  22172. // Methods
  22173. RefractionPostProcess.prototype.dispose = function (camera) {
  22174. if (this._refRexture) {
  22175. this._refRexture.dispose();
  22176. }
  22177. _super.prototype.dispose.call(this, camera);
  22178. };
  22179. return RefractionPostProcess;
  22180. })(BABYLON.PostProcess);
  22181. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22182. })(BABYLON || (BABYLON = {}));
  22183. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22184. var __extends = (this && this.__extends) || function (d, b) {
  22185. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22186. function __() { this.constructor = d; }
  22187. __.prototype = b.prototype;
  22188. d.prototype = new __();
  22189. };
  22190. var BABYLON;
  22191. (function (BABYLON) {
  22192. var BlackAndWhitePostProcess = (function (_super) {
  22193. __extends(BlackAndWhitePostProcess, _super);
  22194. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22195. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22196. }
  22197. return BlackAndWhitePostProcess;
  22198. })(BABYLON.PostProcess);
  22199. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22200. })(BABYLON || (BABYLON = {}));
  22201. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22202. var __extends = (this && this.__extends) || function (d, b) {
  22203. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22204. function __() { this.constructor = d; }
  22205. __.prototype = b.prototype;
  22206. d.prototype = new __();
  22207. };
  22208. var BABYLON;
  22209. (function (BABYLON) {
  22210. var ConvolutionPostProcess = (function (_super) {
  22211. __extends(ConvolutionPostProcess, _super);
  22212. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22213. var _this = this;
  22214. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22215. this.kernel = kernel;
  22216. this.onApply = function (effect) {
  22217. effect.setFloat2("screenSize", _this.width, _this.height);
  22218. effect.setArray("kernel", _this.kernel);
  22219. };
  22220. }
  22221. // Statics
  22222. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22223. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22224. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22225. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22226. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22227. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22228. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22229. return ConvolutionPostProcess;
  22230. })(BABYLON.PostProcess);
  22231. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22232. })(BABYLON || (BABYLON = {}));
  22233. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22234. var __extends = (this && this.__extends) || function (d, b) {
  22235. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22236. function __() { this.constructor = d; }
  22237. __.prototype = b.prototype;
  22238. d.prototype = new __();
  22239. };
  22240. var BABYLON;
  22241. (function (BABYLON) {
  22242. var FilterPostProcess = (function (_super) {
  22243. __extends(FilterPostProcess, _super);
  22244. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22245. var _this = this;
  22246. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22247. this.kernelMatrix = kernelMatrix;
  22248. this.onApply = function (effect) {
  22249. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22250. };
  22251. }
  22252. return FilterPostProcess;
  22253. })(BABYLON.PostProcess);
  22254. BABYLON.FilterPostProcess = FilterPostProcess;
  22255. })(BABYLON || (BABYLON = {}));
  22256. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22257. var __extends = (this && this.__extends) || function (d, b) {
  22258. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22259. function __() { this.constructor = d; }
  22260. __.prototype = b.prototype;
  22261. d.prototype = new __();
  22262. };
  22263. var BABYLON;
  22264. (function (BABYLON) {
  22265. var FxaaPostProcess = (function (_super) {
  22266. __extends(FxaaPostProcess, _super);
  22267. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22268. var _this = this;
  22269. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22270. this.onSizeChanged = function () {
  22271. _this.texelWidth = 1.0 / _this.width;
  22272. _this.texelHeight = 1.0 / _this.height;
  22273. };
  22274. this.onApply = function (effect) {
  22275. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22276. };
  22277. }
  22278. return FxaaPostProcess;
  22279. })(BABYLON.PostProcess);
  22280. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22281. })(BABYLON || (BABYLON = {}));
  22282. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22283. var __extends = (this && this.__extends) || function (d, b) {
  22284. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22285. function __() { this.constructor = d; }
  22286. __.prototype = b.prototype;
  22287. d.prototype = new __();
  22288. };
  22289. var BABYLON;
  22290. (function (BABYLON) {
  22291. var StereoscopicInterlacePostProcess = (function (_super) {
  22292. __extends(StereoscopicInterlacePostProcess, _super);
  22293. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  22294. var _this = this;
  22295. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  22296. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22297. this.onSizeChanged = function () {
  22298. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22299. };
  22300. this.onApply = function (effect) {
  22301. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22302. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22303. };
  22304. }
  22305. return StereoscopicInterlacePostProcess;
  22306. })(BABYLON.PostProcess);
  22307. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  22308. })(BABYLON || (BABYLON = {}));
  22309. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  22310. var BABYLON;
  22311. (function (BABYLON) {
  22312. var LensFlare = (function () {
  22313. function LensFlare(size, position, color, imgUrl, system) {
  22314. this.size = size;
  22315. this.position = position;
  22316. this.dispose = function () {
  22317. if (this.texture) {
  22318. this.texture.dispose();
  22319. }
  22320. // Remove from scene
  22321. var index = this._system.lensFlares.indexOf(this);
  22322. this._system.lensFlares.splice(index, 1);
  22323. };
  22324. this.color = color || new BABYLON.Color3(1, 1, 1);
  22325. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22326. this._system = system;
  22327. system.lensFlares.push(this);
  22328. }
  22329. return LensFlare;
  22330. })();
  22331. BABYLON.LensFlare = LensFlare;
  22332. })(BABYLON || (BABYLON = {}));
  22333. //# sourceMappingURL=babylon.lensFlare.js.map
  22334. var BABYLON;
  22335. (function (BABYLON) {
  22336. var LensFlareSystem = (function () {
  22337. function LensFlareSystem(name, emitter, scene) {
  22338. this.name = name;
  22339. this.lensFlares = new Array();
  22340. this.borderLimit = 300;
  22341. this._vertexDeclaration = [2];
  22342. this._vertexStrideSize = 2 * 4;
  22343. this._isEnabled = true;
  22344. this._scene = scene;
  22345. this._emitter = emitter;
  22346. scene.lensFlareSystems.push(this);
  22347. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22348. // VBO
  22349. var vertices = [];
  22350. vertices.push(1, 1);
  22351. vertices.push(-1, 1);
  22352. vertices.push(-1, -1);
  22353. vertices.push(1, -1);
  22354. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22355. // Indices
  22356. var indices = [];
  22357. indices.push(0);
  22358. indices.push(1);
  22359. indices.push(2);
  22360. indices.push(0);
  22361. indices.push(2);
  22362. indices.push(3);
  22363. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22364. // Effects
  22365. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22366. }
  22367. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22368. get: function () {
  22369. return this._isEnabled;
  22370. },
  22371. set: function (value) {
  22372. this._isEnabled = value;
  22373. },
  22374. enumerable: true,
  22375. configurable: true
  22376. });
  22377. LensFlareSystem.prototype.getScene = function () {
  22378. return this._scene;
  22379. };
  22380. LensFlareSystem.prototype.getEmitter = function () {
  22381. return this._emitter;
  22382. };
  22383. LensFlareSystem.prototype.getEmitterPosition = function () {
  22384. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22385. };
  22386. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22387. var position = this.getEmitterPosition();
  22388. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22389. this._positionX = position.x;
  22390. this._positionY = position.y;
  22391. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22392. if (position.z > 0) {
  22393. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22394. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22395. return true;
  22396. }
  22397. }
  22398. return false;
  22399. };
  22400. LensFlareSystem.prototype._isVisible = function () {
  22401. if (!this._isEnabled) {
  22402. return false;
  22403. }
  22404. var emitterPosition = this.getEmitterPosition();
  22405. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22406. var distance = direction.length();
  22407. direction.normalize();
  22408. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22409. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22410. return !pickInfo.hit || pickInfo.distance > distance;
  22411. };
  22412. LensFlareSystem.prototype.render = function () {
  22413. if (!this._effect.isReady())
  22414. return false;
  22415. var engine = this._scene.getEngine();
  22416. var viewport = this._scene.activeCamera.viewport;
  22417. var globalViewport = viewport.toGlobal(engine);
  22418. // Position
  22419. if (!this.computeEffectivePosition(globalViewport)) {
  22420. return false;
  22421. }
  22422. // Visibility
  22423. if (!this._isVisible()) {
  22424. return false;
  22425. }
  22426. // Intensity
  22427. var awayX;
  22428. var awayY;
  22429. if (this._positionX < this.borderLimit + globalViewport.x) {
  22430. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22431. }
  22432. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22433. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22434. }
  22435. else {
  22436. awayX = 0;
  22437. }
  22438. if (this._positionY < this.borderLimit + globalViewport.y) {
  22439. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22440. }
  22441. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22442. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22443. }
  22444. else {
  22445. awayY = 0;
  22446. }
  22447. var away = (awayX > awayY) ? awayX : awayY;
  22448. if (away > this.borderLimit) {
  22449. away = this.borderLimit;
  22450. }
  22451. var intensity = 1.0 - (away / this.borderLimit);
  22452. if (intensity < 0) {
  22453. return false;
  22454. }
  22455. if (intensity > 1.0) {
  22456. intensity = 1.0;
  22457. }
  22458. // Position
  22459. var centerX = globalViewport.x + globalViewport.width / 2;
  22460. var centerY = globalViewport.y + globalViewport.height / 2;
  22461. var distX = centerX - this._positionX;
  22462. var distY = centerY - this._positionY;
  22463. // Effects
  22464. engine.enableEffect(this._effect);
  22465. engine.setState(false);
  22466. engine.setDepthBuffer(false);
  22467. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22468. // VBOs
  22469. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22470. // Flares
  22471. for (var index = 0; index < this.lensFlares.length; index++) {
  22472. var flare = this.lensFlares[index];
  22473. var x = centerX - (distX * flare.position);
  22474. var y = centerY - (distY * flare.position);
  22475. var cw = flare.size;
  22476. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22477. var cx = 2 * (x / globalViewport.width) - 1.0;
  22478. var cy = 1.0 - 2 * (y / globalViewport.height);
  22479. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22480. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22481. // Texture
  22482. this._effect.setTexture("textureSampler", flare.texture);
  22483. // Color
  22484. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22485. // Draw order
  22486. engine.draw(true, 0, 6);
  22487. }
  22488. engine.setDepthBuffer(true);
  22489. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22490. return true;
  22491. };
  22492. LensFlareSystem.prototype.dispose = function () {
  22493. if (this._vertexBuffer) {
  22494. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22495. this._vertexBuffer = null;
  22496. }
  22497. if (this._indexBuffer) {
  22498. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22499. this._indexBuffer = null;
  22500. }
  22501. while (this.lensFlares.length) {
  22502. this.lensFlares[0].dispose();
  22503. }
  22504. // Remove from scene
  22505. var index = this._scene.lensFlareSystems.indexOf(this);
  22506. this._scene.lensFlareSystems.splice(index, 1);
  22507. };
  22508. return LensFlareSystem;
  22509. })();
  22510. BABYLON.LensFlareSystem = LensFlareSystem;
  22511. })(BABYLON || (BABYLON = {}));
  22512. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22513. var BABYLON;
  22514. (function (BABYLON) {
  22515. var CannonJSPlugin = (function () {
  22516. function CannonJSPlugin() {
  22517. this._registeredMeshes = [];
  22518. this._physicsMaterials = [];
  22519. this.updateBodyPosition = function (mesh) {
  22520. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22521. var registeredMesh = this._registeredMeshes[index];
  22522. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22523. var body = registeredMesh.body;
  22524. var center = mesh.getBoundingInfo().boundingBox.center;
  22525. body.position.set(center.x, center.z, center.y);
  22526. body.quaternion.x = mesh.rotationQuaternion.x;
  22527. body.quaternion.z = mesh.rotationQuaternion.y;
  22528. body.quaternion.y = mesh.rotationQuaternion.z;
  22529. body.quaternion.w = -mesh.rotationQuaternion.w;
  22530. return;
  22531. }
  22532. }
  22533. };
  22534. }
  22535. CannonJSPlugin.prototype.initialize = function (iterations) {
  22536. if (iterations === void 0) { iterations = 10; }
  22537. this._world = new CANNON.World();
  22538. this._world.broadphase = new CANNON.NaiveBroadphase();
  22539. this._world.solver.iterations = iterations;
  22540. };
  22541. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22542. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22543. };
  22544. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22545. this._world.step(delta);
  22546. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22547. var registeredMesh = this._registeredMeshes[index];
  22548. if (registeredMesh.isChild) {
  22549. continue;
  22550. }
  22551. // Body position
  22552. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22553. var deltaPos = registeredMesh.delta;
  22554. if (deltaPos) {
  22555. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22556. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22557. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22558. }
  22559. else {
  22560. registeredMesh.mesh.position.x = bodyX;
  22561. registeredMesh.mesh.position.y = bodyZ;
  22562. registeredMesh.mesh.position.z = bodyY;
  22563. }
  22564. if (!registeredMesh.mesh.rotationQuaternion) {
  22565. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22566. }
  22567. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22568. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22569. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22570. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22571. }
  22572. };
  22573. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22574. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22575. };
  22576. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22577. this.unregisterMesh(mesh);
  22578. mesh.computeWorldMatrix(true);
  22579. switch (impostor) {
  22580. case BABYLON.PhysicsEngine.SphereImpostor:
  22581. var bbox = mesh.getBoundingInfo().boundingBox;
  22582. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22583. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22584. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22585. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22586. case BABYLON.PhysicsEngine.BoxImpostor:
  22587. bbox = mesh.getBoundingInfo().boundingBox;
  22588. var min = bbox.minimumWorld;
  22589. var max = bbox.maximumWorld;
  22590. var box = max.subtract(min).scale(0.5);
  22591. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22592. case BABYLON.PhysicsEngine.PlaneImpostor:
  22593. return this._createPlane(mesh, options);
  22594. case BABYLON.PhysicsEngine.MeshImpostor:
  22595. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22596. var rawFaces = mesh.getIndices();
  22597. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22598. }
  22599. return null;
  22600. };
  22601. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22602. var shape = new CANNON.Sphere(radius);
  22603. if (!options) {
  22604. return shape;
  22605. }
  22606. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22607. };
  22608. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22609. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22610. if (!options) {
  22611. return shape;
  22612. }
  22613. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22614. };
  22615. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22616. var shape = new CANNON.Plane();
  22617. if (!options) {
  22618. return shape;
  22619. }
  22620. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22621. };
  22622. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22623. var verts = [], faces = [];
  22624. mesh.computeWorldMatrix(true);
  22625. // Get vertices
  22626. for (var i = 0; i < rawVerts.length; i += 3) {
  22627. var transformed = BABYLON.Vector3.Zero();
  22628. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22629. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22630. }
  22631. // Get faces
  22632. for (var j = 0; j < rawFaces.length; j += 3) {
  22633. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22634. }
  22635. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22636. if (!options) {
  22637. return shape;
  22638. }
  22639. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22640. };
  22641. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22642. var index;
  22643. var mat;
  22644. for (index = 0; index < this._physicsMaterials.length; index++) {
  22645. mat = this._physicsMaterials[index];
  22646. if (mat.friction === friction && mat.restitution === restitution) {
  22647. return mat;
  22648. }
  22649. }
  22650. var currentMat = new CANNON.Material();
  22651. currentMat.friction = friction;
  22652. currentMat.restitution = restitution;
  22653. this._physicsMaterials.push(currentMat);
  22654. for (index = 0; index < this._physicsMaterials.length; index++) {
  22655. mat = this._physicsMaterials[index];
  22656. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22657. contactMaterial.contactEquationStiffness = 1e10;
  22658. contactMaterial.contactEquationRegularizationTime = 10;
  22659. this._world.addContactMaterial(contactMaterial);
  22660. }
  22661. return currentMat;
  22662. };
  22663. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22664. var initialRotation = null;
  22665. if (mesh.rotationQuaternion) {
  22666. initialRotation = mesh.rotationQuaternion.clone();
  22667. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22668. }
  22669. // The delta between the mesh position and the mesh bounding box center
  22670. var bbox = mesh.getBoundingInfo().boundingBox;
  22671. var deltaPosition = mesh.position.subtract(bbox.center);
  22672. var material = this._addMaterial(friction, restitution);
  22673. var body = new CANNON.RigidBody(mass, shape, material);
  22674. if (initialRotation) {
  22675. body.quaternion.x = initialRotation.x;
  22676. body.quaternion.z = initialRotation.y;
  22677. body.quaternion.y = initialRotation.z;
  22678. body.quaternion.w = -initialRotation.w;
  22679. }
  22680. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22681. this._world.add(body);
  22682. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22683. return body;
  22684. };
  22685. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22686. var compoundShape = new CANNON.Compound();
  22687. for (var index = 0; index < parts.length; index++) {
  22688. var mesh = parts[index].mesh;
  22689. var shape = this.registerMesh(mesh, parts[index].impostor);
  22690. if (index == 0) {
  22691. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22692. }
  22693. else {
  22694. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22695. }
  22696. }
  22697. var initialMesh = parts[0].mesh;
  22698. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22699. body.parts = parts;
  22700. return body;
  22701. };
  22702. CannonJSPlugin.prototype._unbindBody = function (body) {
  22703. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22704. var registeredMesh = this._registeredMeshes[index];
  22705. if (registeredMesh.body === body) {
  22706. registeredMesh.body = null;
  22707. registeredMesh.delta = 0;
  22708. }
  22709. }
  22710. };
  22711. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22712. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22713. var registeredMesh = this._registeredMeshes[index];
  22714. if (registeredMesh.mesh === mesh) {
  22715. // Remove body
  22716. if (registeredMesh.body) {
  22717. this._world.remove(registeredMesh.body);
  22718. this._unbindBody(registeredMesh.body);
  22719. }
  22720. this._registeredMeshes.splice(index, 1);
  22721. return;
  22722. }
  22723. }
  22724. };
  22725. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22726. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22727. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22728. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22729. var registeredMesh = this._registeredMeshes[index];
  22730. if (registeredMesh.mesh === mesh) {
  22731. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22732. return;
  22733. }
  22734. }
  22735. };
  22736. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22737. var body1 = null, body2 = null;
  22738. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22739. var registeredMesh = this._registeredMeshes[index];
  22740. if (registeredMesh.mesh === mesh1) {
  22741. body1 = registeredMesh.body;
  22742. }
  22743. else if (registeredMesh.mesh === mesh2) {
  22744. body2 = registeredMesh.body;
  22745. }
  22746. }
  22747. if (!body1 || !body2) {
  22748. return false;
  22749. }
  22750. 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));
  22751. this._world.addConstraint(constraint);
  22752. return true;
  22753. };
  22754. CannonJSPlugin.prototype.dispose = function () {
  22755. while (this._registeredMeshes.length) {
  22756. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22757. }
  22758. };
  22759. CannonJSPlugin.prototype.isSupported = function () {
  22760. return window.CANNON !== undefined;
  22761. };
  22762. return CannonJSPlugin;
  22763. })();
  22764. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22765. })(BABYLON || (BABYLON = {}));
  22766. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22767. var BABYLON;
  22768. (function (BABYLON) {
  22769. var OimoJSPlugin = (function () {
  22770. function OimoJSPlugin() {
  22771. this._registeredMeshes = [];
  22772. /**
  22773. * Update the body position according to the mesh position
  22774. * @param mesh
  22775. */
  22776. this.updateBodyPosition = function (mesh) {
  22777. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22778. var registeredMesh = this._registeredMeshes[index];
  22779. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22780. var body = registeredMesh.body.body;
  22781. mesh.computeWorldMatrix(true);
  22782. var center = mesh.getBoundingInfo().boundingBox.center;
  22783. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22784. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22785. body.sleeping = false;
  22786. return;
  22787. }
  22788. // Case where the parent has been updated
  22789. if (registeredMesh.mesh.parent === mesh) {
  22790. mesh.computeWorldMatrix(true);
  22791. registeredMesh.mesh.computeWorldMatrix(true);
  22792. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22793. var absoluteRotation = mesh.rotation;
  22794. body = registeredMesh.body.body;
  22795. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22796. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22797. body.sleeping = false;
  22798. return;
  22799. }
  22800. }
  22801. };
  22802. }
  22803. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22804. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22805. };
  22806. OimoJSPlugin.prototype.initialize = function (iterations) {
  22807. this._world = new OIMO.World();
  22808. this._world.clear();
  22809. };
  22810. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22811. this._world.gravity = gravity;
  22812. };
  22813. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22814. var body = null;
  22815. this.unregisterMesh(mesh);
  22816. mesh.computeWorldMatrix(true);
  22817. var initialRotation = null;
  22818. if (mesh.rotationQuaternion) {
  22819. initialRotation = mesh.rotationQuaternion.clone();
  22820. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22821. mesh.computeWorldMatrix(true);
  22822. }
  22823. var bbox = mesh.getBoundingInfo().boundingBox;
  22824. // The delta between the mesh position and the mesh bounding box center
  22825. var deltaPosition = mesh.position.subtract(bbox.center);
  22826. // Transform delta position with the rotation
  22827. if (initialRotation) {
  22828. var m = new BABYLON.Matrix();
  22829. initialRotation.toRotationMatrix(m);
  22830. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22831. }
  22832. // register mesh
  22833. switch (impostor) {
  22834. case BABYLON.PhysicsEngine.SphereImpostor:
  22835. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22836. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22837. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22838. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22839. body = new OIMO.Body({
  22840. type: 'sphere',
  22841. size: [size],
  22842. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22843. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22844. move: options.mass != 0,
  22845. config: [options.mass, options.friction, options.restitution],
  22846. world: this._world
  22847. });
  22848. break;
  22849. case BABYLON.PhysicsEngine.PlaneImpostor:
  22850. //Oimo "fakes" a cylinder as a box, so why don't we!
  22851. case BABYLON.PhysicsEngine.CylinderImpostor:
  22852. case BABYLON.PhysicsEngine.BoxImpostor:
  22853. var min = bbox.minimumWorld;
  22854. var max = bbox.maximumWorld;
  22855. var box = max.subtract(min);
  22856. var sizeX = this._checkWithEpsilon(box.x);
  22857. var sizeY = this._checkWithEpsilon(box.y);
  22858. var sizeZ = this._checkWithEpsilon(box.z);
  22859. body = new OIMO.Body({
  22860. type: 'box',
  22861. size: [sizeX, sizeY, sizeZ],
  22862. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22863. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22864. move: options.mass != 0,
  22865. config: [options.mass, options.friction, options.restitution],
  22866. world: this._world
  22867. });
  22868. break;
  22869. }
  22870. //If quaternion was set as the rotation of the object
  22871. if (initialRotation) {
  22872. //We have to access the rigid body's properties to set the quaternion.
  22873. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22874. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22875. //update the internal rotation matrix
  22876. body.body.syncShapes();
  22877. }
  22878. this._registeredMeshes.push({
  22879. mesh: mesh,
  22880. body: body,
  22881. delta: deltaPosition
  22882. });
  22883. return body;
  22884. };
  22885. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22886. var types = [], sizes = [], positions = [], rotations = [];
  22887. var initialMesh = parts[0].mesh;
  22888. for (var index = 0; index < parts.length; index++) {
  22889. var part = parts[index];
  22890. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22891. types.push(bodyParameters.type);
  22892. sizes.push.apply(sizes, bodyParameters.size);
  22893. positions.push.apply(positions, bodyParameters.pos);
  22894. rotations.push.apply(rotations, bodyParameters.rot);
  22895. }
  22896. var body = new OIMO.Body({
  22897. type: types,
  22898. size: sizes,
  22899. pos: positions,
  22900. rot: rotations,
  22901. move: options.mass != 0,
  22902. config: [options.mass, options.friction, options.restitution],
  22903. world: this._world
  22904. });
  22905. this._registeredMeshes.push({
  22906. mesh: initialMesh,
  22907. body: body
  22908. });
  22909. return body;
  22910. };
  22911. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22912. var bodyParameters = null;
  22913. var mesh = part.mesh;
  22914. // We need the bounding box/sphere info to compute the physics body
  22915. mesh.computeWorldMatrix();
  22916. switch (part.impostor) {
  22917. case BABYLON.PhysicsEngine.SphereImpostor:
  22918. var bbox = mesh.getBoundingInfo().boundingBox;
  22919. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22920. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22921. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22922. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22923. bodyParameters = {
  22924. type: 'sphere',
  22925. /* bug with oimo : sphere needs 3 sizes in this case */
  22926. size: [size, -1, -1],
  22927. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22928. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22929. };
  22930. break;
  22931. case BABYLON.PhysicsEngine.PlaneImpostor:
  22932. case BABYLON.PhysicsEngine.BoxImpostor:
  22933. bbox = mesh.getBoundingInfo().boundingBox;
  22934. var min = bbox.minimumWorld;
  22935. var max = bbox.maximumWorld;
  22936. var box = max.subtract(min);
  22937. var sizeX = this._checkWithEpsilon(box.x);
  22938. var sizeY = this._checkWithEpsilon(box.y);
  22939. var sizeZ = this._checkWithEpsilon(box.z);
  22940. var relativePosition = mesh.position;
  22941. bodyParameters = {
  22942. type: 'box',
  22943. size: [sizeX, sizeY, sizeZ],
  22944. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22945. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22946. };
  22947. break;
  22948. }
  22949. return bodyParameters;
  22950. };
  22951. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22952. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22953. var registeredMesh = this._registeredMeshes[index];
  22954. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22955. if (registeredMesh.body) {
  22956. this._world.removeRigidBody(registeredMesh.body.body);
  22957. this._unbindBody(registeredMesh.body);
  22958. }
  22959. this._registeredMeshes.splice(index, 1);
  22960. return;
  22961. }
  22962. }
  22963. };
  22964. OimoJSPlugin.prototype._unbindBody = function (body) {
  22965. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22966. var registeredMesh = this._registeredMeshes[index];
  22967. if (registeredMesh.body === body) {
  22968. registeredMesh.body = null;
  22969. }
  22970. }
  22971. };
  22972. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22973. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22974. var registeredMesh = this._registeredMeshes[index];
  22975. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22976. // Get object mass to have a behaviour similar to cannon.js
  22977. var mass = registeredMesh.body.body.massInfo.mass;
  22978. // The force is scaled with the mass of object
  22979. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22980. return;
  22981. }
  22982. }
  22983. };
  22984. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22985. var body1 = null, body2 = null;
  22986. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22987. var registeredMesh = this._registeredMeshes[index];
  22988. if (registeredMesh.mesh === mesh1) {
  22989. body1 = registeredMesh.body.body;
  22990. }
  22991. else if (registeredMesh.mesh === mesh2) {
  22992. body2 = registeredMesh.body.body;
  22993. }
  22994. }
  22995. if (!body1 || !body2) {
  22996. return false;
  22997. }
  22998. if (!options) {
  22999. options = {};
  23000. }
  23001. new OIMO.Link({
  23002. type: options.type,
  23003. body1: body1,
  23004. body2: body2,
  23005. min: options.min,
  23006. max: options.max,
  23007. axe1: options.axe1,
  23008. axe2: options.axe2,
  23009. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23010. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23011. collision: options.collision,
  23012. spring: options.spring,
  23013. world: this._world
  23014. });
  23015. return true;
  23016. };
  23017. OimoJSPlugin.prototype.dispose = function () {
  23018. this._world.clear();
  23019. while (this._registeredMeshes.length) {
  23020. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23021. }
  23022. };
  23023. OimoJSPlugin.prototype.isSupported = function () {
  23024. return OIMO !== undefined;
  23025. };
  23026. OimoJSPlugin.prototype._getLastShape = function (body) {
  23027. var lastShape = body.shapes;
  23028. while (lastShape.next) {
  23029. lastShape = lastShape.next;
  23030. }
  23031. return lastShape;
  23032. };
  23033. OimoJSPlugin.prototype.runOneStep = function (time) {
  23034. this._world.step();
  23035. // Update the position of all registered meshes
  23036. var i = this._registeredMeshes.length;
  23037. var m;
  23038. while (i--) {
  23039. var body = this._registeredMeshes[i].body.body;
  23040. var mesh = this._registeredMeshes[i].mesh;
  23041. var delta = this._registeredMeshes[i].delta;
  23042. if (!body.sleeping) {
  23043. if (body.shapes.next) {
  23044. var parentShape = this._getLastShape(body);
  23045. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23046. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23047. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23048. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23049. if (!mesh.rotationQuaternion) {
  23050. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23051. }
  23052. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23053. mesh.computeWorldMatrix();
  23054. }
  23055. else {
  23056. m = body.getMatrix();
  23057. mtx = BABYLON.Matrix.FromArray(m);
  23058. // Body position
  23059. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23060. if (!delta) {
  23061. mesh.position.x = bodyX;
  23062. mesh.position.y = bodyY;
  23063. mesh.position.z = bodyZ;
  23064. }
  23065. else {
  23066. mesh.position.x = bodyX + delta.x;
  23067. mesh.position.y = bodyY + delta.y;
  23068. mesh.position.z = bodyZ + delta.z;
  23069. }
  23070. if (!mesh.rotationQuaternion) {
  23071. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23072. }
  23073. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23074. mesh.computeWorldMatrix();
  23075. }
  23076. }
  23077. }
  23078. };
  23079. return OimoJSPlugin;
  23080. })();
  23081. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23082. })(BABYLON || (BABYLON = {}));
  23083. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  23084. var BABYLON;
  23085. (function (BABYLON) {
  23086. var PhysicsEngine = (function () {
  23087. function PhysicsEngine(plugin) {
  23088. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23089. }
  23090. PhysicsEngine.prototype._initialize = function (gravity) {
  23091. this._currentPlugin.initialize();
  23092. this._setGravity(gravity);
  23093. };
  23094. PhysicsEngine.prototype._runOneStep = function (delta) {
  23095. if (delta > 0.1) {
  23096. delta = 0.1;
  23097. }
  23098. else if (delta <= 0) {
  23099. delta = 1.0 / 60.0;
  23100. }
  23101. this._currentPlugin.runOneStep(delta);
  23102. };
  23103. PhysicsEngine.prototype._setGravity = function (gravity) {
  23104. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  23105. this._currentPlugin.setGravity(this.gravity);
  23106. };
  23107. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23108. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23109. };
  23110. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23111. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23112. };
  23113. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23114. this._currentPlugin.unregisterMesh(mesh);
  23115. };
  23116. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23117. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23118. };
  23119. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23120. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23121. };
  23122. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23123. this._currentPlugin.updateBodyPosition(mesh);
  23124. };
  23125. PhysicsEngine.prototype.dispose = function () {
  23126. this._currentPlugin.dispose();
  23127. };
  23128. PhysicsEngine.prototype.isSupported = function () {
  23129. return this._currentPlugin.isSupported();
  23130. };
  23131. // Statics
  23132. PhysicsEngine.NoImpostor = 0;
  23133. PhysicsEngine.SphereImpostor = 1;
  23134. PhysicsEngine.BoxImpostor = 2;
  23135. PhysicsEngine.PlaneImpostor = 3;
  23136. PhysicsEngine.MeshImpostor = 4;
  23137. PhysicsEngine.CapsuleImpostor = 5;
  23138. PhysicsEngine.ConeImpostor = 6;
  23139. PhysicsEngine.CylinderImpostor = 7;
  23140. PhysicsEngine.ConvexHullImpostor = 8;
  23141. PhysicsEngine.Epsilon = 0.001;
  23142. return PhysicsEngine;
  23143. })();
  23144. BABYLON.PhysicsEngine = PhysicsEngine;
  23145. })(BABYLON || (BABYLON = {}));
  23146. //# sourceMappingURL=babylon.physicsEngine.js.map
  23147. var BABYLON;
  23148. (function (BABYLON) {
  23149. var serializeLight = function (light) {
  23150. var serializationObject = {};
  23151. serializationObject.name = light.name;
  23152. serializationObject.id = light.id;
  23153. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23154. if (light instanceof BABYLON.PointLight) {
  23155. serializationObject.type = 0;
  23156. serializationObject.position = light.position.asArray();
  23157. }
  23158. else if (light instanceof BABYLON.DirectionalLight) {
  23159. serializationObject.type = 1;
  23160. var directionalLight = light;
  23161. serializationObject.position = directionalLight.position.asArray();
  23162. serializationObject.direction = directionalLight.direction.asArray();
  23163. }
  23164. else if (light instanceof BABYLON.SpotLight) {
  23165. serializationObject.type = 2;
  23166. var spotLight = light;
  23167. serializationObject.position = spotLight.position.asArray();
  23168. serializationObject.direction = spotLight.position.asArray();
  23169. serializationObject.angle = spotLight.angle;
  23170. serializationObject.exponent = spotLight.exponent;
  23171. }
  23172. else if (light instanceof BABYLON.HemisphericLight) {
  23173. serializationObject.type = 3;
  23174. var hemisphericLight = light;
  23175. serializationObject.direction = hemisphericLight.direction.asArray();
  23176. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23177. }
  23178. if (light.intensity) {
  23179. serializationObject.intensity = light.intensity;
  23180. }
  23181. serializationObject.range = light.range;
  23182. serializationObject.diffuse = light.diffuse.asArray();
  23183. serializationObject.specular = light.specular.asArray();
  23184. return serializationObject;
  23185. };
  23186. var serializeFresnelParameter = function (fresnelParameter) {
  23187. var serializationObject = {};
  23188. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23189. serializationObject.leftColor = fresnelParameter.leftColor;
  23190. serializationObject.rightColor = fresnelParameter.rightColor;
  23191. serializationObject.bias = fresnelParameter.bias;
  23192. serializationObject.power = fresnelParameter.power;
  23193. return serializationObject;
  23194. };
  23195. var appendAnimations = function (source, destination) {
  23196. if (source.animations) {
  23197. destination.animations = [];
  23198. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23199. var animation = source.animations[animationIndex];
  23200. destination.animations.push(serializeAnimation(animation));
  23201. }
  23202. }
  23203. };
  23204. var serializeCamera = function (camera) {
  23205. var serializationObject = {};
  23206. serializationObject.name = camera.name;
  23207. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23208. serializationObject.id = camera.id;
  23209. serializationObject.position = camera.position.asArray();
  23210. // Parent
  23211. if (camera.parent) {
  23212. serializationObject.parentId = camera.parent.id;
  23213. }
  23214. serializationObject.fov = camera.fov;
  23215. serializationObject.minZ = camera.minZ;
  23216. serializationObject.maxZ = camera.maxZ;
  23217. serializationObject.inertia = camera.inertia;
  23218. //setting the type
  23219. if (camera instanceof BABYLON.FreeCamera) {
  23220. serializationObject.type = "FreeCamera";
  23221. }
  23222. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23223. serializationObject.type = "ArcRotateCamera";
  23224. }
  23225. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23226. serializationObject.type = "AnaglyphArcRotateCamera";
  23227. }
  23228. else if (camera instanceof BABYLON.GamepadCamera) {
  23229. serializationObject.type = "GamepadCamera";
  23230. }
  23231. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23232. serializationObject.type = "AnaglyphFreeCamera";
  23233. }
  23234. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23235. serializationObject.type = "DeviceOrientationCamera";
  23236. }
  23237. else if (camera instanceof BABYLON.FollowCamera) {
  23238. serializationObject.type = "FollowCamera";
  23239. }
  23240. else if (camera instanceof BABYLON.TouchCamera) {
  23241. serializationObject.type = "TouchCamera";
  23242. }
  23243. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23244. serializationObject.type = "VirtualJoysticksCamera";
  23245. }
  23246. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23247. serializationObject.type = "WebVRFreeCamera";
  23248. }
  23249. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23250. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23251. }
  23252. //special properties of specific cameras
  23253. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23254. var arcCamera = camera;
  23255. serializationObject.alpha = arcCamera.alpha;
  23256. serializationObject.beta = arcCamera.beta;
  23257. serializationObject.radius = arcCamera.radius;
  23258. if (arcCamera.target && arcCamera.target.id) {
  23259. serializationObject.lockedTargetId = arcCamera.target.id;
  23260. }
  23261. }
  23262. else if (camera instanceof BABYLON.FollowCamera) {
  23263. var followCam = camera;
  23264. serializationObject.radius = followCam.radius;
  23265. serializationObject.heightOffset = followCam.heightOffset;
  23266. serializationObject.rotationOffset = followCam.rotationOffset;
  23267. }
  23268. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23269. //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.
  23270. if (camera['_eyeSpace'] !== undefined) {
  23271. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  23272. }
  23273. }
  23274. //general properties that not all cameras have. The [] is due to typescript's type safety
  23275. if (camera['speed'] !== undefined) {
  23276. serializationObject.speed = camera['speed'];
  23277. }
  23278. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23279. serializationObject.target = camera['target'].asArray();
  23280. }
  23281. // Target
  23282. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23283. serializationObject.rotation = camera['rotation'].asArray();
  23284. }
  23285. // Locked target
  23286. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23287. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23288. }
  23289. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23290. serializationObject.applyGravity = camera['applyGravity'] || false;
  23291. if (camera['ellipsoid']) {
  23292. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23293. }
  23294. // Animations
  23295. appendAnimations(camera, serializationObject);
  23296. // Layer mask
  23297. serializationObject.layerMask = camera.layerMask;
  23298. return serializationObject;
  23299. };
  23300. var serializeAnimation = function (animation) {
  23301. var serializationObject = {};
  23302. serializationObject.name = animation.name;
  23303. serializationObject.property = animation.targetProperty;
  23304. serializationObject.framePerSecond = animation.framePerSecond;
  23305. serializationObject.dataType = animation.dataType;
  23306. serializationObject.loopBehavior = animation.loopMode;
  23307. var dataType = animation.dataType;
  23308. serializationObject.keys = [];
  23309. var keys = animation.getKeys();
  23310. for (var index = 0; index < keys.length; index++) {
  23311. var animationKey = keys[index];
  23312. var key = {};
  23313. key.frame = animationKey.frame;
  23314. switch (dataType) {
  23315. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23316. key.values = [animationKey.value];
  23317. break;
  23318. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23319. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23320. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23321. key.values = animationKey.value.asArray();
  23322. break;
  23323. }
  23324. serializationObject.keys.push(key);
  23325. }
  23326. return serializationObject;
  23327. };
  23328. var serializeMultiMaterial = function (material) {
  23329. var serializationObject = {};
  23330. serializationObject.name = material.name;
  23331. serializationObject.id = material.id;
  23332. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23333. serializationObject.materials = [];
  23334. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23335. var subMat = material.subMaterials[matIndex];
  23336. if (subMat) {
  23337. serializationObject.materials.push(subMat.id);
  23338. }
  23339. else {
  23340. serializationObject.materials.push(null);
  23341. }
  23342. }
  23343. return serializationObject;
  23344. };
  23345. var serializeMaterial = function (material) {
  23346. var serializationObject = {};
  23347. serializationObject.name = material.name;
  23348. serializationObject.ambient = material.ambientColor.asArray();
  23349. serializationObject.diffuse = material.diffuseColor.asArray();
  23350. serializationObject.specular = material.specularColor.asArray();
  23351. serializationObject.specularPower = material.specularPower;
  23352. serializationObject.emissive = material.emissiveColor.asArray();
  23353. serializationObject.alpha = material.alpha;
  23354. serializationObject.id = material.id;
  23355. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23356. serializationObject.backFaceCulling = material.backFaceCulling;
  23357. if (material.diffuseTexture) {
  23358. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23359. }
  23360. if (material.diffuseFresnelParameters) {
  23361. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23362. }
  23363. if (material.ambientTexture) {
  23364. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23365. }
  23366. if (material.opacityTexture) {
  23367. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23368. }
  23369. if (material.opacityFresnelParameters) {
  23370. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23371. }
  23372. if (material.reflectionTexture) {
  23373. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23374. }
  23375. if (material.reflectionFresnelParameters) {
  23376. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23377. }
  23378. if (material.emissiveTexture) {
  23379. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23380. }
  23381. if (material.emissiveFresnelParameters) {
  23382. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23383. }
  23384. if (material.specularTexture) {
  23385. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23386. }
  23387. if (material.bumpTexture) {
  23388. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23389. }
  23390. return serializationObject;
  23391. };
  23392. var serializeTexture = function (texture) {
  23393. var serializationObject = {};
  23394. if (!texture.name) {
  23395. return null;
  23396. }
  23397. if (texture instanceof BABYLON.CubeTexture) {
  23398. serializationObject.name = texture.name;
  23399. serializationObject.hasAlpha = texture.hasAlpha;
  23400. serializationObject.level = texture.level;
  23401. serializationObject.coordinatesMode = texture.coordinatesMode;
  23402. return serializationObject;
  23403. }
  23404. if (texture instanceof BABYLON.MirrorTexture) {
  23405. var mirrorTexture = texture;
  23406. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23407. serializationObject.renderList = [];
  23408. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23409. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23410. }
  23411. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23412. }
  23413. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23414. var renderTargetTexture = texture;
  23415. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23416. serializationObject.renderList = [];
  23417. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23418. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23419. }
  23420. }
  23421. var regularTexture = texture;
  23422. serializationObject.name = texture.name;
  23423. serializationObject.hasAlpha = texture.hasAlpha;
  23424. serializationObject.level = texture.level;
  23425. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23426. serializationObject.coordinatesMode = texture.coordinatesMode;
  23427. serializationObject.uOffset = regularTexture.uOffset;
  23428. serializationObject.vOffset = regularTexture.vOffset;
  23429. serializationObject.uScale = regularTexture.uScale;
  23430. serializationObject.vScale = regularTexture.vScale;
  23431. serializationObject.uAng = regularTexture.uAng;
  23432. serializationObject.vAng = regularTexture.vAng;
  23433. serializationObject.wAng = regularTexture.wAng;
  23434. serializationObject.wrapU = texture.wrapU;
  23435. serializationObject.wrapV = texture.wrapV;
  23436. // Animations
  23437. appendAnimations(texture, serializationObject);
  23438. return serializationObject;
  23439. };
  23440. var serializeSkeleton = function (skeleton) {
  23441. var serializationObject = {};
  23442. serializationObject.name = skeleton.name;
  23443. serializationObject.id = skeleton.id;
  23444. serializationObject.bones = [];
  23445. for (var index = 0; index < skeleton.bones.length; index++) {
  23446. var bone = skeleton.bones[index];
  23447. var serializedBone = {
  23448. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23449. name: bone.name,
  23450. matrix: bone.getLocalMatrix().toArray()
  23451. };
  23452. serializationObject.bones.push(serializedBone);
  23453. if (bone.animations && bone.animations.length > 0) {
  23454. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23455. }
  23456. }
  23457. return serializationObject;
  23458. };
  23459. var serializeParticleSystem = function (particleSystem) {
  23460. var serializationObject = {};
  23461. serializationObject.emitterId = particleSystem.emitter.id;
  23462. serializationObject.capacity = particleSystem.getCapacity();
  23463. if (particleSystem.particleTexture) {
  23464. serializationObject.textureName = particleSystem.particleTexture.name;
  23465. }
  23466. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23467. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23468. serializationObject.minSize = particleSystem.minSize;
  23469. serializationObject.maxSize = particleSystem.maxSize;
  23470. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23471. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23472. serializationObject.emitRate = particleSystem.emitRate;
  23473. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23474. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23475. serializationObject.gravity = particleSystem.gravity.asArray();
  23476. serializationObject.direction1 = particleSystem.direction1.asArray();
  23477. serializationObject.direction2 = particleSystem.direction2.asArray();
  23478. serializationObject.color1 = particleSystem.color1.asArray();
  23479. serializationObject.color2 = particleSystem.color2.asArray();
  23480. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23481. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23482. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23483. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23484. serializationObject.blendMode = particleSystem.blendMode;
  23485. return serializationObject;
  23486. };
  23487. var serializeLensFlareSystem = function (lensFlareSystem) {
  23488. var serializationObject = {};
  23489. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23490. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23491. serializationObject.flares = [];
  23492. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23493. var flare = lensFlareSystem.lensFlares[index];
  23494. serializationObject.flares.push({
  23495. size: flare.size,
  23496. position: flare.position,
  23497. color: flare.color.asArray(),
  23498. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23499. });
  23500. }
  23501. return serializationObject;
  23502. };
  23503. var serializeShadowGenerator = function (light) {
  23504. var serializationObject = {};
  23505. var shadowGenerator = light.getShadowGenerator();
  23506. serializationObject.lightId = light.id;
  23507. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23508. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23509. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23510. serializationObject.renderList = [];
  23511. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23512. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23513. serializationObject.renderList.push(mesh.id);
  23514. }
  23515. return serializationObject;
  23516. };
  23517. var serializedGeometries = [];
  23518. var serializeGeometry = function (geometry, serializationGeometries) {
  23519. if (serializedGeometries[geometry.id]) {
  23520. return;
  23521. }
  23522. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23523. serializationGeometries.boxes.push(serializeBox(geometry));
  23524. }
  23525. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23526. serializationGeometries.spheres.push(serializeSphere(geometry));
  23527. }
  23528. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23529. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23530. }
  23531. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23532. serializationGeometries.toruses.push(serializeTorus(geometry));
  23533. }
  23534. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23535. serializationGeometries.grounds.push(serializeGround(geometry));
  23536. }
  23537. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23538. serializationGeometries.planes.push(serializePlane(geometry));
  23539. }
  23540. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23541. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23542. }
  23543. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23544. throw new Error("Unknow primitive type");
  23545. }
  23546. else {
  23547. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23548. }
  23549. serializedGeometries[geometry.id] = true;
  23550. };
  23551. var serializeGeometryBase = function (geometry) {
  23552. var serializationObject = {};
  23553. serializationObject.id = geometry.id;
  23554. if (BABYLON.Tags.HasTags(geometry)) {
  23555. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23556. }
  23557. return serializationObject;
  23558. };
  23559. var serializeVertexData = function (vertexData) {
  23560. var serializationObject = serializeGeometryBase(vertexData);
  23561. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23562. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23563. }
  23564. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23565. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23566. }
  23567. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23568. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23569. }
  23570. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23571. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23572. }
  23573. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23574. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23575. }
  23576. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23577. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23578. serializationObject.matricesIndices._isExpanded = true;
  23579. }
  23580. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23581. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23582. }
  23583. serializationObject.indices = vertexData.getIndices();
  23584. return serializationObject;
  23585. };
  23586. var serializePrimitive = function (primitive) {
  23587. var serializationObject = serializeGeometryBase(primitive);
  23588. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23589. return serializationObject;
  23590. };
  23591. var serializeBox = function (box) {
  23592. var serializationObject = serializePrimitive(box);
  23593. serializationObject.size = box.size;
  23594. return serializationObject;
  23595. };
  23596. var serializeSphere = function (sphere) {
  23597. var serializationObject = serializePrimitive(sphere);
  23598. serializationObject.segments = sphere.segments;
  23599. serializationObject.diameter = sphere.diameter;
  23600. return serializationObject;
  23601. };
  23602. var serializeCylinder = function (cylinder) {
  23603. var serializationObject = serializePrimitive(cylinder);
  23604. serializationObject.height = cylinder.height;
  23605. serializationObject.diameterTop = cylinder.diameterTop;
  23606. serializationObject.diameterBottom = cylinder.diameterBottom;
  23607. serializationObject.tessellation = cylinder.tessellation;
  23608. return serializationObject;
  23609. };
  23610. var serializeTorus = function (torus) {
  23611. var serializationObject = serializePrimitive(torus);
  23612. serializationObject.diameter = torus.diameter;
  23613. serializationObject.thickness = torus.thickness;
  23614. serializationObject.tessellation = torus.tessellation;
  23615. return serializationObject;
  23616. };
  23617. var serializeGround = function (ground) {
  23618. var serializationObject = serializePrimitive(ground);
  23619. serializationObject.width = ground.width;
  23620. serializationObject.height = ground.height;
  23621. serializationObject.subdivisions = ground.subdivisions;
  23622. return serializationObject;
  23623. };
  23624. var serializePlane = function (plane) {
  23625. var serializationObject = serializePrimitive(plane);
  23626. serializationObject.size = plane.size;
  23627. return serializationObject;
  23628. };
  23629. var serializeTorusKnot = function (torusKnot) {
  23630. var serializationObject = serializePrimitive(torusKnot);
  23631. serializationObject.radius = torusKnot.radius;
  23632. serializationObject.tube = torusKnot.tube;
  23633. serializationObject.radialSegments = torusKnot.radialSegments;
  23634. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23635. serializationObject.p = torusKnot.p;
  23636. serializationObject.q = torusKnot.q;
  23637. return serializationObject;
  23638. };
  23639. var serializeMesh = function (mesh, serializationScene) {
  23640. var serializationObject = {};
  23641. serializationObject.name = mesh.name;
  23642. serializationObject.id = mesh.id;
  23643. if (BABYLON.Tags.HasTags(mesh)) {
  23644. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23645. }
  23646. serializationObject.position = mesh.position.asArray();
  23647. if (mesh.rotationQuaternion) {
  23648. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23649. }
  23650. else if (mesh.rotation) {
  23651. serializationObject.rotation = mesh.rotation.asArray();
  23652. }
  23653. serializationObject.scaling = mesh.scaling.asArray();
  23654. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23655. serializationObject.isEnabled = mesh.isEnabled();
  23656. serializationObject.isVisible = mesh.isVisible;
  23657. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23658. serializationObject.pickable = mesh.isPickable;
  23659. serializationObject.receiveShadows = mesh.receiveShadows;
  23660. serializationObject.billboardMode = mesh.billboardMode;
  23661. serializationObject.visibility = mesh.visibility;
  23662. serializationObject.checkCollisions = mesh.checkCollisions;
  23663. // Parent
  23664. if (mesh.parent) {
  23665. serializationObject.parentId = mesh.parent.id;
  23666. }
  23667. // Geometry
  23668. var geometry = mesh._geometry;
  23669. if (geometry) {
  23670. var geometryId = geometry.id;
  23671. serializationObject.geometryId = geometryId;
  23672. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23673. // 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
  23674. serializeGeometry(geometry, serializationScene.geometries);
  23675. }
  23676. // SubMeshes
  23677. serializationObject.subMeshes = [];
  23678. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23679. var subMesh = mesh.subMeshes[subIndex];
  23680. serializationObject.subMeshes.push({
  23681. materialIndex: subMesh.materialIndex,
  23682. verticesStart: subMesh.verticesStart,
  23683. verticesCount: subMesh.verticesCount,
  23684. indexStart: subMesh.indexStart,
  23685. indexCount: subMesh.indexCount
  23686. });
  23687. }
  23688. }
  23689. // Material
  23690. if (mesh.material) {
  23691. serializationObject.materialId = mesh.material.id;
  23692. }
  23693. else {
  23694. mesh.material = null;
  23695. }
  23696. // Skeleton
  23697. if (mesh.skeleton) {
  23698. serializationObject.skeletonId = mesh.skeleton.id;
  23699. }
  23700. // Physics
  23701. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23702. serializationObject.physicsMass = mesh.getPhysicsMass();
  23703. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23704. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23705. switch (mesh.getPhysicsImpostor()) {
  23706. case BABYLON.PhysicsEngine.BoxImpostor:
  23707. serializationObject.physicsImpostor = 1;
  23708. break;
  23709. case BABYLON.PhysicsEngine.SphereImpostor:
  23710. serializationObject.physicsImpostor = 2;
  23711. break;
  23712. }
  23713. }
  23714. // Instances
  23715. serializationObject.instances = [];
  23716. for (var index = 0; index < mesh.instances.length; index++) {
  23717. var instance = mesh.instances[index];
  23718. var serializationInstance = {
  23719. name: instance.name,
  23720. position: instance.position,
  23721. rotation: instance.rotation,
  23722. rotationQuaternion: instance.rotationQuaternion,
  23723. scaling: instance.scaling
  23724. };
  23725. serializationObject.instances.push(serializationInstance);
  23726. // Animations
  23727. appendAnimations(instance, serializationInstance);
  23728. }
  23729. // Animations
  23730. appendAnimations(mesh, serializationObject);
  23731. // Layer mask
  23732. serializationObject.layerMask = mesh.layerMask;
  23733. return serializationObject;
  23734. };
  23735. var SceneSerializer = (function () {
  23736. function SceneSerializer() {
  23737. }
  23738. SceneSerializer.Serialize = function (scene) {
  23739. var serializationObject = {};
  23740. // Scene
  23741. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23742. serializationObject.autoClear = scene.autoClear;
  23743. serializationObject.clearColor = scene.clearColor.asArray();
  23744. serializationObject.ambientColor = scene.ambientColor.asArray();
  23745. serializationObject.gravity = scene.gravity.asArray();
  23746. // Fog
  23747. if (scene.fogMode && scene.fogMode !== 0) {
  23748. serializationObject.fogMode = scene.fogMode;
  23749. serializationObject.fogColor = scene.fogColor.asArray();
  23750. serializationObject.fogStart = scene.fogStart;
  23751. serializationObject.fogEnd = scene.fogEnd;
  23752. serializationObject.fogDensity = scene.fogDensity;
  23753. }
  23754. // Lights
  23755. serializationObject.lights = [];
  23756. for (var index = 0; index < scene.lights.length; index++) {
  23757. var light = scene.lights[index];
  23758. serializationObject.lights.push(serializeLight(light));
  23759. }
  23760. // Cameras
  23761. serializationObject.cameras = [];
  23762. for (index = 0; index < scene.cameras.length; index++) {
  23763. var camera = scene.cameras[index];
  23764. serializationObject.cameras.push(serializeCamera(camera));
  23765. }
  23766. if (scene.activeCamera) {
  23767. serializationObject.activeCameraID = scene.activeCamera.id;
  23768. }
  23769. // Materials
  23770. serializationObject.materials = [];
  23771. serializationObject.multiMaterials = [];
  23772. for (index = 0; index < scene.materials.length; index++) {
  23773. var material = scene.materials[index];
  23774. if (material instanceof BABYLON.StandardMaterial) {
  23775. serializationObject.materials.push(serializeMaterial(material));
  23776. }
  23777. else if (material instanceof BABYLON.MultiMaterial) {
  23778. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23779. }
  23780. }
  23781. // Skeletons
  23782. serializationObject.skeletons = [];
  23783. for (index = 0; index < scene.skeletons.length; index++) {
  23784. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23785. }
  23786. // Geometries
  23787. serializationObject.geometries = {};
  23788. serializationObject.geometries.boxes = [];
  23789. serializationObject.geometries.spheres = [];
  23790. serializationObject.geometries.cylinders = [];
  23791. serializationObject.geometries.toruses = [];
  23792. serializationObject.geometries.grounds = [];
  23793. serializationObject.geometries.planes = [];
  23794. serializationObject.geometries.torusKnots = [];
  23795. serializationObject.geometries.vertexData = [];
  23796. serializedGeometries = [];
  23797. var geometries = scene.getGeometries();
  23798. for (index = 0; index < geometries.length; index++) {
  23799. var geometry = geometries[index];
  23800. if (geometry.isReady()) {
  23801. serializeGeometry(geometry, serializationObject.geometries);
  23802. }
  23803. }
  23804. // Meshes
  23805. serializationObject.meshes = [];
  23806. for (index = 0; index < scene.meshes.length; index++) {
  23807. var abstractMesh = scene.meshes[index];
  23808. if (abstractMesh instanceof BABYLON.Mesh) {
  23809. var mesh = abstractMesh;
  23810. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23811. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23812. }
  23813. }
  23814. }
  23815. // Particles Systems
  23816. serializationObject.particleSystems = [];
  23817. for (index = 0; index < scene.particleSystems.length; index++) {
  23818. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23819. }
  23820. // Lens flares
  23821. serializationObject.lensFlareSystems = [];
  23822. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23823. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23824. }
  23825. // Shadows
  23826. serializationObject.shadowGenerators = [];
  23827. for (index = 0; index < scene.lights.length; index++) {
  23828. light = scene.lights[index];
  23829. if (light.getShadowGenerator()) {
  23830. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23831. }
  23832. }
  23833. return serializationObject;
  23834. };
  23835. return SceneSerializer;
  23836. })();
  23837. BABYLON.SceneSerializer = SceneSerializer;
  23838. })(BABYLON || (BABYLON = {}));
  23839. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23840. var BABYLON;
  23841. (function (BABYLON) {
  23842. // Unique ID when we import meshes from Babylon to CSG
  23843. var currentCSGMeshId = 0;
  23844. // # class Vertex
  23845. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23846. // one to provide additional features like texture coordinates and vertex
  23847. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23848. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23849. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23850. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23851. // is not used anywhere else.
  23852. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23853. var Vertex = (function () {
  23854. function Vertex(pos, normal, uv) {
  23855. this.pos = pos;
  23856. this.normal = normal;
  23857. this.uv = uv;
  23858. }
  23859. Vertex.prototype.clone = function () {
  23860. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23861. };
  23862. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23863. // orientation of a polygon is flipped.
  23864. Vertex.prototype.flip = function () {
  23865. this.normal = this.normal.scale(-1);
  23866. };
  23867. // Create a new vertex between this vertex and `other` by linearly
  23868. // interpolating all properties using a parameter of `t`. Subclasses should
  23869. // override this to interpolate additional properties.
  23870. Vertex.prototype.interpolate = function (other, t) {
  23871. 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));
  23872. };
  23873. return Vertex;
  23874. })();
  23875. // # class Plane
  23876. // Represents a plane in 3D space.
  23877. var Plane = (function () {
  23878. function Plane(normal, w) {
  23879. this.normal = normal;
  23880. this.w = w;
  23881. }
  23882. Plane.FromPoints = function (a, b, c) {
  23883. var v0 = c.subtract(a);
  23884. var v1 = b.subtract(a);
  23885. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23886. return null;
  23887. }
  23888. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23889. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23890. };
  23891. Plane.prototype.clone = function () {
  23892. return new Plane(this.normal.clone(), this.w);
  23893. };
  23894. Plane.prototype.flip = function () {
  23895. this.normal.scaleInPlace(-1);
  23896. this.w = -this.w;
  23897. };
  23898. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23899. // fragments in the appropriate lists. Coplanar polygons go into either
  23900. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23901. // respect to this plane. Polygons in front or in back of this plane go into
  23902. // either `front` or `back`.
  23903. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23904. var COPLANAR = 0;
  23905. var FRONT = 1;
  23906. var BACK = 2;
  23907. var SPANNING = 3;
  23908. // Classify each point as well as the entire polygon into one of the above
  23909. // four classes.
  23910. var polygonType = 0;
  23911. var types = [];
  23912. for (var i = 0; i < polygon.vertices.length; i++) {
  23913. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23914. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23915. polygonType |= type;
  23916. types.push(type);
  23917. }
  23918. // Put the polygon in the correct list, splitting it when necessary.
  23919. switch (polygonType) {
  23920. case COPLANAR:
  23921. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23922. break;
  23923. case FRONT:
  23924. front.push(polygon);
  23925. break;
  23926. case BACK:
  23927. back.push(polygon);
  23928. break;
  23929. case SPANNING:
  23930. var f = [], b = [];
  23931. for (i = 0; i < polygon.vertices.length; i++) {
  23932. var j = (i + 1) % polygon.vertices.length;
  23933. var ti = types[i], tj = types[j];
  23934. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23935. if (ti != BACK)
  23936. f.push(vi);
  23937. if (ti != FRONT)
  23938. b.push(ti != BACK ? vi.clone() : vi);
  23939. if ((ti | tj) == SPANNING) {
  23940. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23941. var v = vi.interpolate(vj, t);
  23942. f.push(v);
  23943. b.push(v.clone());
  23944. }
  23945. }
  23946. if (f.length >= 3) {
  23947. var poly = new Polygon(f, polygon.shared);
  23948. if (poly.plane)
  23949. front.push(poly);
  23950. }
  23951. if (b.length >= 3) {
  23952. poly = new Polygon(b, polygon.shared);
  23953. if (poly.plane)
  23954. back.push(poly);
  23955. }
  23956. break;
  23957. }
  23958. };
  23959. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23960. // point is on the plane.
  23961. Plane.EPSILON = 1e-5;
  23962. return Plane;
  23963. })();
  23964. // # class Polygon
  23965. // Represents a convex polygon. The vertices used to initialize a polygon must
  23966. // be coplanar and form a convex loop.
  23967. //
  23968. // Each convex polygon has a `shared` property, which is shared between all
  23969. // polygons that are clones of each other or were split from the same polygon.
  23970. // This can be used to define per-polygon properties (such as surface color).
  23971. var Polygon = (function () {
  23972. function Polygon(vertices, shared) {
  23973. this.vertices = vertices;
  23974. this.shared = shared;
  23975. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23976. }
  23977. Polygon.prototype.clone = function () {
  23978. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23979. return new Polygon(vertices, this.shared);
  23980. };
  23981. Polygon.prototype.flip = function () {
  23982. this.vertices.reverse().map(function (v) { v.flip(); });
  23983. this.plane.flip();
  23984. };
  23985. return Polygon;
  23986. })();
  23987. // # class Node
  23988. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23989. // by picking a polygon to split along. That polygon (and all other coplanar
  23990. // polygons) are added directly to that node and the other polygons are added to
  23991. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23992. // no distinction between internal and leaf nodes.
  23993. var Node = (function () {
  23994. function Node(polygons) {
  23995. this.plane = null;
  23996. this.front = null;
  23997. this.back = null;
  23998. this.polygons = [];
  23999. if (polygons) {
  24000. this.build(polygons);
  24001. }
  24002. }
  24003. Node.prototype.clone = function () {
  24004. var node = new Node();
  24005. node.plane = this.plane && this.plane.clone();
  24006. node.front = this.front && this.front.clone();
  24007. node.back = this.back && this.back.clone();
  24008. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24009. return node;
  24010. };
  24011. // Convert solid space to empty space and empty space to solid space.
  24012. Node.prototype.invert = function () {
  24013. for (var i = 0; i < this.polygons.length; i++) {
  24014. this.polygons[i].flip();
  24015. }
  24016. if (this.plane) {
  24017. this.plane.flip();
  24018. }
  24019. if (this.front) {
  24020. this.front.invert();
  24021. }
  24022. if (this.back) {
  24023. this.back.invert();
  24024. }
  24025. var temp = this.front;
  24026. this.front = this.back;
  24027. this.back = temp;
  24028. };
  24029. // Recursively remove all polygons in `polygons` that are inside this BSP
  24030. // tree.
  24031. Node.prototype.clipPolygons = function (polygons) {
  24032. if (!this.plane)
  24033. return polygons.slice();
  24034. var front = [], back = [];
  24035. for (var i = 0; i < polygons.length; i++) {
  24036. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24037. }
  24038. if (this.front) {
  24039. front = this.front.clipPolygons(front);
  24040. }
  24041. if (this.back) {
  24042. back = this.back.clipPolygons(back);
  24043. }
  24044. else {
  24045. back = [];
  24046. }
  24047. return front.concat(back);
  24048. };
  24049. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24050. // `bsp`.
  24051. Node.prototype.clipTo = function (bsp) {
  24052. this.polygons = bsp.clipPolygons(this.polygons);
  24053. if (this.front)
  24054. this.front.clipTo(bsp);
  24055. if (this.back)
  24056. this.back.clipTo(bsp);
  24057. };
  24058. // Return a list of all polygons in this BSP tree.
  24059. Node.prototype.allPolygons = function () {
  24060. var polygons = this.polygons.slice();
  24061. if (this.front)
  24062. polygons = polygons.concat(this.front.allPolygons());
  24063. if (this.back)
  24064. polygons = polygons.concat(this.back.allPolygons());
  24065. return polygons;
  24066. };
  24067. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24068. // new polygons are filtered down to the bottom of the tree and become new
  24069. // nodes there. Each set of polygons is partitioned using the first polygon
  24070. // (no heuristic is used to pick a good split).
  24071. Node.prototype.build = function (polygons) {
  24072. if (!polygons.length)
  24073. return;
  24074. if (!this.plane)
  24075. this.plane = polygons[0].plane.clone();
  24076. var front = [], back = [];
  24077. for (var i = 0; i < polygons.length; i++) {
  24078. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24079. }
  24080. if (front.length) {
  24081. if (!this.front)
  24082. this.front = new Node();
  24083. this.front.build(front);
  24084. }
  24085. if (back.length) {
  24086. if (!this.back)
  24087. this.back = new Node();
  24088. this.back.build(back);
  24089. }
  24090. };
  24091. return Node;
  24092. })();
  24093. var CSG = (function () {
  24094. function CSG() {
  24095. this.polygons = new Array();
  24096. }
  24097. // Convert BABYLON.Mesh to BABYLON.CSG
  24098. CSG.FromMesh = function (mesh) {
  24099. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  24100. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  24101. if (mesh instanceof BABYLON.Mesh) {
  24102. mesh.computeWorldMatrix(true);
  24103. matrix = mesh.getWorldMatrix();
  24104. meshPosition = mesh.position.clone();
  24105. meshRotation = mesh.rotation.clone();
  24106. if (mesh.rotationQuaternion) {
  24107. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24108. }
  24109. meshScaling = mesh.scaling.clone();
  24110. }
  24111. else {
  24112. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24113. }
  24114. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24115. var subMeshes = mesh.subMeshes;
  24116. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24117. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24118. vertices = [];
  24119. for (var j = 0; j < 3; j++) {
  24120. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24121. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24122. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24123. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24124. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24125. vertex = new Vertex(position, normal, uv);
  24126. vertices.push(vertex);
  24127. }
  24128. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24129. // To handle the case of degenerated triangle
  24130. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24131. if (polygon.plane)
  24132. polygons.push(polygon);
  24133. }
  24134. }
  24135. var csg = CSG.FromPolygons(polygons);
  24136. csg.matrix = matrix;
  24137. csg.position = meshPosition;
  24138. csg.rotation = meshRotation;
  24139. csg.scaling = meshScaling;
  24140. csg.rotationQuaternion = meshRotationQuaternion;
  24141. currentCSGMeshId++;
  24142. return csg;
  24143. };
  24144. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24145. CSG.FromPolygons = function (polygons) {
  24146. var csg = new BABYLON.CSG();
  24147. csg.polygons = polygons;
  24148. return csg;
  24149. };
  24150. CSG.prototype.clone = function () {
  24151. var csg = new BABYLON.CSG();
  24152. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24153. csg.copyTransformAttributes(this);
  24154. return csg;
  24155. };
  24156. CSG.prototype.toPolygons = function () {
  24157. return this.polygons;
  24158. };
  24159. CSG.prototype.union = function (csg) {
  24160. var a = new Node(this.clone().polygons);
  24161. var b = new Node(csg.clone().polygons);
  24162. a.clipTo(b);
  24163. b.clipTo(a);
  24164. b.invert();
  24165. b.clipTo(a);
  24166. b.invert();
  24167. a.build(b.allPolygons());
  24168. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24169. };
  24170. CSG.prototype.unionInPlace = function (csg) {
  24171. var a = new Node(this.polygons);
  24172. var b = new Node(csg.polygons);
  24173. a.clipTo(b);
  24174. b.clipTo(a);
  24175. b.invert();
  24176. b.clipTo(a);
  24177. b.invert();
  24178. a.build(b.allPolygons());
  24179. this.polygons = a.allPolygons();
  24180. };
  24181. CSG.prototype.subtract = function (csg) {
  24182. var a = new Node(this.clone().polygons);
  24183. var b = new Node(csg.clone().polygons);
  24184. a.invert();
  24185. a.clipTo(b);
  24186. b.clipTo(a);
  24187. b.invert();
  24188. b.clipTo(a);
  24189. b.invert();
  24190. a.build(b.allPolygons());
  24191. a.invert();
  24192. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24193. };
  24194. CSG.prototype.subtractInPlace = function (csg) {
  24195. var a = new Node(this.polygons);
  24196. var b = new Node(csg.polygons);
  24197. a.invert();
  24198. a.clipTo(b);
  24199. b.clipTo(a);
  24200. b.invert();
  24201. b.clipTo(a);
  24202. b.invert();
  24203. a.build(b.allPolygons());
  24204. a.invert();
  24205. this.polygons = a.allPolygons();
  24206. };
  24207. CSG.prototype.intersect = function (csg) {
  24208. var a = new Node(this.clone().polygons);
  24209. var b = new Node(csg.clone().polygons);
  24210. a.invert();
  24211. b.clipTo(a);
  24212. b.invert();
  24213. a.clipTo(b);
  24214. b.clipTo(a);
  24215. a.build(b.allPolygons());
  24216. a.invert();
  24217. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24218. };
  24219. CSG.prototype.intersectInPlace = function (csg) {
  24220. var a = new Node(this.polygons);
  24221. var b = new Node(csg.polygons);
  24222. a.invert();
  24223. b.clipTo(a);
  24224. b.invert();
  24225. a.clipTo(b);
  24226. b.clipTo(a);
  24227. a.build(b.allPolygons());
  24228. a.invert();
  24229. this.polygons = a.allPolygons();
  24230. };
  24231. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24232. // not modified.
  24233. CSG.prototype.inverse = function () {
  24234. var csg = this.clone();
  24235. csg.inverseInPlace();
  24236. return csg;
  24237. };
  24238. CSG.prototype.inverseInPlace = function () {
  24239. this.polygons.map(function (p) { p.flip(); });
  24240. };
  24241. // This is used to keep meshes transformations so they can be restored
  24242. // when we build back a Babylon Mesh
  24243. // NB : All CSG operations are performed in world coordinates
  24244. CSG.prototype.copyTransformAttributes = function (csg) {
  24245. this.matrix = csg.matrix;
  24246. this.position = csg.position;
  24247. this.rotation = csg.rotation;
  24248. this.scaling = csg.scaling;
  24249. this.rotationQuaternion = csg.rotationQuaternion;
  24250. return this;
  24251. };
  24252. // Build Raw mesh from CSG
  24253. // Coordinates here are in world space
  24254. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24255. var matrix = this.matrix.clone();
  24256. matrix.invert();
  24257. 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;
  24258. if (keepSubMeshes) {
  24259. // Sort Polygons, since subMeshes are indices range
  24260. polygons.sort(function (a, b) {
  24261. if (a.shared.meshId === b.shared.meshId) {
  24262. return a.shared.subMeshId - b.shared.subMeshId;
  24263. }
  24264. else {
  24265. return a.shared.meshId - b.shared.meshId;
  24266. }
  24267. });
  24268. }
  24269. for (var i = 0, il = polygons.length; i < il; i++) {
  24270. polygon = polygons[i];
  24271. // Building SubMeshes
  24272. if (!subMesh_dict[polygon.shared.meshId]) {
  24273. subMesh_dict[polygon.shared.meshId] = {};
  24274. }
  24275. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24276. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24277. indexStart: +Infinity,
  24278. indexEnd: -Infinity,
  24279. materialIndex: polygon.shared.materialIndex
  24280. };
  24281. }
  24282. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24283. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24284. polygonIndices[0] = 0;
  24285. polygonIndices[1] = j - 1;
  24286. polygonIndices[2] = j;
  24287. for (var k = 0; k < 3; k++) {
  24288. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24289. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24290. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24291. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24292. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24293. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24294. // Check if 2 points can be merged
  24295. if (!(typeof vertex_idx !== 'undefined' &&
  24296. normals[vertex_idx * 3] === localNormal.x &&
  24297. normals[vertex_idx * 3 + 1] === localNormal.y &&
  24298. normals[vertex_idx * 3 + 2] === localNormal.z &&
  24299. uvs[vertex_idx * 2] === uv.x &&
  24300. uvs[vertex_idx * 2 + 1] === uv.y)) {
  24301. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24302. uvs.push(uv.x, uv.y);
  24303. normals.push(normal.x, normal.y, normal.z);
  24304. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24305. }
  24306. indices.push(vertex_idx);
  24307. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24308. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24309. currentIndex++;
  24310. }
  24311. }
  24312. }
  24313. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24314. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24315. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24316. mesh.setIndices(indices);
  24317. if (keepSubMeshes) {
  24318. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24319. var materialIndexOffset = 0, materialMaxIndex;
  24320. mesh.subMeshes.length = 0;
  24321. for (var m in subMesh_dict) {
  24322. materialMaxIndex = -1;
  24323. for (var sm in subMesh_dict[m]) {
  24324. subMesh_obj = subMesh_dict[m][sm];
  24325. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24326. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24327. }
  24328. materialIndexOffset += ++materialMaxIndex;
  24329. }
  24330. }
  24331. return mesh;
  24332. };
  24333. // Build Mesh from CSG taking material and transforms into account
  24334. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24335. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24336. mesh.material = material;
  24337. mesh.position.copyFrom(this.position);
  24338. mesh.rotation.copyFrom(this.rotation);
  24339. if (this.rotationQuaternion) {
  24340. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  24341. }
  24342. mesh.scaling.copyFrom(this.scaling);
  24343. mesh.computeWorldMatrix(true);
  24344. return mesh;
  24345. };
  24346. return CSG;
  24347. })();
  24348. BABYLON.CSG = CSG;
  24349. })(BABYLON || (BABYLON = {}));
  24350. //# sourceMappingURL=babylon.csg.js.map
  24351. var __extends = (this && this.__extends) || function (d, b) {
  24352. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24353. function __() { this.constructor = d; }
  24354. __.prototype = b.prototype;
  24355. d.prototype = new __();
  24356. };
  24357. var BABYLON;
  24358. (function (BABYLON) {
  24359. var VRDistortionCorrectionPostProcess = (function (_super) {
  24360. __extends(VRDistortionCorrectionPostProcess, _super);
  24361. //ANY
  24362. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24363. var _this = this;
  24364. _super.call(this, name, "vrDistortionCorrection", [
  24365. 'LensCenter',
  24366. 'Scale',
  24367. 'ScaleIn',
  24368. 'HmdWarpParam'
  24369. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24370. this._isRightEye = isRightEye;
  24371. this._distortionFactors = vrMetrics.distortionK;
  24372. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24373. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24374. this.onSizeChanged = function () {
  24375. _this.aspectRatio = _this.width * .5 / _this.height;
  24376. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24377. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24378. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24379. };
  24380. this.onApply = function (effect) {
  24381. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24382. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24383. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24384. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24385. };
  24386. }
  24387. return VRDistortionCorrectionPostProcess;
  24388. })(BABYLON.PostProcess);
  24389. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24390. })(BABYLON || (BABYLON = {}));
  24391. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24392. // Mainly based on these 2 articles :
  24393. // 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
  24394. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24395. var BABYLON;
  24396. (function (BABYLON) {
  24397. (function (JoystickAxis) {
  24398. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24399. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24400. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24401. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24402. var JoystickAxis = BABYLON.JoystickAxis;
  24403. var VirtualJoystick = (function () {
  24404. function VirtualJoystick(leftJoystick) {
  24405. var _this = this;
  24406. if (leftJoystick) {
  24407. this._leftJoystick = true;
  24408. }
  24409. else {
  24410. this._leftJoystick = false;
  24411. }
  24412. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24413. VirtualJoystick._globalJoystickIndex++;
  24414. // By default left & right arrow keys are moving the X
  24415. // and up & down keys are moving the Y
  24416. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24417. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24418. this.reverseLeftRight = false;
  24419. this.reverseUpDown = false;
  24420. // collections of pointers
  24421. this._touches = new BABYLON.SmartCollection();
  24422. this.deltaPosition = BABYLON.Vector3.Zero();
  24423. this._joystickSensibility = 25;
  24424. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24425. this._rotationSpeed = 25;
  24426. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24427. this._rotateOnAxisRelativeToMesh = false;
  24428. // injecting a canvas element on top of the canvas 3D game
  24429. if (!VirtualJoystick.vjCanvas) {
  24430. window.addEventListener("resize", function () {
  24431. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24432. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24433. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24434. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24435. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24436. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24437. }, false);
  24438. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24439. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24440. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24441. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24442. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24443. VirtualJoystick.vjCanvas.style.width = "100%";
  24444. VirtualJoystick.vjCanvas.style.height = "100%";
  24445. VirtualJoystick.vjCanvas.style.position = "absolute";
  24446. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24447. VirtualJoystick.vjCanvas.style.top = "0px";
  24448. VirtualJoystick.vjCanvas.style.left = "0px";
  24449. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24450. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24451. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24452. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24453. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24454. document.body.appendChild(VirtualJoystick.vjCanvas);
  24455. }
  24456. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24457. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24458. this.pressed = false;
  24459. // default joystick color
  24460. this._joystickColor = "cyan";
  24461. this._joystickPointerID = -1;
  24462. // current joystick position
  24463. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24464. // origin joystick position
  24465. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24466. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24467. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24468. _this._onPointerDown(evt);
  24469. }, false);
  24470. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24471. _this._onPointerMove(evt);
  24472. }, false);
  24473. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24474. _this._onPointerUp(evt);
  24475. }, false);
  24476. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24477. _this._onPointerUp(evt);
  24478. }, false);
  24479. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24480. evt.preventDefault(); // Disables system menu
  24481. }, false);
  24482. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24483. }
  24484. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24485. this._joystickSensibility = newJoystickSensibility;
  24486. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24487. };
  24488. VirtualJoystick.prototype._onPointerDown = function (e) {
  24489. var positionOnScreenCondition;
  24490. e.preventDefault();
  24491. if (this._leftJoystick === true) {
  24492. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24493. }
  24494. else {
  24495. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24496. }
  24497. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24498. // First contact will be dedicated to the virtual joystick
  24499. this._joystickPointerID = e.pointerId;
  24500. this._joystickPointerStartPos.x = e.clientX;
  24501. this._joystickPointerStartPos.y = e.clientY;
  24502. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24503. this._deltaJoystickVector.x = 0;
  24504. this._deltaJoystickVector.y = 0;
  24505. this.pressed = true;
  24506. this._touches.add(e.pointerId.toString(), e);
  24507. }
  24508. else {
  24509. // You can only trigger the action buttons with a joystick declared
  24510. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24511. this._action();
  24512. this._touches.add(e.pointerId.toString(), e);
  24513. }
  24514. }
  24515. };
  24516. VirtualJoystick.prototype._onPointerMove = function (e) {
  24517. // If the current pointer is the one associated to the joystick (first touch contact)
  24518. if (this._joystickPointerID == e.pointerId) {
  24519. this._joystickPointerPos.x = e.clientX;
  24520. this._joystickPointerPos.y = e.clientY;
  24521. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24522. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24523. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24524. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24525. switch (this._axisTargetedByLeftAndRight) {
  24526. case JoystickAxis.X:
  24527. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24528. break;
  24529. case JoystickAxis.Y:
  24530. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24531. break;
  24532. case JoystickAxis.Z:
  24533. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24534. break;
  24535. }
  24536. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24537. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24538. switch (this._axisTargetedByUpAndDown) {
  24539. case JoystickAxis.X:
  24540. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24541. break;
  24542. case JoystickAxis.Y:
  24543. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24544. break;
  24545. case JoystickAxis.Z:
  24546. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24547. break;
  24548. }
  24549. }
  24550. else {
  24551. if (this._touches.item(e.pointerId.toString())) {
  24552. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24553. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24554. }
  24555. }
  24556. };
  24557. VirtualJoystick.prototype._onPointerUp = function (e) {
  24558. this._clearCanvas();
  24559. if (this._joystickPointerID == e.pointerId) {
  24560. this._joystickPointerID = -1;
  24561. this.pressed = false;
  24562. }
  24563. this._deltaJoystickVector.x = 0;
  24564. this._deltaJoystickVector.y = 0;
  24565. this._touches.remove(e.pointerId.toString());
  24566. };
  24567. /**
  24568. * Change the color of the virtual joystick
  24569. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24570. */
  24571. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24572. this._joystickColor = newColor;
  24573. };
  24574. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24575. this._action = action;
  24576. };
  24577. // Define which axis you'd like to control for left & right
  24578. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24579. switch (axis) {
  24580. case JoystickAxis.X:
  24581. case JoystickAxis.Y:
  24582. case JoystickAxis.Z:
  24583. this._axisTargetedByLeftAndRight = axis;
  24584. break;
  24585. default:
  24586. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24587. break;
  24588. }
  24589. };
  24590. // Define which axis you'd like to control for up & down
  24591. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24592. switch (axis) {
  24593. case JoystickAxis.X:
  24594. case JoystickAxis.Y:
  24595. case JoystickAxis.Z:
  24596. this._axisTargetedByUpAndDown = axis;
  24597. break;
  24598. default:
  24599. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24600. break;
  24601. }
  24602. };
  24603. VirtualJoystick.prototype._clearCanvas = function () {
  24604. if (this._leftJoystick) {
  24605. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24606. }
  24607. else {
  24608. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24609. }
  24610. };
  24611. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24612. var _this = this;
  24613. if (this.pressed) {
  24614. this._clearCanvas();
  24615. this._touches.forEach(function (touch) {
  24616. if (touch.pointerId === _this._joystickPointerID) {
  24617. VirtualJoystick.vjCanvasContext.beginPath();
  24618. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24619. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24620. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24621. VirtualJoystick.vjCanvasContext.stroke();
  24622. VirtualJoystick.vjCanvasContext.beginPath();
  24623. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24624. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24625. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24626. VirtualJoystick.vjCanvasContext.stroke();
  24627. VirtualJoystick.vjCanvasContext.beginPath();
  24628. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24629. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24630. VirtualJoystick.vjCanvasContext.stroke();
  24631. }
  24632. else {
  24633. VirtualJoystick.vjCanvasContext.beginPath();
  24634. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24635. VirtualJoystick.vjCanvasContext.beginPath();
  24636. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24637. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24638. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24639. VirtualJoystick.vjCanvasContext.stroke();
  24640. }
  24641. ;
  24642. });
  24643. }
  24644. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24645. };
  24646. VirtualJoystick.prototype.releaseCanvas = function () {
  24647. if (VirtualJoystick.vjCanvas) {
  24648. document.body.removeChild(VirtualJoystick.vjCanvas);
  24649. VirtualJoystick.vjCanvas = null;
  24650. }
  24651. };
  24652. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24653. VirtualJoystick._globalJoystickIndex = 0;
  24654. return VirtualJoystick;
  24655. })();
  24656. BABYLON.VirtualJoystick = VirtualJoystick;
  24657. })(BABYLON || (BABYLON = {}));
  24658. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24659. var __extends = (this && this.__extends) || function (d, b) {
  24660. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24661. function __() { this.constructor = d; }
  24662. __.prototype = b.prototype;
  24663. d.prototype = new __();
  24664. };
  24665. var BABYLON;
  24666. (function (BABYLON) {
  24667. // We're mainly based on the logic defined into the FreeCamera code
  24668. var VirtualJoysticksCamera = (function (_super) {
  24669. __extends(VirtualJoysticksCamera, _super);
  24670. function VirtualJoysticksCamera(name, position, scene) {
  24671. _super.call(this, name, position, scene);
  24672. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24673. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  24674. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  24675. this._leftjoystick.setJoystickSensibility(0.15);
  24676. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24677. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  24678. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  24679. this._rightjoystick.reverseUpDown = true;
  24680. this._rightjoystick.setJoystickSensibility(0.05);
  24681. this._rightjoystick.setJoystickColor("yellow");
  24682. }
  24683. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24684. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24685. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24686. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24687. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24688. if (!this._leftjoystick.pressed) {
  24689. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24690. }
  24691. if (!this._rightjoystick.pressed) {
  24692. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24693. }
  24694. _super.prototype._checkInputs.call(this);
  24695. };
  24696. VirtualJoysticksCamera.prototype.dispose = function () {
  24697. this._leftjoystick.releaseCanvas();
  24698. _super.prototype.dispose.call(this);
  24699. };
  24700. return VirtualJoysticksCamera;
  24701. })(BABYLON.FreeCamera);
  24702. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24703. })(BABYLON || (BABYLON = {}));
  24704. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24705. var __extends = (this && this.__extends) || function (d, b) {
  24706. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24707. function __() { this.constructor = d; }
  24708. __.prototype = b.prototype;
  24709. d.prototype = new __();
  24710. };
  24711. var BABYLON;
  24712. (function (BABYLON) {
  24713. var ShaderMaterial = (function (_super) {
  24714. __extends(ShaderMaterial, _super);
  24715. function ShaderMaterial(name, scene, shaderPath, options) {
  24716. _super.call(this, name, scene);
  24717. this._textures = new Array();
  24718. this._floats = new Array();
  24719. this._floatsArrays = {};
  24720. this._colors3 = new Array();
  24721. this._colors4 = new Array();
  24722. this._vectors2 = new Array();
  24723. this._vectors3 = new Array();
  24724. this._matrices = new Array();
  24725. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24726. this._shaderPath = shaderPath;
  24727. options.needAlphaBlending = options.needAlphaBlending || false;
  24728. options.needAlphaTesting = options.needAlphaTesting || false;
  24729. options.attributes = options.attributes || ["position", "normal", "uv"];
  24730. options.uniforms = options.uniforms || ["worldViewProjection"];
  24731. options.samplers = options.samplers || [];
  24732. this._options = options;
  24733. }
  24734. ShaderMaterial.prototype.needAlphaBlending = function () {
  24735. return this._options.needAlphaBlending;
  24736. };
  24737. ShaderMaterial.prototype.needAlphaTesting = function () {
  24738. return this._options.needAlphaTesting;
  24739. };
  24740. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24741. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24742. this._options.uniforms.push(uniformName);
  24743. }
  24744. };
  24745. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24746. if (this._options.samplers.indexOf(name) === -1) {
  24747. this._options.samplers.push(name);
  24748. }
  24749. this._textures[name] = texture;
  24750. return this;
  24751. };
  24752. ShaderMaterial.prototype.setFloat = function (name, value) {
  24753. this._checkUniform(name);
  24754. this._floats[name] = value;
  24755. return this;
  24756. };
  24757. ShaderMaterial.prototype.setFloats = function (name, value) {
  24758. this._checkUniform(name);
  24759. this._floatsArrays[name] = value;
  24760. return this;
  24761. };
  24762. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24763. this._checkUniform(name);
  24764. this._colors3[name] = value;
  24765. return this;
  24766. };
  24767. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24768. this._checkUniform(name);
  24769. this._colors4[name] = value;
  24770. return this;
  24771. };
  24772. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24773. this._checkUniform(name);
  24774. this._vectors2[name] = value;
  24775. return this;
  24776. };
  24777. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24778. this._checkUniform(name);
  24779. this._vectors3[name] = value;
  24780. return this;
  24781. };
  24782. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24783. this._checkUniform(name);
  24784. this._matrices[name] = value;
  24785. return this;
  24786. };
  24787. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24788. var scene = this.getScene();
  24789. var engine = scene.getEngine();
  24790. if (!this.checkReadyOnEveryCall) {
  24791. if (this._renderId === scene.getRenderId()) {
  24792. return true;
  24793. }
  24794. }
  24795. // Instances
  24796. var defines = [];
  24797. var fallbacks = new BABYLON.EffectFallbacks();
  24798. if (useInstances) {
  24799. defines.push("#define INSTANCES");
  24800. }
  24801. // Bones
  24802. if (mesh && mesh.useBones) {
  24803. defines.push("#define BONES");
  24804. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24805. defines.push("#define BONES4");
  24806. fallbacks.addFallback(0, "BONES4");
  24807. }
  24808. // Alpha test
  24809. if (engine.getAlphaTesting()) {
  24810. defines.push("#define ALPHATEST");
  24811. }
  24812. var previousEffect = this._effect;
  24813. var join = defines.join("\n");
  24814. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24815. if (!this._effect.isReady()) {
  24816. return false;
  24817. }
  24818. if (previousEffect !== this._effect) {
  24819. scene.resetCachedMaterial();
  24820. }
  24821. this._renderId = scene.getRenderId();
  24822. return true;
  24823. };
  24824. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24825. var scene = this.getScene();
  24826. if (this._options.uniforms.indexOf("world") !== -1) {
  24827. this._effect.setMatrix("world", world);
  24828. }
  24829. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24830. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24831. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24832. }
  24833. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24834. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24835. }
  24836. };
  24837. ShaderMaterial.prototype.bind = function (world, mesh) {
  24838. // Std values
  24839. this.bindOnlyWorldMatrix(world);
  24840. if (this.getScene().getCachedMaterial() !== this) {
  24841. if (this._options.uniforms.indexOf("view") !== -1) {
  24842. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24843. }
  24844. if (this._options.uniforms.indexOf("projection") !== -1) {
  24845. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24846. }
  24847. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24848. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24849. }
  24850. // Bones
  24851. if (mesh && mesh.useBones) {
  24852. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24853. }
  24854. // Texture
  24855. for (var name in this._textures) {
  24856. this._effect.setTexture(name, this._textures[name]);
  24857. }
  24858. // Float
  24859. for (name in this._floats) {
  24860. this._effect.setFloat(name, this._floats[name]);
  24861. }
  24862. // Float s
  24863. for (name in this._floatsArrays) {
  24864. this._effect.setArray(name, this._floatsArrays[name]);
  24865. }
  24866. // Color3
  24867. for (name in this._colors3) {
  24868. this._effect.setColor3(name, this._colors3[name]);
  24869. }
  24870. // Color4
  24871. for (name in this._colors4) {
  24872. var color = this._colors4[name];
  24873. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24874. }
  24875. // Vector2
  24876. for (name in this._vectors2) {
  24877. this._effect.setVector2(name, this._vectors2[name]);
  24878. }
  24879. // Vector3
  24880. for (name in this._vectors3) {
  24881. this._effect.setVector3(name, this._vectors3[name]);
  24882. }
  24883. // Matrix
  24884. for (name in this._matrices) {
  24885. this._effect.setMatrix(name, this._matrices[name]);
  24886. }
  24887. }
  24888. _super.prototype.bind.call(this, world, mesh);
  24889. };
  24890. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24891. for (var name in this._textures) {
  24892. this._textures[name].dispose();
  24893. }
  24894. this._textures = [];
  24895. _super.prototype.dispose.call(this, forceDisposeEffect);
  24896. };
  24897. return ShaderMaterial;
  24898. })(BABYLON.Material);
  24899. BABYLON.ShaderMaterial = ShaderMaterial;
  24900. })(BABYLON || (BABYLON = {}));
  24901. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24902. var BABYLON;
  24903. (function (BABYLON) {
  24904. var VertexData = (function () {
  24905. function VertexData() {
  24906. }
  24907. VertexData.prototype.set = function (data, kind) {
  24908. switch (kind) {
  24909. case BABYLON.VertexBuffer.PositionKind:
  24910. this.positions = data;
  24911. break;
  24912. case BABYLON.VertexBuffer.NormalKind:
  24913. this.normals = data;
  24914. break;
  24915. case BABYLON.VertexBuffer.UVKind:
  24916. this.uvs = data;
  24917. break;
  24918. case BABYLON.VertexBuffer.UV2Kind:
  24919. this.uv2s = data;
  24920. break;
  24921. case BABYLON.VertexBuffer.ColorKind:
  24922. this.colors = data;
  24923. break;
  24924. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24925. this.matricesIndices = data;
  24926. break;
  24927. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24928. this.matricesWeights = data;
  24929. break;
  24930. }
  24931. };
  24932. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24933. this._applyTo(mesh, updatable);
  24934. };
  24935. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24936. this._applyTo(geometry, updatable);
  24937. };
  24938. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24939. this._update(mesh);
  24940. };
  24941. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24942. this._update(geometry);
  24943. };
  24944. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24945. if (this.positions) {
  24946. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24947. }
  24948. if (this.normals) {
  24949. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24950. }
  24951. if (this.uvs) {
  24952. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24953. }
  24954. if (this.uv2s) {
  24955. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24956. }
  24957. if (this.colors) {
  24958. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24959. }
  24960. if (this.matricesIndices) {
  24961. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24962. }
  24963. if (this.matricesWeights) {
  24964. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24965. }
  24966. if (this.indices) {
  24967. meshOrGeometry.setIndices(this.indices);
  24968. }
  24969. };
  24970. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24971. if (this.positions) {
  24972. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24973. }
  24974. if (this.normals) {
  24975. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24976. }
  24977. if (this.uvs) {
  24978. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24979. }
  24980. if (this.uv2s) {
  24981. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24982. }
  24983. if (this.colors) {
  24984. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24985. }
  24986. if (this.matricesIndices) {
  24987. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24988. }
  24989. if (this.matricesWeights) {
  24990. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24991. }
  24992. if (this.indices) {
  24993. meshOrGeometry.setIndices(this.indices);
  24994. }
  24995. };
  24996. VertexData.prototype.transform = function (matrix) {
  24997. var transformed = BABYLON.Vector3.Zero();
  24998. if (this.positions) {
  24999. var position = BABYLON.Vector3.Zero();
  25000. for (var index = 0; index < this.positions.length; index += 3) {
  25001. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25002. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25003. this.positions[index] = transformed.x;
  25004. this.positions[index + 1] = transformed.y;
  25005. this.positions[index + 2] = transformed.z;
  25006. }
  25007. }
  25008. if (this.normals) {
  25009. var normal = BABYLON.Vector3.Zero();
  25010. for (index = 0; index < this.normals.length; index += 3) {
  25011. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25012. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25013. this.normals[index] = transformed.x;
  25014. this.normals[index + 1] = transformed.y;
  25015. this.normals[index + 2] = transformed.z;
  25016. }
  25017. }
  25018. };
  25019. VertexData.prototype.merge = function (other) {
  25020. if (other.indices) {
  25021. if (!this.indices) {
  25022. this.indices = [];
  25023. }
  25024. var offset = this.positions ? this.positions.length / 3 : 0;
  25025. for (var index = 0; index < other.indices.length; index++) {
  25026. this.indices.push(other.indices[index] + offset);
  25027. }
  25028. }
  25029. if (other.positions) {
  25030. if (!this.positions) {
  25031. this.positions = [];
  25032. }
  25033. for (index = 0; index < other.positions.length; index++) {
  25034. this.positions.push(other.positions[index]);
  25035. }
  25036. }
  25037. if (other.normals) {
  25038. if (!this.normals) {
  25039. this.normals = [];
  25040. }
  25041. for (index = 0; index < other.normals.length; index++) {
  25042. this.normals.push(other.normals[index]);
  25043. }
  25044. }
  25045. if (other.uvs) {
  25046. if (!this.uvs) {
  25047. this.uvs = [];
  25048. }
  25049. for (index = 0; index < other.uvs.length; index++) {
  25050. this.uvs.push(other.uvs[index]);
  25051. }
  25052. }
  25053. if (other.uv2s) {
  25054. if (!this.uv2s) {
  25055. this.uv2s = [];
  25056. }
  25057. for (index = 0; index < other.uv2s.length; index++) {
  25058. this.uv2s.push(other.uv2s[index]);
  25059. }
  25060. }
  25061. if (other.matricesIndices) {
  25062. if (!this.matricesIndices) {
  25063. this.matricesIndices = [];
  25064. }
  25065. for (index = 0; index < other.matricesIndices.length; index++) {
  25066. this.matricesIndices.push(other.matricesIndices[index]);
  25067. }
  25068. }
  25069. if (other.matricesWeights) {
  25070. if (!this.matricesWeights) {
  25071. this.matricesWeights = [];
  25072. }
  25073. for (index = 0; index < other.matricesWeights.length; index++) {
  25074. this.matricesWeights.push(other.matricesWeights[index]);
  25075. }
  25076. }
  25077. if (other.colors) {
  25078. if (!this.colors) {
  25079. this.colors = [];
  25080. }
  25081. for (index = 0; index < other.colors.length; index++) {
  25082. this.colors.push(other.colors[index]);
  25083. }
  25084. }
  25085. };
  25086. // Statics
  25087. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  25088. return VertexData._ExtractFrom(mesh, copyWhenShared);
  25089. };
  25090. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  25091. return VertexData._ExtractFrom(geometry, copyWhenShared);
  25092. };
  25093. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  25094. var result = new VertexData();
  25095. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25096. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  25097. }
  25098. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25099. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  25100. }
  25101. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25102. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  25103. }
  25104. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25105. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  25106. }
  25107. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25108. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  25109. }
  25110. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25111. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  25112. }
  25113. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25114. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  25115. }
  25116. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25117. return result;
  25118. };
  25119. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  25120. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25121. closeArray = closeArray || false;
  25122. closePath = closePath || false;
  25123. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25124. offset = offset || defaultOffset;
  25125. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25126. var positions = [];
  25127. var indices = [];
  25128. var normals = [];
  25129. var uvs = [];
  25130. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25131. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25132. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25133. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25134. var minlg; // minimal length among all paths from pathArray
  25135. var lg = []; // array of path lengths : nb of vertex per path
  25136. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  25137. var p; // path iterator
  25138. var i; // point iterator
  25139. var j; // point iterator
  25140. // if single path in pathArray
  25141. if (pathArray.length < 2) {
  25142. var ar1 = [];
  25143. var ar2 = [];
  25144. for (i = 0; i < pathArray[0].length - offset; i++) {
  25145. ar1.push(pathArray[0][i]);
  25146. ar2.push(pathArray[0][i + offset]);
  25147. }
  25148. pathArray = [ar1, ar2];
  25149. }
  25150. // positions and horizontal distances (u)
  25151. var idc = 0;
  25152. minlg = pathArray[0].length;
  25153. for (p = 0; p < pathArray.length; p++) {
  25154. uTotalDistance[p] = 0;
  25155. us[p] = [0];
  25156. var path = pathArray[p];
  25157. var l = path.length;
  25158. minlg = (minlg < l) ? minlg : l;
  25159. lg[p] = l;
  25160. idx[p] = idc;
  25161. j = 0;
  25162. while (j < l) {
  25163. positions.push(path[j].x, path[j].y, path[j].z);
  25164. if (j > 0) {
  25165. var vectlg = path[j].subtract(path[j - 1]).length();
  25166. var dist = vectlg + uTotalDistance[p];
  25167. us[p].push(dist);
  25168. uTotalDistance[p] = dist;
  25169. }
  25170. j++;
  25171. }
  25172. if (closePath) {
  25173. vectlg = path[0].subtract(path[j - 1]).length();
  25174. dist = vectlg + uTotalDistance[p];
  25175. uTotalDistance[p] = dist;
  25176. }
  25177. idc += l;
  25178. }
  25179. // vertical distances (v)
  25180. for (i = 0; i < minlg; i++) {
  25181. vTotalDistance[i] = 0;
  25182. vs[i] = [0];
  25183. var path1;
  25184. var path2;
  25185. for (p = 0; p < pathArray.length - 1; p++) {
  25186. path1 = pathArray[p];
  25187. path2 = pathArray[p + 1];
  25188. vectlg = path2[i].subtract(path1[i]).length();
  25189. dist = vectlg + vTotalDistance[i];
  25190. vs[i].push(dist);
  25191. vTotalDistance[i] = dist;
  25192. }
  25193. if (closeArray) {
  25194. path1 = pathArray[p];
  25195. path2 = pathArray[0];
  25196. vectlg = path2[i].subtract(path1[i]).length();
  25197. dist = vectlg + vTotalDistance[i];
  25198. vTotalDistance[i] = dist;
  25199. }
  25200. }
  25201. // uvs
  25202. var u;
  25203. var v;
  25204. for (p = 0; p < pathArray.length; p++) {
  25205. for (i = 0; i < minlg; i++) {
  25206. u = us[p][i] / uTotalDistance[p];
  25207. v = vs[i][p] / vTotalDistance[i];
  25208. uvs.push(u, v);
  25209. }
  25210. }
  25211. // indices
  25212. p = 0; // path index
  25213. var pi = 0; // positions array index
  25214. var l1 = lg[p] - 1; // path1 length
  25215. var l2 = lg[p + 1] - 1; // path2 length
  25216. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25217. var shft = idx[1] - idx[0]; // shift
  25218. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  25219. var t1; // two consecutive triangles, so 4 points : point1
  25220. var t2; // point2
  25221. var t3; // point3
  25222. var t4; // point4
  25223. while (pi <= min && p < path1nb) {
  25224. // 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
  25225. t1 = pi;
  25226. t2 = pi + shft;
  25227. t3 = pi + 1;
  25228. t4 = pi + shft + 1;
  25229. indices.push(pi, pi + shft, pi + 1);
  25230. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25231. pi += 1;
  25232. if (pi === min) {
  25233. if (closePath) {
  25234. indices.push(pi, pi + shft, idx[p]);
  25235. indices.push(idx[p] + shft, idx[p], pi + shft);
  25236. t3 = idx[p];
  25237. t4 = idx[p] + shft;
  25238. }
  25239. p++;
  25240. if (p === lg.length - 1) {
  25241. shft = idx[0] - idx[p];
  25242. l1 = lg[p] - 1;
  25243. l2 = lg[0] - 1;
  25244. }
  25245. else {
  25246. shft = idx[p + 1] - idx[p];
  25247. l1 = lg[p] - 1;
  25248. l2 = lg[p + 1] - 1;
  25249. }
  25250. pi = idx[p];
  25251. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25252. }
  25253. }
  25254. // normals
  25255. VertexData.ComputeNormals(positions, indices, normals);
  25256. // sides
  25257. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25258. // Result
  25259. var vertexData = new VertexData();
  25260. vertexData.indices = indices;
  25261. vertexData.positions = positions;
  25262. vertexData.normals = normals;
  25263. vertexData.uvs = uvs;
  25264. return vertexData;
  25265. };
  25266. VertexData.CreateBox = function (size, sideOrientation) {
  25267. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25268. var normalsSource = [
  25269. new BABYLON.Vector3(0, 0, 1),
  25270. new BABYLON.Vector3(0, 0, -1),
  25271. new BABYLON.Vector3(1, 0, 0),
  25272. new BABYLON.Vector3(-1, 0, 0),
  25273. new BABYLON.Vector3(0, 1, 0),
  25274. new BABYLON.Vector3(0, -1, 0)
  25275. ];
  25276. var indices = [];
  25277. var positions = [];
  25278. var normals = [];
  25279. var uvs = [];
  25280. size = size || 1;
  25281. // Create each face in turn.
  25282. for (var index = 0; index < normalsSource.length; index++) {
  25283. var normal = normalsSource[index];
  25284. // Get two vectors perpendicular to the face normal and to each other.
  25285. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25286. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25287. // Six indices (two triangles) per face.
  25288. var verticesLength = positions.length / 3;
  25289. indices.push(verticesLength);
  25290. indices.push(verticesLength + 1);
  25291. indices.push(verticesLength + 2);
  25292. indices.push(verticesLength);
  25293. indices.push(verticesLength + 2);
  25294. indices.push(verticesLength + 3);
  25295. // Four vertices per face.
  25296. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25297. positions.push(vertex.x, vertex.y, vertex.z);
  25298. normals.push(normal.x, normal.y, normal.z);
  25299. uvs.push(1.0, 1.0);
  25300. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25301. positions.push(vertex.x, vertex.y, vertex.z);
  25302. normals.push(normal.x, normal.y, normal.z);
  25303. uvs.push(0.0, 1.0);
  25304. vertex = normal.add(side1).add(side2).scale(size / 2);
  25305. positions.push(vertex.x, vertex.y, vertex.z);
  25306. normals.push(normal.x, normal.y, normal.z);
  25307. uvs.push(0.0, 0.0);
  25308. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25309. positions.push(vertex.x, vertex.y, vertex.z);
  25310. normals.push(normal.x, normal.y, normal.z);
  25311. uvs.push(1.0, 0.0);
  25312. }
  25313. // sides
  25314. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25315. // Result
  25316. var vertexData = new VertexData();
  25317. vertexData.indices = indices;
  25318. vertexData.positions = positions;
  25319. vertexData.normals = normals;
  25320. vertexData.uvs = uvs;
  25321. return vertexData;
  25322. };
  25323. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25324. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25325. segments = segments || 32;
  25326. diameter = diameter || 1;
  25327. var radius = diameter / 2;
  25328. var totalZRotationSteps = 2 + segments;
  25329. var totalYRotationSteps = 2 * totalZRotationSteps;
  25330. var indices = [];
  25331. var positions = [];
  25332. var normals = [];
  25333. var uvs = [];
  25334. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25335. var normalizedZ = zRotationStep / totalZRotationSteps;
  25336. var angleZ = (normalizedZ * Math.PI);
  25337. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25338. var normalizedY = yRotationStep / totalYRotationSteps;
  25339. var angleY = normalizedY * Math.PI * 2;
  25340. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25341. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25342. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25343. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25344. var vertex = complete.scale(radius);
  25345. var normal = BABYLON.Vector3.Normalize(vertex);
  25346. positions.push(vertex.x, vertex.y, vertex.z);
  25347. normals.push(normal.x, normal.y, normal.z);
  25348. uvs.push(normalizedZ, normalizedY);
  25349. }
  25350. if (zRotationStep > 0) {
  25351. var verticesCount = positions.length / 3;
  25352. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25353. indices.push((firstIndex));
  25354. indices.push((firstIndex + 1));
  25355. indices.push(firstIndex + totalYRotationSteps + 1);
  25356. indices.push((firstIndex + totalYRotationSteps + 1));
  25357. indices.push((firstIndex + 1));
  25358. indices.push((firstIndex + totalYRotationSteps + 2));
  25359. }
  25360. }
  25361. }
  25362. // Sides
  25363. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25364. // Result
  25365. var vertexData = new VertexData();
  25366. vertexData.indices = indices;
  25367. vertexData.positions = positions;
  25368. vertexData.normals = normals;
  25369. vertexData.uvs = uvs;
  25370. return vertexData;
  25371. };
  25372. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25373. if (subdivisions === void 0) { subdivisions = 1; }
  25374. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25375. var radiusTop = diameterTop / 2;
  25376. var radiusBottom = diameterBottom / 2;
  25377. var indices = [];
  25378. var positions = [];
  25379. var normals = [];
  25380. var uvs = [];
  25381. height = height || 1;
  25382. diameterTop = diameterTop || 0.5;
  25383. diameterBottom = diameterBottom || 1;
  25384. tessellation = tessellation || 16;
  25385. subdivisions = subdivisions || 1;
  25386. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25387. var getCircleVector = function (i) {
  25388. var angle = (i * 2.0 * Math.PI / tessellation);
  25389. var dx = Math.cos(angle);
  25390. var dz = Math.sin(angle);
  25391. return new BABYLON.Vector3(dx, 0, dz);
  25392. };
  25393. var createCylinderCap = function (isTop) {
  25394. var radius = isTop ? radiusTop : radiusBottom;
  25395. if (radius === 0) {
  25396. return;
  25397. }
  25398. var vbase = positions.length / 3;
  25399. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25400. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25401. if (!isTop) {
  25402. offset.scaleInPlace(-1);
  25403. textureScale.x = -textureScale.x;
  25404. }
  25405. // Positions, normals & uvs
  25406. for (var i = 0; i < tessellation; i++) {
  25407. var circleVector = getCircleVector(i);
  25408. var position = circleVector.scale(radius).add(offset);
  25409. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25410. positions.push(position.x, position.y, position.z);
  25411. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25412. }
  25413. // Indices
  25414. for (i = 0; i < tessellation - 2; i++) {
  25415. if (!isTop) {
  25416. indices.push(vbase);
  25417. indices.push(vbase + (i + 2) % tessellation);
  25418. indices.push(vbase + (i + 1) % tessellation);
  25419. }
  25420. else {
  25421. indices.push(vbase);
  25422. indices.push(vbase + (i + 1) % tessellation);
  25423. indices.push(vbase + (i + 2) % tessellation);
  25424. }
  25425. }
  25426. };
  25427. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25428. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25429. var stride = tessellation + 1;
  25430. // Positions, normals & uvs
  25431. for (var i = 0; i <= tessellation; i++) {
  25432. var circleVector = getCircleVector(i);
  25433. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25434. var position, radius = radiusBottom;
  25435. for (var s = 0; s <= subdivisions; s++) {
  25436. // Update variables
  25437. position = circleVector.scale(radius);
  25438. position.addInPlace(base.add(offset.scale(s)));
  25439. textureCoordinate.y += 1 / subdivisions;
  25440. radius += (radiusTop - radiusBottom) / subdivisions;
  25441. // Push in arrays
  25442. positions.push(position.x, position.y, position.z);
  25443. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25444. }
  25445. }
  25446. subdivisions += 1;
  25447. // Indices
  25448. for (s = 0; s < subdivisions - 1; s++) {
  25449. for (i = 0; i <= tessellation; i++) {
  25450. indices.push(i * subdivisions + s);
  25451. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25452. indices.push(i * subdivisions + (s + 1));
  25453. indices.push(i * subdivisions + (s + 1));
  25454. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25455. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25456. }
  25457. }
  25458. // Create flat triangle fan caps to seal the top and bottom.
  25459. createCylinderCap(true);
  25460. createCylinderCap(false);
  25461. // Normals
  25462. VertexData.ComputeNormals(positions, indices, normals);
  25463. // Sides
  25464. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25465. // Result
  25466. var vertexData = new VertexData();
  25467. vertexData.indices = indices;
  25468. vertexData.positions = positions;
  25469. vertexData.normals = normals;
  25470. vertexData.uvs = uvs;
  25471. return vertexData;
  25472. };
  25473. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25474. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25475. var indices = [];
  25476. var positions = [];
  25477. var normals = [];
  25478. var uvs = [];
  25479. diameter = diameter || 1;
  25480. thickness = thickness || 0.5;
  25481. tessellation = tessellation || 16;
  25482. var stride = tessellation + 1;
  25483. for (var i = 0; i <= tessellation; i++) {
  25484. var u = i / tessellation;
  25485. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25486. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25487. for (var j = 0; j <= tessellation; j++) {
  25488. var v = 1 - j / tessellation;
  25489. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25490. var dx = Math.cos(innerAngle);
  25491. var dy = Math.sin(innerAngle);
  25492. // Create a vertex.
  25493. var normal = new BABYLON.Vector3(dx, dy, 0);
  25494. var position = normal.scale(thickness / 2);
  25495. var textureCoordinate = new BABYLON.Vector2(u, v);
  25496. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25497. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25498. positions.push(position.x, position.y, position.z);
  25499. normals.push(normal.x, normal.y, normal.z);
  25500. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25501. // And create indices for two triangles.
  25502. var nextI = (i + 1) % stride;
  25503. var nextJ = (j + 1) % stride;
  25504. indices.push(i * stride + j);
  25505. indices.push(i * stride + nextJ);
  25506. indices.push(nextI * stride + j);
  25507. indices.push(i * stride + nextJ);
  25508. indices.push(nextI * stride + nextJ);
  25509. indices.push(nextI * stride + j);
  25510. }
  25511. }
  25512. // Sides
  25513. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25514. // Result
  25515. var vertexData = new VertexData();
  25516. vertexData.indices = indices;
  25517. vertexData.positions = positions;
  25518. vertexData.normals = normals;
  25519. vertexData.uvs = uvs;
  25520. return vertexData;
  25521. };
  25522. VertexData.CreateLines = function (points) {
  25523. var indices = [];
  25524. var positions = [];
  25525. for (var index = 0; index < points.length; index++) {
  25526. positions.push(points[index].x, points[index].y, points[index].z);
  25527. if (index > 0) {
  25528. indices.push(index - 1);
  25529. indices.push(index);
  25530. }
  25531. }
  25532. // Result
  25533. var vertexData = new VertexData();
  25534. vertexData.indices = indices;
  25535. vertexData.positions = positions;
  25536. return vertexData;
  25537. };
  25538. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25539. dashSize = dashSize || 3;
  25540. gapSize = gapSize || 1;
  25541. dashNb = dashNb || 200;
  25542. var positions = new Array();
  25543. var indices = new Array();
  25544. var curvect = BABYLON.Vector3.Zero();
  25545. var lg = 0;
  25546. var nb = 0;
  25547. var shft = 0;
  25548. var dashshft = 0;
  25549. var curshft = 0;
  25550. var idx = 0;
  25551. var i = 0;
  25552. for (i = 0; i < points.length - 1; i++) {
  25553. points[i + 1].subtractToRef(points[i], curvect);
  25554. lg += curvect.length();
  25555. }
  25556. shft = lg / dashNb;
  25557. dashshft = dashSize * shft / (dashSize + gapSize);
  25558. for (i = 0; i < points.length - 1; i++) {
  25559. points[i + 1].subtractToRef(points[i], curvect);
  25560. nb = Math.floor(curvect.length() / shft);
  25561. curvect.normalize();
  25562. for (var j = 0; j < nb; j++) {
  25563. curshft = shft * j;
  25564. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25565. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25566. indices.push(idx, idx + 1);
  25567. idx += 2;
  25568. }
  25569. }
  25570. // Result
  25571. var vertexData = new VertexData();
  25572. vertexData.positions = positions;
  25573. vertexData.indices = indices;
  25574. return vertexData;
  25575. };
  25576. VertexData.CreateGround = function (width, height, subdivisions) {
  25577. var indices = [];
  25578. var positions = [];
  25579. var normals = [];
  25580. var uvs = [];
  25581. var row, col;
  25582. width = width || 1;
  25583. height = height || 1;
  25584. subdivisions = subdivisions || 1;
  25585. for (row = 0; row <= subdivisions; row++) {
  25586. for (col = 0; col <= subdivisions; col++) {
  25587. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25588. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25589. positions.push(position.x, position.y, position.z);
  25590. normals.push(normal.x, normal.y, normal.z);
  25591. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25592. }
  25593. }
  25594. for (row = 0; row < subdivisions; row++) {
  25595. for (col = 0; col < subdivisions; col++) {
  25596. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25597. indices.push(col + 1 + row * (subdivisions + 1));
  25598. indices.push(col + row * (subdivisions + 1));
  25599. indices.push(col + (row + 1) * (subdivisions + 1));
  25600. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25601. indices.push(col + row * (subdivisions + 1));
  25602. }
  25603. }
  25604. // Result
  25605. var vertexData = new VertexData();
  25606. vertexData.indices = indices;
  25607. vertexData.positions = positions;
  25608. vertexData.normals = normals;
  25609. vertexData.uvs = uvs;
  25610. return vertexData;
  25611. };
  25612. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25613. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25614. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25615. var indices = [];
  25616. var positions = [];
  25617. var normals = [];
  25618. var uvs = [];
  25619. var row, col, tileRow, tileCol;
  25620. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25621. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25622. precision.w = (precision.w < 1) ? 1 : precision.w;
  25623. precision.h = (precision.h < 1) ? 1 : precision.h;
  25624. var tileSize = {
  25625. 'w': (xmax - xmin) / subdivisions.w,
  25626. 'h': (zmax - zmin) / subdivisions.h
  25627. };
  25628. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25629. // Indices
  25630. var base = positions.length / 3;
  25631. var rowLength = precision.w + 1;
  25632. for (row = 0; row < precision.h; row++) {
  25633. for (col = 0; col < precision.w; col++) {
  25634. var square = [
  25635. base + col + row * rowLength,
  25636. base + (col + 1) + row * rowLength,
  25637. base + (col + 1) + (row + 1) * rowLength,
  25638. base + col + (row + 1) * rowLength
  25639. ];
  25640. indices.push(square[1]);
  25641. indices.push(square[2]);
  25642. indices.push(square[3]);
  25643. indices.push(square[0]);
  25644. indices.push(square[1]);
  25645. indices.push(square[3]);
  25646. }
  25647. }
  25648. // Position, normals and uvs
  25649. var position = BABYLON.Vector3.Zero();
  25650. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25651. for (row = 0; row <= precision.h; row++) {
  25652. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25653. for (col = 0; col <= precision.w; col++) {
  25654. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25655. position.y = 0;
  25656. positions.push(position.x, position.y, position.z);
  25657. normals.push(normal.x, normal.y, normal.z);
  25658. uvs.push(col / precision.w, row / precision.h);
  25659. }
  25660. }
  25661. }
  25662. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25663. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25664. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25665. }
  25666. }
  25667. // Result
  25668. var vertexData = new VertexData();
  25669. vertexData.indices = indices;
  25670. vertexData.positions = positions;
  25671. vertexData.normals = normals;
  25672. vertexData.uvs = uvs;
  25673. return vertexData;
  25674. };
  25675. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25676. var indices = [];
  25677. var positions = [];
  25678. var normals = [];
  25679. var uvs = [];
  25680. var row, col;
  25681. // Vertices
  25682. for (row = 0; row <= subdivisions; row++) {
  25683. for (col = 0; col <= subdivisions; col++) {
  25684. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25685. // Compute height
  25686. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25687. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25688. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25689. var r = buffer[pos] / 255.0;
  25690. var g = buffer[pos + 1] / 255.0;
  25691. var b = buffer[pos + 2] / 255.0;
  25692. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25693. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25694. // Add vertex
  25695. positions.push(position.x, position.y, position.z);
  25696. normals.push(0, 0, 0);
  25697. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25698. }
  25699. }
  25700. // Indices
  25701. for (row = 0; row < subdivisions; row++) {
  25702. for (col = 0; col < subdivisions; col++) {
  25703. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25704. indices.push(col + 1 + row * (subdivisions + 1));
  25705. indices.push(col + row * (subdivisions + 1));
  25706. indices.push(col + (row + 1) * (subdivisions + 1));
  25707. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25708. indices.push(col + row * (subdivisions + 1));
  25709. }
  25710. }
  25711. // Normals
  25712. VertexData.ComputeNormals(positions, indices, normals);
  25713. // Result
  25714. var vertexData = new VertexData();
  25715. vertexData.indices = indices;
  25716. vertexData.positions = positions;
  25717. vertexData.normals = normals;
  25718. vertexData.uvs = uvs;
  25719. return vertexData;
  25720. };
  25721. VertexData.CreatePlane = function (size, sideOrientation) {
  25722. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25723. var indices = [];
  25724. var positions = [];
  25725. var normals = [];
  25726. var uvs = [];
  25727. size = size || 1;
  25728. // Vertices
  25729. var halfSize = size / 2.0;
  25730. positions.push(-halfSize, -halfSize, 0);
  25731. normals.push(0, 0, -1.0);
  25732. uvs.push(0.0, 0.0);
  25733. positions.push(halfSize, -halfSize, 0);
  25734. normals.push(0, 0, -1.0);
  25735. uvs.push(1.0, 0.0);
  25736. positions.push(halfSize, halfSize, 0);
  25737. normals.push(0, 0, -1.0);
  25738. uvs.push(1.0, 1.0);
  25739. positions.push(-halfSize, halfSize, 0);
  25740. normals.push(0, 0, -1.0);
  25741. uvs.push(0.0, 1.0);
  25742. // Indices
  25743. indices.push(0);
  25744. indices.push(1);
  25745. indices.push(2);
  25746. indices.push(0);
  25747. indices.push(2);
  25748. indices.push(3);
  25749. // Sides
  25750. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25751. // Result
  25752. var vertexData = new VertexData();
  25753. vertexData.indices = indices;
  25754. vertexData.positions = positions;
  25755. vertexData.normals = normals;
  25756. vertexData.uvs = uvs;
  25757. return vertexData;
  25758. };
  25759. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25760. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25761. var positions = [];
  25762. var indices = [];
  25763. var normals = [];
  25764. var uvs = [];
  25765. // positions and uvs
  25766. positions.push(0, 0, 0); // disc center first
  25767. uvs.push(0.5, 0.5);
  25768. var step = Math.PI * 2 / tessellation;
  25769. for (var a = 0; a < Math.PI * 2; a += step) {
  25770. var x = Math.cos(a);
  25771. var y = Math.sin(a);
  25772. var u = (x + 1) / 2;
  25773. var v = (1 - y) / 2;
  25774. positions.push(radius * x, radius * y, 0);
  25775. uvs.push(u, v);
  25776. }
  25777. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25778. uvs.push(uvs[2], uvs[3]);
  25779. //indices
  25780. var vertexNb = positions.length / 3;
  25781. for (var i = 1; i < vertexNb - 1; i++) {
  25782. indices.push(i + 1, 0, i);
  25783. }
  25784. // result
  25785. VertexData.ComputeNormals(positions, indices, normals);
  25786. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25787. var vertexData = new VertexData();
  25788. vertexData.indices = indices;
  25789. vertexData.positions = positions;
  25790. vertexData.normals = normals;
  25791. vertexData.uvs = uvs;
  25792. return vertexData;
  25793. };
  25794. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25795. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25796. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25797. var indices = [];
  25798. var positions = [];
  25799. var normals = [];
  25800. var uvs = [];
  25801. radius = radius || 2;
  25802. tube = tube || 0.5;
  25803. radialSegments = radialSegments || 32;
  25804. tubularSegments = tubularSegments || 32;
  25805. p = p || 2;
  25806. q = q || 3;
  25807. // Helper
  25808. var getPos = function (angle) {
  25809. var cu = Math.cos(angle);
  25810. var su = Math.sin(angle);
  25811. var quOverP = q / p * angle;
  25812. var cs = Math.cos(quOverP);
  25813. var tx = radius * (2 + cs) * 0.5 * cu;
  25814. var ty = radius * (2 + cs) * su * 0.5;
  25815. var tz = radius * Math.sin(quOverP) * 0.5;
  25816. return new BABYLON.Vector3(tx, ty, tz);
  25817. };
  25818. // Vertices
  25819. for (var i = 0; i <= radialSegments; i++) {
  25820. var modI = i % radialSegments;
  25821. var u = modI / radialSegments * 2 * p * Math.PI;
  25822. var p1 = getPos(u);
  25823. var p2 = getPos(u + 0.01);
  25824. var tang = p2.subtract(p1);
  25825. var n = p2.add(p1);
  25826. var bitan = BABYLON.Vector3.Cross(tang, n);
  25827. n = BABYLON.Vector3.Cross(bitan, tang);
  25828. bitan.normalize();
  25829. n.normalize();
  25830. for (var j = 0; j < tubularSegments; j++) {
  25831. var modJ = j % tubularSegments;
  25832. var v = modJ / tubularSegments * 2 * Math.PI;
  25833. var cx = -tube * Math.cos(v);
  25834. var cy = tube * Math.sin(v);
  25835. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25836. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25837. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25838. uvs.push(i / radialSegments);
  25839. uvs.push(j / tubularSegments);
  25840. }
  25841. }
  25842. for (i = 0; i < radialSegments; i++) {
  25843. for (j = 0; j < tubularSegments; j++) {
  25844. var jNext = (j + 1) % tubularSegments;
  25845. var a = i * tubularSegments + j;
  25846. var b = (i + 1) * tubularSegments + j;
  25847. var c = (i + 1) * tubularSegments + jNext;
  25848. var d = i * tubularSegments + jNext;
  25849. indices.push(d);
  25850. indices.push(b);
  25851. indices.push(a);
  25852. indices.push(d);
  25853. indices.push(c);
  25854. indices.push(b);
  25855. }
  25856. }
  25857. // Normals
  25858. VertexData.ComputeNormals(positions, indices, normals);
  25859. // Sides
  25860. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25861. // Result
  25862. var vertexData = new VertexData();
  25863. vertexData.indices = indices;
  25864. vertexData.positions = positions;
  25865. vertexData.normals = normals;
  25866. vertexData.uvs = uvs;
  25867. return vertexData;
  25868. };
  25869. // Tools
  25870. /**
  25871. * @param {any} - positions (number[] or Float32Array)
  25872. * @param {any} - indices (number[] or Uint16Array)
  25873. * @param {any} - normals (number[] or Float32Array)
  25874. */
  25875. VertexData.ComputeNormals = function (positions, indices, normals) {
  25876. var index = 0;
  25877. // temp Vector3
  25878. var p1 = BABYLON.Vector3.Zero();
  25879. var p2 = BABYLON.Vector3.Zero();
  25880. var p3 = BABYLON.Vector3.Zero();
  25881. var p1p2 = BABYLON.Vector3.Zero();
  25882. var p3p2 = BABYLON.Vector3.Zero();
  25883. var faceNormal = BABYLON.Vector3.Zero();
  25884. var vertexNormali1 = BABYLON.Vector3.Zero();
  25885. var vertexNormali2 = BABYLON.Vector3.Zero();
  25886. var vertexNormali3 = BABYLON.Vector3.Zero();
  25887. // indice triplet = 1 face
  25888. var nbFaces = indices.length / 3;
  25889. for (index = 0; index < nbFaces; index++) {
  25890. var i1 = indices[index * 3];
  25891. var i2 = indices[index * 3 + 1];
  25892. var i3 = indices[index * 3 + 2];
  25893. // setting the temp V3
  25894. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25895. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25896. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25897. p1.subtractToRef(p2, p1p2);
  25898. p3.subtractToRef(p2, p3p2);
  25899. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25900. faceNormal.normalize();
  25901. // All intermediate results are stored in the normals array :
  25902. // get the normals at i1, i2 and i3 indexes
  25903. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25904. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25905. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25906. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25907. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25908. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25909. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25910. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25911. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25912. // make intermediate vectors3 from normals values
  25913. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25914. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25915. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25916. // add the current face normals to these intermediate vectors3
  25917. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25918. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25919. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25920. // store back intermediate vectors3 into the normals array
  25921. normals[i1 * 3] = vertexNormali1.x;
  25922. normals[i1 * 3 + 1] = vertexNormali1.y;
  25923. normals[i1 * 3 + 2] = vertexNormali1.z;
  25924. normals[i2 * 3] = vertexNormali2.x;
  25925. normals[i2 * 3 + 1] = vertexNormali2.y;
  25926. normals[i2 * 3 + 2] = vertexNormali2.z;
  25927. normals[i3 * 3] = vertexNormali3.x;
  25928. normals[i3 * 3 + 1] = vertexNormali3.y;
  25929. normals[i3 * 3 + 2] = vertexNormali3.z;
  25930. }
  25931. // last normalization
  25932. for (index = 0; index < normals.length / 3; index++) {
  25933. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25934. vertexNormali1.normalize();
  25935. normals[index * 3] = vertexNormali1.x;
  25936. normals[index * 3 + 1] = vertexNormali1.y;
  25937. normals[index * 3 + 2] = vertexNormali1.z;
  25938. }
  25939. };
  25940. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25941. var li = indices.length;
  25942. var ln = normals.length;
  25943. var i;
  25944. var n;
  25945. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25946. switch (sideOrientation) {
  25947. case BABYLON.Mesh.FRONTSIDE:
  25948. // nothing changed
  25949. break;
  25950. case BABYLON.Mesh.BACKSIDE:
  25951. var tmp;
  25952. // indices
  25953. for (i = 0; i < li; i += 3) {
  25954. tmp = indices[i];
  25955. indices[i] = indices[i + 2];
  25956. indices[i + 2] = tmp;
  25957. }
  25958. // normals
  25959. for (n = 0; n < ln; n++) {
  25960. normals[n] = -normals[n];
  25961. }
  25962. break;
  25963. case BABYLON.Mesh.DOUBLESIDE:
  25964. // positions
  25965. var lp = positions.length;
  25966. var l = lp / 3;
  25967. for (var p = 0; p < lp; p++) {
  25968. positions[lp + p] = positions[p];
  25969. }
  25970. // indices
  25971. for (i = 0; i < li; i += 3) {
  25972. indices[i + li] = indices[i + 2] + l;
  25973. indices[i + 1 + li] = indices[i + 1] + l;
  25974. indices[i + 2 + li] = indices[i] + l;
  25975. }
  25976. // normals
  25977. for (n = 0; n < ln; n++) {
  25978. normals[ln + n] = -normals[n];
  25979. }
  25980. // uvs
  25981. var lu = uvs.length;
  25982. for (var u = 0; u < lu; u++) {
  25983. uvs[u + lu] = uvs[u];
  25984. }
  25985. break;
  25986. }
  25987. };
  25988. return VertexData;
  25989. })();
  25990. BABYLON.VertexData = VertexData;
  25991. })(BABYLON || (BABYLON = {}));
  25992. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25993. var __extends = (this && this.__extends) || function (d, b) {
  25994. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25995. function __() { this.constructor = d; }
  25996. __.prototype = b.prototype;
  25997. d.prototype = new __();
  25998. };
  25999. var BABYLON;
  26000. (function (BABYLON) {
  26001. var AnaglyphFreeCamera = (function (_super) {
  26002. __extends(AnaglyphFreeCamera, _super);
  26003. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  26004. _super.call(this, name, position, scene);
  26005. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  26006. }
  26007. return AnaglyphFreeCamera;
  26008. })(BABYLON.FreeCamera);
  26009. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  26010. var AnaglyphArcRotateCamera = (function (_super) {
  26011. __extends(AnaglyphArcRotateCamera, _super);
  26012. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  26013. _super.call(this, name, alpha, beta, radius, target, scene);
  26014. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  26015. }
  26016. return AnaglyphArcRotateCamera;
  26017. })(BABYLON.ArcRotateCamera);
  26018. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  26019. var AnaglyphGamepadCamera = (function (_super) {
  26020. __extends(AnaglyphGamepadCamera, _super);
  26021. function AnaglyphGamepadCamera(name, position, eyeSpace, scene) {
  26022. _super.call(this, name, position, scene);
  26023. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  26024. }
  26025. return AnaglyphGamepadCamera;
  26026. })(BABYLON.GamepadCamera);
  26027. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  26028. })(BABYLON || (BABYLON = {}));
  26029. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  26030. var __extends = (this && this.__extends) || function (d, b) {
  26031. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26032. function __() { this.constructor = d; }
  26033. __.prototype = b.prototype;
  26034. d.prototype = new __();
  26035. };
  26036. var BABYLON;
  26037. (function (BABYLON) {
  26038. var AnaglyphPostProcess = (function (_super) {
  26039. __extends(AnaglyphPostProcess, _super);
  26040. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26041. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  26042. }
  26043. return AnaglyphPostProcess;
  26044. })(BABYLON.PostProcess);
  26045. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  26046. })(BABYLON || (BABYLON = {}));
  26047. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  26048. var BABYLON;
  26049. (function (BABYLON) {
  26050. var Tags = (function () {
  26051. function Tags() {
  26052. }
  26053. Tags.EnableFor = function (obj) {
  26054. obj._tags = obj._tags || {};
  26055. obj.hasTags = function () {
  26056. return Tags.HasTags(obj);
  26057. };
  26058. obj.addTags = function (tagsString) {
  26059. return Tags.AddTagsTo(obj, tagsString);
  26060. };
  26061. obj.removeTags = function (tagsString) {
  26062. return Tags.RemoveTagsFrom(obj, tagsString);
  26063. };
  26064. obj.matchesTagsQuery = function (tagsQuery) {
  26065. return Tags.MatchesQuery(obj, tagsQuery);
  26066. };
  26067. };
  26068. Tags.DisableFor = function (obj) {
  26069. delete obj._tags;
  26070. delete obj.hasTags;
  26071. delete obj.addTags;
  26072. delete obj.removeTags;
  26073. delete obj.matchesTagsQuery;
  26074. };
  26075. Tags.HasTags = function (obj) {
  26076. if (!obj._tags) {
  26077. return false;
  26078. }
  26079. return !BABYLON.Tools.IsEmpty(obj._tags);
  26080. };
  26081. Tags.GetTags = function (obj) {
  26082. if (!obj._tags) {
  26083. return null;
  26084. }
  26085. return obj._tags;
  26086. };
  26087. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26088. // a tag cannot start with '||', '&&', and '!'
  26089. // it cannot contain whitespaces
  26090. Tags.AddTagsTo = function (obj, tagsString) {
  26091. if (!tagsString) {
  26092. return;
  26093. }
  26094. var tags = tagsString.split(" ");
  26095. for (var t in tags) {
  26096. Tags._AddTagTo(obj, tags[t]);
  26097. }
  26098. };
  26099. Tags._AddTagTo = function (obj, tag) {
  26100. tag = tag.trim();
  26101. if (tag === "" || tag === "true" || tag === "false") {
  26102. return;
  26103. }
  26104. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26105. return;
  26106. }
  26107. Tags.EnableFor(obj);
  26108. obj._tags[tag] = true;
  26109. };
  26110. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26111. if (!Tags.HasTags(obj)) {
  26112. return;
  26113. }
  26114. var tags = tagsString.split(" ");
  26115. for (var t in tags) {
  26116. Tags._RemoveTagFrom(obj, tags[t]);
  26117. }
  26118. };
  26119. Tags._RemoveTagFrom = function (obj, tag) {
  26120. delete obj._tags[tag];
  26121. };
  26122. Tags.MatchesQuery = function (obj, tagsQuery) {
  26123. if (tagsQuery === undefined) {
  26124. return true;
  26125. }
  26126. if (tagsQuery === "") {
  26127. return Tags.HasTags(obj);
  26128. }
  26129. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26130. };
  26131. return Tags;
  26132. })();
  26133. BABYLON.Tags = Tags;
  26134. })(BABYLON || (BABYLON = {}));
  26135. //# sourceMappingURL=babylon.tags.js.map
  26136. var BABYLON;
  26137. (function (BABYLON) {
  26138. var Internals;
  26139. (function (Internals) {
  26140. var AndOrNotEvaluator = (function () {
  26141. function AndOrNotEvaluator() {
  26142. }
  26143. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26144. if (!query.match(/\([^\(\)]*\)/g)) {
  26145. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26146. }
  26147. else {
  26148. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26149. // remove parenthesis
  26150. r = r.slice(1, r.length - 1);
  26151. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26152. });
  26153. }
  26154. if (query === "true") {
  26155. return true;
  26156. }
  26157. if (query === "false") {
  26158. return false;
  26159. }
  26160. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26161. };
  26162. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26163. evaluateCallback = evaluateCallback || (function (r) {
  26164. return r === "true" ? true : false;
  26165. });
  26166. var result;
  26167. var or = parenthesisContent.split("||");
  26168. for (var i in or) {
  26169. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26170. var and = ori.split("&&");
  26171. if (and.length > 1) {
  26172. for (var j = 0; j < and.length; ++j) {
  26173. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26174. if (andj !== "true" && andj !== "false") {
  26175. if (andj[0] === "!") {
  26176. result = !evaluateCallback(andj.substring(1));
  26177. }
  26178. else {
  26179. result = evaluateCallback(andj);
  26180. }
  26181. }
  26182. else {
  26183. result = andj === "true" ? true : false;
  26184. }
  26185. if (!result) {
  26186. ori = "false";
  26187. break;
  26188. }
  26189. }
  26190. }
  26191. if (result || ori === "true") {
  26192. result = true;
  26193. break;
  26194. }
  26195. // result equals false (or undefined)
  26196. if (ori !== "true" && ori !== "false") {
  26197. if (ori[0] === "!") {
  26198. result = !evaluateCallback(ori.substring(1));
  26199. }
  26200. else {
  26201. result = evaluateCallback(ori);
  26202. }
  26203. }
  26204. else {
  26205. result = ori === "true" ? true : false;
  26206. }
  26207. }
  26208. // the whole parenthesis scope is replaced by 'true' or 'false'
  26209. return result ? "true" : "false";
  26210. };
  26211. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26212. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26213. // remove whitespaces
  26214. r = r.replace(/[\s]/g, function () { return ""; });
  26215. return r.length % 2 ? "!" : "";
  26216. });
  26217. booleanString = booleanString.trim();
  26218. if (booleanString === "!true") {
  26219. booleanString = "false";
  26220. }
  26221. else if (booleanString === "!false") {
  26222. booleanString = "true";
  26223. }
  26224. return booleanString;
  26225. };
  26226. return AndOrNotEvaluator;
  26227. })();
  26228. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26229. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26230. })(BABYLON || (BABYLON = {}));
  26231. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  26232. var BABYLON;
  26233. (function (BABYLON) {
  26234. var PostProcessRenderPass = (function () {
  26235. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26236. this._enabled = true;
  26237. this._refCount = 0;
  26238. this._name = name;
  26239. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26240. this.setRenderList(renderList);
  26241. this._renderTexture.onBeforeRender = beforeRender;
  26242. this._renderTexture.onAfterRender = afterRender;
  26243. this._scene = scene;
  26244. this._renderList = renderList;
  26245. }
  26246. // private
  26247. PostProcessRenderPass.prototype._incRefCount = function () {
  26248. if (this._refCount === 0) {
  26249. this._scene.customRenderTargets.push(this._renderTexture);
  26250. }
  26251. return ++this._refCount;
  26252. };
  26253. PostProcessRenderPass.prototype._decRefCount = function () {
  26254. this._refCount--;
  26255. if (this._refCount <= 0) {
  26256. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26257. }
  26258. return this._refCount;
  26259. };
  26260. PostProcessRenderPass.prototype._update = function () {
  26261. this.setRenderList(this._renderList);
  26262. };
  26263. // public
  26264. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26265. this._renderTexture.renderList = renderList;
  26266. };
  26267. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26268. return this._renderTexture;
  26269. };
  26270. return PostProcessRenderPass;
  26271. })();
  26272. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26273. })(BABYLON || (BABYLON = {}));
  26274. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26275. var BABYLON;
  26276. (function (BABYLON) {
  26277. var PostProcessRenderEffect = (function () {
  26278. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26279. this._engine = engine;
  26280. this._name = name;
  26281. this._singleInstance = singleInstance || true;
  26282. this._getPostProcess = getPostProcess;
  26283. this._cameras = [];
  26284. this._indicesForCamera = [];
  26285. this._postProcesses = {};
  26286. this._renderPasses = {};
  26287. this._renderEffectAsPasses = {};
  26288. }
  26289. PostProcessRenderEffect.prototype._update = function () {
  26290. for (var renderPassName in this._renderPasses) {
  26291. this._renderPasses[renderPassName]._update();
  26292. }
  26293. };
  26294. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26295. this._renderPasses[renderPass._name] = renderPass;
  26296. this._linkParameters();
  26297. };
  26298. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26299. delete this._renderPasses[renderPass._name];
  26300. this._linkParameters();
  26301. };
  26302. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26303. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26304. this._linkParameters();
  26305. };
  26306. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26307. for (var renderPassName in this._renderPasses) {
  26308. if (renderPassName === passName) {
  26309. return this._renderPasses[passName];
  26310. }
  26311. }
  26312. };
  26313. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26314. this._renderPasses = {};
  26315. this._linkParameters();
  26316. };
  26317. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26318. var cameraKey;
  26319. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26320. for (var i = 0; i < _cam.length; i++) {
  26321. var camera = _cam[i];
  26322. var cameraName = camera.name;
  26323. if (this._singleInstance) {
  26324. cameraKey = 0;
  26325. }
  26326. else {
  26327. cameraKey = cameraName;
  26328. }
  26329. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26330. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26331. if (!this._indicesForCamera[cameraName]) {
  26332. this._indicesForCamera[cameraName] = [];
  26333. }
  26334. this._indicesForCamera[cameraName].push(index);
  26335. if (this._cameras.indexOf(camera) === -1) {
  26336. this._cameras[cameraName] = camera;
  26337. }
  26338. for (var passName in this._renderPasses) {
  26339. this._renderPasses[passName]._incRefCount();
  26340. }
  26341. }
  26342. this._linkParameters();
  26343. };
  26344. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26345. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26346. for (var i = 0; i < _cam.length; i++) {
  26347. var camera = _cam[i];
  26348. var cameraName = camera.name;
  26349. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26350. var index = this._cameras.indexOf(cameraName);
  26351. this._indicesForCamera.splice(index, 1);
  26352. this._cameras.splice(index, 1);
  26353. for (var passName in this._renderPasses) {
  26354. this._renderPasses[passName]._decRefCount();
  26355. }
  26356. }
  26357. };
  26358. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26359. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26360. for (var i = 0; i < _cam.length; i++) {
  26361. var camera = _cam[i];
  26362. var cameraName = camera.name;
  26363. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26364. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26365. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26366. }
  26367. }
  26368. for (var passName in this._renderPasses) {
  26369. this._renderPasses[passName]._incRefCount();
  26370. }
  26371. }
  26372. };
  26373. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26374. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26375. for (var i = 0; i < _cam.length; i++) {
  26376. var camera = _cam[i];
  26377. var cameraName = camera.Name;
  26378. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26379. for (var passName in this._renderPasses) {
  26380. this._renderPasses[passName]._decRefCount();
  26381. }
  26382. }
  26383. };
  26384. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26385. if (this._singleInstance) {
  26386. return this._postProcesses[0];
  26387. }
  26388. else {
  26389. return this._postProcesses[camera.name];
  26390. }
  26391. };
  26392. PostProcessRenderEffect.prototype._linkParameters = function () {
  26393. var _this = this;
  26394. for (var index in this._postProcesses) {
  26395. if (this.applyParameters) {
  26396. this.applyParameters(this._postProcesses[index]);
  26397. }
  26398. this._postProcesses[index].onBeforeRender = function (effect) {
  26399. _this._linkTextures(effect);
  26400. };
  26401. }
  26402. };
  26403. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26404. for (var renderPassName in this._renderPasses) {
  26405. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26406. }
  26407. for (var renderEffectName in this._renderEffectAsPasses) {
  26408. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26409. }
  26410. };
  26411. return PostProcessRenderEffect;
  26412. })();
  26413. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26414. })(BABYLON || (BABYLON = {}));
  26415. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26416. var BABYLON;
  26417. (function (BABYLON) {
  26418. var PostProcessRenderPipeline = (function () {
  26419. function PostProcessRenderPipeline(engine, name) {
  26420. this._engine = engine;
  26421. this._name = name;
  26422. this._renderEffects = {};
  26423. this._renderEffectsForIsolatedPass = {};
  26424. this._cameras = [];
  26425. }
  26426. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26427. this._renderEffects[renderEffect._name] = renderEffect;
  26428. };
  26429. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26430. var renderEffects = this._renderEffects[renderEffectName];
  26431. if (!renderEffects) {
  26432. return;
  26433. }
  26434. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26435. };
  26436. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26437. var renderEffects = this._renderEffects[renderEffectName];
  26438. if (!renderEffects) {
  26439. return;
  26440. }
  26441. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26442. };
  26443. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26444. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26445. var indicesToDelete = [];
  26446. for (var i = 0; i < _cam.length; i++) {
  26447. var camera = _cam[i];
  26448. var cameraName = camera.name;
  26449. if (this._cameras.indexOf(camera) === -1) {
  26450. this._cameras[cameraName] = camera;
  26451. }
  26452. else if (unique) {
  26453. indicesToDelete.push(i);
  26454. }
  26455. }
  26456. for (var i = 0; i < indicesToDelete.length; i++) {
  26457. cameras.splice(indicesToDelete[i], 1);
  26458. }
  26459. for (var renderEffectName in this._renderEffects) {
  26460. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26461. }
  26462. };
  26463. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26464. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26465. for (var renderEffectName in this._renderEffects) {
  26466. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26467. }
  26468. for (var i = 0; i < _cam.length; i++) {
  26469. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26470. }
  26471. };
  26472. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26473. var _this = this;
  26474. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26475. var pass = null;
  26476. for (var renderEffectName in this._renderEffects) {
  26477. pass = this._renderEffects[renderEffectName].getPass(passName);
  26478. if (pass != null) {
  26479. break;
  26480. }
  26481. }
  26482. if (pass === null) {
  26483. return;
  26484. }
  26485. for (var renderEffectName in this._renderEffects) {
  26486. this._renderEffects[renderEffectName]._disable(_cam);
  26487. }
  26488. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26489. for (var i = 0; i < _cam.length; i++) {
  26490. var camera = _cam[i];
  26491. var cameraName = camera.name;
  26492. 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); });
  26493. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26494. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26495. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26496. }
  26497. };
  26498. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26499. var _this = this;
  26500. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26501. for (var i = 0; i < _cam.length; i++) {
  26502. var camera = _cam[i];
  26503. var cameraName = camera.name;
  26504. 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); });
  26505. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26506. }
  26507. for (var renderEffectName in this._renderEffects) {
  26508. this._renderEffects[renderEffectName]._enable(_cam);
  26509. }
  26510. };
  26511. PostProcessRenderPipeline.prototype._update = function () {
  26512. for (var renderEffectName in this._renderEffects) {
  26513. this._renderEffects[renderEffectName]._update();
  26514. }
  26515. for (var i = 0; i < this._cameras.length; i++) {
  26516. var cameraName = this._cameras[i].name;
  26517. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26518. this._renderEffectsForIsolatedPass[cameraName]._update();
  26519. }
  26520. }
  26521. };
  26522. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26523. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26524. return PostProcessRenderPipeline;
  26525. })();
  26526. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26527. })(BABYLON || (BABYLON = {}));
  26528. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26529. var BABYLON;
  26530. (function (BABYLON) {
  26531. var PostProcessRenderPipelineManager = (function () {
  26532. function PostProcessRenderPipelineManager() {
  26533. this._renderPipelines = {};
  26534. }
  26535. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26536. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26537. };
  26538. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26539. var renderPipeline = this._renderPipelines[renderPipelineName];
  26540. if (!renderPipeline) {
  26541. return;
  26542. }
  26543. renderPipeline._attachCameras(cameras, unique);
  26544. };
  26545. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26546. var renderPipeline = this._renderPipelines[renderPipelineName];
  26547. if (!renderPipeline) {
  26548. return;
  26549. }
  26550. renderPipeline._detachCameras(cameras);
  26551. };
  26552. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26553. var renderPipeline = this._renderPipelines[renderPipelineName];
  26554. if (!renderPipeline) {
  26555. return;
  26556. }
  26557. renderPipeline._enableEffect(renderEffectName, cameras);
  26558. };
  26559. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26560. var renderPipeline = this._renderPipelines[renderPipelineName];
  26561. if (!renderPipeline) {
  26562. return;
  26563. }
  26564. renderPipeline._disableEffect(renderEffectName, cameras);
  26565. };
  26566. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26567. var renderPipeline = this._renderPipelines[renderPipelineName];
  26568. if (!renderPipeline) {
  26569. return;
  26570. }
  26571. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26572. };
  26573. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26574. var renderPipeline = this._renderPipelines[renderPipelineName];
  26575. if (!renderPipeline) {
  26576. return;
  26577. }
  26578. renderPipeline._disableDisplayOnlyPass(cameras);
  26579. };
  26580. PostProcessRenderPipelineManager.prototype.update = function () {
  26581. for (var renderPipelineName in this._renderPipelines) {
  26582. this._renderPipelines[renderPipelineName]._update();
  26583. }
  26584. };
  26585. return PostProcessRenderPipelineManager;
  26586. })();
  26587. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26588. })(BABYLON || (BABYLON = {}));
  26589. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26590. var __extends = (this && this.__extends) || function (d, b) {
  26591. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26592. function __() { this.constructor = d; }
  26593. __.prototype = b.prototype;
  26594. d.prototype = new __();
  26595. };
  26596. var BABYLON;
  26597. (function (BABYLON) {
  26598. var DisplayPassPostProcess = (function (_super) {
  26599. __extends(DisplayPassPostProcess, _super);
  26600. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26601. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26602. }
  26603. return DisplayPassPostProcess;
  26604. })(BABYLON.PostProcess);
  26605. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26606. })(BABYLON || (BABYLON = {}));
  26607. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26608. var BABYLON;
  26609. (function (BABYLON) {
  26610. var BoundingBoxRenderer = (function () {
  26611. function BoundingBoxRenderer(scene) {
  26612. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26613. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26614. this.showBackLines = true;
  26615. this.renderList = new BABYLON.SmartArray(32);
  26616. this._scene = scene;
  26617. }
  26618. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26619. if (this._colorShader) {
  26620. return;
  26621. }
  26622. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26623. attributes: ["position"],
  26624. uniforms: ["worldViewProjection", "color"]
  26625. });
  26626. var engine = this._scene.getEngine();
  26627. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26628. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26629. 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]);
  26630. };
  26631. BoundingBoxRenderer.prototype.reset = function () {
  26632. this.renderList.reset();
  26633. };
  26634. BoundingBoxRenderer.prototype.render = function () {
  26635. if (this.renderList.length === 0) {
  26636. return;
  26637. }
  26638. this._prepareRessources();
  26639. if (!this._colorShader.isReady()) {
  26640. return;
  26641. }
  26642. var engine = this._scene.getEngine();
  26643. engine.setDepthWrite(false);
  26644. this._colorShader._preBind();
  26645. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26646. var boundingBox = this.renderList.data[boundingBoxIndex];
  26647. var min = boundingBox.minimum;
  26648. var max = boundingBox.maximum;
  26649. var diff = max.subtract(min);
  26650. var median = min.add(diff.scale(0.5));
  26651. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26652. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26653. .multiply(boundingBox.getWorldMatrix());
  26654. // VBOs
  26655. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26656. if (this.showBackLines) {
  26657. // Back
  26658. engine.setDepthFunctionToGreaterOrEqual();
  26659. this._scene.resetCachedMaterial();
  26660. this._colorShader.setColor4("color", this.backColor.toColor4());
  26661. this._colorShader.bind(worldMatrix);
  26662. // Draw order
  26663. engine.draw(false, 0, 24);
  26664. }
  26665. // Front
  26666. engine.setDepthFunctionToLess();
  26667. this._scene.resetCachedMaterial();
  26668. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26669. this._colorShader.bind(worldMatrix);
  26670. // Draw order
  26671. engine.draw(false, 0, 24);
  26672. }
  26673. this._colorShader.unbind();
  26674. engine.setDepthFunctionToLessOrEqual();
  26675. engine.setDepthWrite(true);
  26676. };
  26677. BoundingBoxRenderer.prototype.dispose = function () {
  26678. if (!this._colorShader) {
  26679. return;
  26680. }
  26681. this._colorShader.dispose();
  26682. this._vb.dispose();
  26683. this._scene.getEngine()._releaseBuffer(this._ib);
  26684. };
  26685. return BoundingBoxRenderer;
  26686. })();
  26687. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26688. })(BABYLON || (BABYLON = {}));
  26689. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26690. var __extends = (this && this.__extends) || function (d, b) {
  26691. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26692. function __() { this.constructor = d; }
  26693. __.prototype = b.prototype;
  26694. d.prototype = new __();
  26695. };
  26696. var BABYLON;
  26697. (function (BABYLON) {
  26698. var Condition = (function () {
  26699. function Condition(actionManager) {
  26700. this._actionManager = actionManager;
  26701. }
  26702. Condition.prototype.isValid = function () {
  26703. return true;
  26704. };
  26705. Condition.prototype._getProperty = function (propertyPath) {
  26706. return this._actionManager._getProperty(propertyPath);
  26707. };
  26708. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26709. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26710. };
  26711. return Condition;
  26712. })();
  26713. BABYLON.Condition = Condition;
  26714. var ValueCondition = (function (_super) {
  26715. __extends(ValueCondition, _super);
  26716. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26717. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26718. _super.call(this, actionManager);
  26719. this.propertyPath = propertyPath;
  26720. this.value = value;
  26721. this.operator = operator;
  26722. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26723. this._property = this._getProperty(this.propertyPath);
  26724. }
  26725. Object.defineProperty(ValueCondition, "IsEqual", {
  26726. get: function () {
  26727. return ValueCondition._IsEqual;
  26728. },
  26729. enumerable: true,
  26730. configurable: true
  26731. });
  26732. Object.defineProperty(ValueCondition, "IsDifferent", {
  26733. get: function () {
  26734. return ValueCondition._IsDifferent;
  26735. },
  26736. enumerable: true,
  26737. configurable: true
  26738. });
  26739. Object.defineProperty(ValueCondition, "IsGreater", {
  26740. get: function () {
  26741. return ValueCondition._IsGreater;
  26742. },
  26743. enumerable: true,
  26744. configurable: true
  26745. });
  26746. Object.defineProperty(ValueCondition, "IsLesser", {
  26747. get: function () {
  26748. return ValueCondition._IsLesser;
  26749. },
  26750. enumerable: true,
  26751. configurable: true
  26752. });
  26753. // Methods
  26754. ValueCondition.prototype.isValid = function () {
  26755. switch (this.operator) {
  26756. case ValueCondition.IsGreater:
  26757. return this._target[this._property] > this.value;
  26758. case ValueCondition.IsLesser:
  26759. return this._target[this._property] < this.value;
  26760. case ValueCondition.IsEqual:
  26761. case ValueCondition.IsDifferent:
  26762. var check;
  26763. if (this.value.equals) {
  26764. check = this.value.equals(this._target[this._property]);
  26765. }
  26766. else {
  26767. check = this.value === this._target[this._property];
  26768. }
  26769. return this.operator === ValueCondition.IsEqual ? check : !check;
  26770. }
  26771. return false;
  26772. };
  26773. // Statics
  26774. ValueCondition._IsEqual = 0;
  26775. ValueCondition._IsDifferent = 1;
  26776. ValueCondition._IsGreater = 2;
  26777. ValueCondition._IsLesser = 3;
  26778. return ValueCondition;
  26779. })(Condition);
  26780. BABYLON.ValueCondition = ValueCondition;
  26781. var PredicateCondition = (function (_super) {
  26782. __extends(PredicateCondition, _super);
  26783. function PredicateCondition(actionManager, predicate) {
  26784. _super.call(this, actionManager);
  26785. this.predicate = predicate;
  26786. }
  26787. PredicateCondition.prototype.isValid = function () {
  26788. return this.predicate();
  26789. };
  26790. return PredicateCondition;
  26791. })(Condition);
  26792. BABYLON.PredicateCondition = PredicateCondition;
  26793. var StateCondition = (function (_super) {
  26794. __extends(StateCondition, _super);
  26795. function StateCondition(actionManager, target, value) {
  26796. _super.call(this, actionManager);
  26797. this.value = value;
  26798. this._target = target;
  26799. }
  26800. // Methods
  26801. StateCondition.prototype.isValid = function () {
  26802. return this._target.state === this.value;
  26803. };
  26804. return StateCondition;
  26805. })(Condition);
  26806. BABYLON.StateCondition = StateCondition;
  26807. })(BABYLON || (BABYLON = {}));
  26808. //# sourceMappingURL=babylon.condition.js.map
  26809. var BABYLON;
  26810. (function (BABYLON) {
  26811. var Action = (function () {
  26812. function Action(triggerOptions, condition) {
  26813. this.triggerOptions = triggerOptions;
  26814. if (triggerOptions.parameter) {
  26815. this.trigger = triggerOptions.trigger;
  26816. this._triggerParameter = triggerOptions.parameter;
  26817. }
  26818. else {
  26819. this.trigger = triggerOptions;
  26820. }
  26821. this._nextActiveAction = this;
  26822. this._condition = condition;
  26823. }
  26824. // Methods
  26825. Action.prototype._prepare = function () {
  26826. };
  26827. Action.prototype.getTriggerParameter = function () {
  26828. return this._triggerParameter;
  26829. };
  26830. Action.prototype._executeCurrent = function (evt) {
  26831. if (this._nextActiveAction._condition) {
  26832. var condition = this._nextActiveAction._condition;
  26833. var currentRenderId = this._actionManager.getScene().getRenderId();
  26834. // We cache the current evaluation for the current frame
  26835. if (condition._evaluationId === currentRenderId) {
  26836. if (!condition._currentResult) {
  26837. return;
  26838. }
  26839. }
  26840. else {
  26841. condition._evaluationId = currentRenderId;
  26842. if (!condition.isValid()) {
  26843. condition._currentResult = false;
  26844. return;
  26845. }
  26846. condition._currentResult = true;
  26847. }
  26848. }
  26849. this._nextActiveAction.execute(evt);
  26850. if (this._nextActiveAction._child) {
  26851. if (!this._nextActiveAction._child._actionManager) {
  26852. this._nextActiveAction._child._actionManager = this._actionManager;
  26853. }
  26854. this._nextActiveAction = this._nextActiveAction._child;
  26855. }
  26856. else {
  26857. this._nextActiveAction = this;
  26858. }
  26859. };
  26860. Action.prototype.execute = function (evt) {
  26861. };
  26862. Action.prototype.then = function (action) {
  26863. this._child = action;
  26864. action._actionManager = this._actionManager;
  26865. action._prepare();
  26866. return action;
  26867. };
  26868. Action.prototype._getProperty = function (propertyPath) {
  26869. return this._actionManager._getProperty(propertyPath);
  26870. };
  26871. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26872. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26873. };
  26874. return Action;
  26875. })();
  26876. BABYLON.Action = Action;
  26877. })(BABYLON || (BABYLON = {}));
  26878. //# sourceMappingURL=babylon.action.js.map
  26879. var BABYLON;
  26880. (function (BABYLON) {
  26881. /**
  26882. * ActionEvent is the event beint sent when an action is triggered.
  26883. */
  26884. var ActionEvent = (function () {
  26885. /**
  26886. * @constructor
  26887. * @param source The mesh that triggered the action.
  26888. * @param pointerX the X mouse cursor position at the time of the event
  26889. * @param pointerY the Y mouse cursor position at the time of the event
  26890. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26891. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26892. */
  26893. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26894. this.source = source;
  26895. this.pointerX = pointerX;
  26896. this.pointerY = pointerY;
  26897. this.meshUnderPointer = meshUnderPointer;
  26898. this.sourceEvent = sourceEvent;
  26899. }
  26900. /**
  26901. * Helper function to auto-create an ActionEvent from a source mesh.
  26902. * @param source the source mesh that triggered the event
  26903. * @param evt {Event} The original (browser) event
  26904. */
  26905. ActionEvent.CreateNew = function (source, evt) {
  26906. var scene = source.getScene();
  26907. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26908. };
  26909. /**
  26910. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26911. * @param scene the scene where the event occurred
  26912. * @param evt {Event} The original (browser) event
  26913. */
  26914. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26915. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26916. };
  26917. return ActionEvent;
  26918. })();
  26919. BABYLON.ActionEvent = ActionEvent;
  26920. /**
  26921. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26922. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26923. */
  26924. var ActionManager = (function () {
  26925. function ActionManager(scene) {
  26926. // Members
  26927. this.actions = new Array();
  26928. this._scene = scene;
  26929. scene._actionManagers.push(this);
  26930. }
  26931. Object.defineProperty(ActionManager, "NothingTrigger", {
  26932. get: function () {
  26933. return ActionManager._NothingTrigger;
  26934. },
  26935. enumerable: true,
  26936. configurable: true
  26937. });
  26938. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26939. get: function () {
  26940. return ActionManager._OnPickTrigger;
  26941. },
  26942. enumerable: true,
  26943. configurable: true
  26944. });
  26945. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26946. get: function () {
  26947. return ActionManager._OnLeftPickTrigger;
  26948. },
  26949. enumerable: true,
  26950. configurable: true
  26951. });
  26952. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26953. get: function () {
  26954. return ActionManager._OnRightPickTrigger;
  26955. },
  26956. enumerable: true,
  26957. configurable: true
  26958. });
  26959. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26960. get: function () {
  26961. return ActionManager._OnCenterPickTrigger;
  26962. },
  26963. enumerable: true,
  26964. configurable: true
  26965. });
  26966. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26967. get: function () {
  26968. return ActionManager._OnPointerOverTrigger;
  26969. },
  26970. enumerable: true,
  26971. configurable: true
  26972. });
  26973. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26974. get: function () {
  26975. return ActionManager._OnPointerOutTrigger;
  26976. },
  26977. enumerable: true,
  26978. configurable: true
  26979. });
  26980. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26981. get: function () {
  26982. return ActionManager._OnEveryFrameTrigger;
  26983. },
  26984. enumerable: true,
  26985. configurable: true
  26986. });
  26987. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26988. get: function () {
  26989. return ActionManager._OnIntersectionEnterTrigger;
  26990. },
  26991. enumerable: true,
  26992. configurable: true
  26993. });
  26994. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26995. get: function () {
  26996. return ActionManager._OnIntersectionExitTrigger;
  26997. },
  26998. enumerable: true,
  26999. configurable: true
  27000. });
  27001. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27002. get: function () {
  27003. return ActionManager._OnKeyDownTrigger;
  27004. },
  27005. enumerable: true,
  27006. configurable: true
  27007. });
  27008. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27009. get: function () {
  27010. return ActionManager._OnKeyUpTrigger;
  27011. },
  27012. enumerable: true,
  27013. configurable: true
  27014. });
  27015. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27016. get: function () {
  27017. return ActionManager._OnPickUpTrigger;
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. // Methods
  27023. ActionManager.prototype.dispose = function () {
  27024. var index = this._scene._actionManagers.indexOf(this);
  27025. if (index > -1) {
  27026. this._scene._actionManagers.splice(index, 1);
  27027. }
  27028. };
  27029. ActionManager.prototype.getScene = function () {
  27030. return this._scene;
  27031. };
  27032. /**
  27033. * Does this action manager handles actions of any of the given triggers
  27034. * @param {number[]} triggers - the triggers to be tested
  27035. * @return {boolean} whether one (or more) of the triggers is handeled
  27036. */
  27037. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27038. for (var index = 0; index < this.actions.length; index++) {
  27039. var action = this.actions[index];
  27040. if (triggers.indexOf(action.trigger) > -1) {
  27041. return true;
  27042. }
  27043. }
  27044. return false;
  27045. };
  27046. /**
  27047. * Does this action manager handles actions of a given trigger
  27048. * @param {number} trigger - the trigger to be tested
  27049. * @return {boolean} whether the trigger is handeled
  27050. */
  27051. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27052. for (var index = 0; index < this.actions.length; index++) {
  27053. var action = this.actions[index];
  27054. if (action.trigger === trigger) {
  27055. return true;
  27056. }
  27057. }
  27058. return false;
  27059. };
  27060. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27061. /**
  27062. * Does this action manager has pointer triggers
  27063. * @return {boolean} whether or not it has pointer triggers
  27064. */
  27065. get: function () {
  27066. for (var index = 0; index < this.actions.length; index++) {
  27067. var action = this.actions[index];
  27068. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27069. return true;
  27070. }
  27071. if (action.trigger == ActionManager._OnPickUpTrigger) {
  27072. return true;
  27073. }
  27074. }
  27075. return false;
  27076. },
  27077. enumerable: true,
  27078. configurable: true
  27079. });
  27080. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27081. /**
  27082. * Does this action manager has pick triggers
  27083. * @return {boolean} whether or not it has pick triggers
  27084. */
  27085. get: function () {
  27086. for (var index = 0; index < this.actions.length; index++) {
  27087. var action = this.actions[index];
  27088. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  27089. return true;
  27090. }
  27091. }
  27092. return false;
  27093. },
  27094. enumerable: true,
  27095. configurable: true
  27096. });
  27097. /**
  27098. * Registers an action to this action manager
  27099. * @param {BABYLON.Action} action - the action to be registered
  27100. * @return {BABYLON.Action} the action amended (prepared) after registration
  27101. */
  27102. ActionManager.prototype.registerAction = function (action) {
  27103. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27104. if (this.getScene().actionManager !== this) {
  27105. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27106. return null;
  27107. }
  27108. }
  27109. this.actions.push(action);
  27110. action._actionManager = this;
  27111. action._prepare();
  27112. return action;
  27113. };
  27114. /**
  27115. * Process a specific trigger
  27116. * @param {number} trigger - the trigger to process
  27117. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27118. */
  27119. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27120. for (var index = 0; index < this.actions.length; index++) {
  27121. var action = this.actions[index];
  27122. if (action.trigger === trigger) {
  27123. if (trigger === ActionManager.OnKeyUpTrigger
  27124. || trigger === ActionManager.OnKeyDownTrigger) {
  27125. var parameter = action.getTriggerParameter();
  27126. if (parameter) {
  27127. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27128. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27129. if (actualkey !== parameter.toLowerCase()) {
  27130. continue;
  27131. }
  27132. }
  27133. }
  27134. action._executeCurrent(evt);
  27135. }
  27136. }
  27137. };
  27138. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27139. var properties = propertyPath.split(".");
  27140. for (var index = 0; index < properties.length - 1; index++) {
  27141. target = target[properties[index]];
  27142. }
  27143. return target;
  27144. };
  27145. ActionManager.prototype._getProperty = function (propertyPath) {
  27146. var properties = propertyPath.split(".");
  27147. return properties[properties.length - 1];
  27148. };
  27149. // Statics
  27150. ActionManager._NothingTrigger = 0;
  27151. ActionManager._OnPickTrigger = 1;
  27152. ActionManager._OnLeftPickTrigger = 2;
  27153. ActionManager._OnRightPickTrigger = 3;
  27154. ActionManager._OnCenterPickTrigger = 4;
  27155. ActionManager._OnPointerOverTrigger = 5;
  27156. ActionManager._OnPointerOutTrigger = 6;
  27157. ActionManager._OnEveryFrameTrigger = 7;
  27158. ActionManager._OnIntersectionEnterTrigger = 8;
  27159. ActionManager._OnIntersectionExitTrigger = 9;
  27160. ActionManager._OnKeyDownTrigger = 10;
  27161. ActionManager._OnKeyUpTrigger = 11;
  27162. ActionManager._OnPickUpTrigger = 12;
  27163. return ActionManager;
  27164. })();
  27165. BABYLON.ActionManager = ActionManager;
  27166. })(BABYLON || (BABYLON = {}));
  27167. //# sourceMappingURL=babylon.actionManager.js.map
  27168. var __extends = (this && this.__extends) || function (d, b) {
  27169. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27170. function __() { this.constructor = d; }
  27171. __.prototype = b.prototype;
  27172. d.prototype = new __();
  27173. };
  27174. var BABYLON;
  27175. (function (BABYLON) {
  27176. var InterpolateValueAction = (function (_super) {
  27177. __extends(InterpolateValueAction, _super);
  27178. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  27179. if (duration === void 0) { duration = 1000; }
  27180. _super.call(this, triggerOptions, condition);
  27181. this.propertyPath = propertyPath;
  27182. this.value = value;
  27183. this.duration = duration;
  27184. this.stopOtherAnimations = stopOtherAnimations;
  27185. this._target = target;
  27186. }
  27187. InterpolateValueAction.prototype._prepare = function () {
  27188. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27189. this._property = this._getProperty(this.propertyPath);
  27190. };
  27191. InterpolateValueAction.prototype.execute = function () {
  27192. var scene = this._actionManager.getScene();
  27193. var keys = [
  27194. {
  27195. frame: 0,
  27196. value: this._target[this._property]
  27197. }, {
  27198. frame: 100,
  27199. value: this.value
  27200. }
  27201. ];
  27202. var dataType;
  27203. if (typeof this.value === "number") {
  27204. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27205. }
  27206. else if (this.value instanceof BABYLON.Color3) {
  27207. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27208. }
  27209. else if (this.value instanceof BABYLON.Vector3) {
  27210. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27211. }
  27212. else if (this.value instanceof BABYLON.Matrix) {
  27213. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27214. }
  27215. else if (this.value instanceof BABYLON.Quaternion) {
  27216. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27217. }
  27218. else {
  27219. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27220. return;
  27221. }
  27222. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27223. animation.setKeys(keys);
  27224. if (this.stopOtherAnimations) {
  27225. scene.stopAnimation(this._target);
  27226. }
  27227. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  27228. };
  27229. return InterpolateValueAction;
  27230. })(BABYLON.Action);
  27231. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27232. })(BABYLON || (BABYLON = {}));
  27233. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  27234. var __extends = (this && this.__extends) || function (d, b) {
  27235. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27236. function __() { this.constructor = d; }
  27237. __.prototype = b.prototype;
  27238. d.prototype = new __();
  27239. };
  27240. var BABYLON;
  27241. (function (BABYLON) {
  27242. var SwitchBooleanAction = (function (_super) {
  27243. __extends(SwitchBooleanAction, _super);
  27244. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27245. _super.call(this, triggerOptions, condition);
  27246. this.propertyPath = propertyPath;
  27247. this._target = target;
  27248. }
  27249. SwitchBooleanAction.prototype._prepare = function () {
  27250. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27251. this._property = this._getProperty(this.propertyPath);
  27252. };
  27253. SwitchBooleanAction.prototype.execute = function () {
  27254. this._target[this._property] = !this._target[this._property];
  27255. };
  27256. return SwitchBooleanAction;
  27257. })(BABYLON.Action);
  27258. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27259. var SetStateAction = (function (_super) {
  27260. __extends(SetStateAction, _super);
  27261. function SetStateAction(triggerOptions, target, value, condition) {
  27262. _super.call(this, triggerOptions, condition);
  27263. this.value = value;
  27264. this._target = target;
  27265. }
  27266. SetStateAction.prototype.execute = function () {
  27267. this._target.state = this.value;
  27268. };
  27269. return SetStateAction;
  27270. })(BABYLON.Action);
  27271. BABYLON.SetStateAction = SetStateAction;
  27272. var SetValueAction = (function (_super) {
  27273. __extends(SetValueAction, _super);
  27274. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27275. _super.call(this, triggerOptions, condition);
  27276. this.propertyPath = propertyPath;
  27277. this.value = value;
  27278. this._target = target;
  27279. }
  27280. SetValueAction.prototype._prepare = function () {
  27281. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27282. this._property = this._getProperty(this.propertyPath);
  27283. };
  27284. SetValueAction.prototype.execute = function () {
  27285. this._target[this._property] = this.value;
  27286. };
  27287. return SetValueAction;
  27288. })(BABYLON.Action);
  27289. BABYLON.SetValueAction = SetValueAction;
  27290. var IncrementValueAction = (function (_super) {
  27291. __extends(IncrementValueAction, _super);
  27292. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27293. _super.call(this, triggerOptions, condition);
  27294. this.propertyPath = propertyPath;
  27295. this.value = value;
  27296. this._target = target;
  27297. }
  27298. IncrementValueAction.prototype._prepare = function () {
  27299. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27300. this._property = this._getProperty(this.propertyPath);
  27301. if (typeof this._target[this._property] !== "number") {
  27302. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27303. }
  27304. };
  27305. IncrementValueAction.prototype.execute = function () {
  27306. this._target[this._property] += this.value;
  27307. };
  27308. return IncrementValueAction;
  27309. })(BABYLON.Action);
  27310. BABYLON.IncrementValueAction = IncrementValueAction;
  27311. var PlayAnimationAction = (function (_super) {
  27312. __extends(PlayAnimationAction, _super);
  27313. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27314. _super.call(this, triggerOptions, condition);
  27315. this.from = from;
  27316. this.to = to;
  27317. this.loop = loop;
  27318. this._target = target;
  27319. }
  27320. PlayAnimationAction.prototype._prepare = function () {
  27321. };
  27322. PlayAnimationAction.prototype.execute = function () {
  27323. var scene = this._actionManager.getScene();
  27324. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27325. };
  27326. return PlayAnimationAction;
  27327. })(BABYLON.Action);
  27328. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27329. var StopAnimationAction = (function (_super) {
  27330. __extends(StopAnimationAction, _super);
  27331. function StopAnimationAction(triggerOptions, target, condition) {
  27332. _super.call(this, triggerOptions, condition);
  27333. this._target = target;
  27334. }
  27335. StopAnimationAction.prototype._prepare = function () {
  27336. };
  27337. StopAnimationAction.prototype.execute = function () {
  27338. var scene = this._actionManager.getScene();
  27339. scene.stopAnimation(this._target);
  27340. };
  27341. return StopAnimationAction;
  27342. })(BABYLON.Action);
  27343. BABYLON.StopAnimationAction = StopAnimationAction;
  27344. var DoNothingAction = (function (_super) {
  27345. __extends(DoNothingAction, _super);
  27346. function DoNothingAction(triggerOptions, condition) {
  27347. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27348. _super.call(this, triggerOptions, condition);
  27349. }
  27350. DoNothingAction.prototype.execute = function () {
  27351. };
  27352. return DoNothingAction;
  27353. })(BABYLON.Action);
  27354. BABYLON.DoNothingAction = DoNothingAction;
  27355. var CombineAction = (function (_super) {
  27356. __extends(CombineAction, _super);
  27357. function CombineAction(triggerOptions, children, condition) {
  27358. _super.call(this, triggerOptions, condition);
  27359. this.children = children;
  27360. }
  27361. CombineAction.prototype._prepare = function () {
  27362. for (var index = 0; index < this.children.length; index++) {
  27363. this.children[index]._actionManager = this._actionManager;
  27364. this.children[index]._prepare();
  27365. }
  27366. };
  27367. CombineAction.prototype.execute = function (evt) {
  27368. for (var index = 0; index < this.children.length; index++) {
  27369. this.children[index].execute(evt);
  27370. }
  27371. };
  27372. return CombineAction;
  27373. })(BABYLON.Action);
  27374. BABYLON.CombineAction = CombineAction;
  27375. var ExecuteCodeAction = (function (_super) {
  27376. __extends(ExecuteCodeAction, _super);
  27377. function ExecuteCodeAction(triggerOptions, func, condition) {
  27378. _super.call(this, triggerOptions, condition);
  27379. this.func = func;
  27380. }
  27381. ExecuteCodeAction.prototype.execute = function (evt) {
  27382. this.func(evt);
  27383. };
  27384. return ExecuteCodeAction;
  27385. })(BABYLON.Action);
  27386. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27387. var SetParentAction = (function (_super) {
  27388. __extends(SetParentAction, _super);
  27389. function SetParentAction(triggerOptions, target, parent, condition) {
  27390. _super.call(this, triggerOptions, condition);
  27391. this._target = target;
  27392. this._parent = parent;
  27393. }
  27394. SetParentAction.prototype._prepare = function () {
  27395. };
  27396. SetParentAction.prototype.execute = function () {
  27397. if (this._target.parent === this._parent) {
  27398. return;
  27399. }
  27400. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27401. invertParentWorldMatrix.invert();
  27402. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27403. this._target.parent = this._parent;
  27404. };
  27405. return SetParentAction;
  27406. })(BABYLON.Action);
  27407. BABYLON.SetParentAction = SetParentAction;
  27408. var PlaySoundAction = (function (_super) {
  27409. __extends(PlaySoundAction, _super);
  27410. function PlaySoundAction(triggerOptions, sound, condition) {
  27411. _super.call(this, triggerOptions, condition);
  27412. this._sound = sound;
  27413. }
  27414. PlaySoundAction.prototype._prepare = function () {
  27415. };
  27416. PlaySoundAction.prototype.execute = function () {
  27417. if (this._sound !== undefined)
  27418. this._sound.play();
  27419. };
  27420. return PlaySoundAction;
  27421. })(BABYLON.Action);
  27422. BABYLON.PlaySoundAction = PlaySoundAction;
  27423. var StopSoundAction = (function (_super) {
  27424. __extends(StopSoundAction, _super);
  27425. function StopSoundAction(triggerOptions, sound, condition) {
  27426. _super.call(this, triggerOptions, condition);
  27427. this._sound = sound;
  27428. }
  27429. StopSoundAction.prototype._prepare = function () {
  27430. };
  27431. StopSoundAction.prototype.execute = function () {
  27432. if (this._sound !== undefined)
  27433. this._sound.stop();
  27434. };
  27435. return StopSoundAction;
  27436. })(BABYLON.Action);
  27437. BABYLON.StopSoundAction = StopSoundAction;
  27438. })(BABYLON || (BABYLON = {}));
  27439. //# sourceMappingURL=babylon.directActions.js.map
  27440. var __extends = (this && this.__extends) || function (d, b) {
  27441. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27442. function __() { this.constructor = d; }
  27443. __.prototype = b.prototype;
  27444. d.prototype = new __();
  27445. };
  27446. var BABYLON;
  27447. (function (BABYLON) {
  27448. var Geometry = (function () {
  27449. function Geometry(id, scene, vertexData, updatable, mesh) {
  27450. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27451. this._totalVertices = 0;
  27452. this._indices = [];
  27453. this._isDisposed = false;
  27454. this.id = id;
  27455. this._engine = scene.getEngine();
  27456. this._meshes = [];
  27457. this._scene = scene;
  27458. // vertexData
  27459. if (vertexData) {
  27460. this.setAllVerticesData(vertexData, updatable);
  27461. }
  27462. else {
  27463. this._totalVertices = 0;
  27464. this._indices = [];
  27465. }
  27466. // applyToMesh
  27467. if (mesh) {
  27468. this.applyToMesh(mesh);
  27469. mesh.computeWorldMatrix(true);
  27470. }
  27471. }
  27472. Geometry.prototype.getScene = function () {
  27473. return this._scene;
  27474. };
  27475. Geometry.prototype.getEngine = function () {
  27476. return this._engine;
  27477. };
  27478. Geometry.prototype.isReady = function () {
  27479. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27480. };
  27481. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27482. vertexData.applyToGeometry(this, updatable);
  27483. this.notifyUpdate();
  27484. };
  27485. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27486. this._vertexBuffers = this._vertexBuffers || {};
  27487. if (this._vertexBuffers[kind]) {
  27488. this._vertexBuffers[kind].dispose();
  27489. }
  27490. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27491. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27492. stride = this._vertexBuffers[kind].getStrideSize();
  27493. this._totalVertices = data.length / stride;
  27494. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27495. var meshes = this._meshes;
  27496. var numOfMeshes = meshes.length;
  27497. for (var index = 0; index < numOfMeshes; index++) {
  27498. var mesh = meshes[index];
  27499. mesh._resetPointsArrayCache();
  27500. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27501. mesh._createGlobalSubMesh();
  27502. mesh.computeWorldMatrix(true);
  27503. }
  27504. }
  27505. this.notifyUpdate(kind);
  27506. };
  27507. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27508. var vertexBuffer = this.getVertexBuffer(kind);
  27509. if (!vertexBuffer) {
  27510. return;
  27511. }
  27512. vertexBuffer.updateDirectly(data, offset);
  27513. this.notifyUpdate(kind);
  27514. };
  27515. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27516. var vertexBuffer = this.getVertexBuffer(kind);
  27517. if (!vertexBuffer) {
  27518. return;
  27519. }
  27520. vertexBuffer.update(data);
  27521. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27522. var extend;
  27523. var stride = vertexBuffer.getStrideSize();
  27524. this._totalVertices = data.length / stride;
  27525. if (updateExtends) {
  27526. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27527. }
  27528. var meshes = this._meshes;
  27529. var numOfMeshes = meshes.length;
  27530. for (var index = 0; index < numOfMeshes; index++) {
  27531. var mesh = meshes[index];
  27532. mesh._resetPointsArrayCache();
  27533. if (updateExtends) {
  27534. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27535. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27536. var subMesh = mesh.subMeshes[subIndex];
  27537. subMesh.refreshBoundingInfo();
  27538. }
  27539. }
  27540. }
  27541. }
  27542. this.notifyUpdate(kind);
  27543. };
  27544. Geometry.prototype.getTotalVertices = function () {
  27545. if (!this.isReady()) {
  27546. return 0;
  27547. }
  27548. return this._totalVertices;
  27549. };
  27550. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27551. var vertexBuffer = this.getVertexBuffer(kind);
  27552. if (!vertexBuffer) {
  27553. return null;
  27554. }
  27555. var orig = vertexBuffer.getData();
  27556. if (!copyWhenShared || this._meshes.length === 1) {
  27557. return orig;
  27558. }
  27559. else {
  27560. var len = orig.length;
  27561. var copy = [];
  27562. for (var i = 0; i < len; i++) {
  27563. copy.push(orig[i]);
  27564. }
  27565. return copy;
  27566. }
  27567. };
  27568. Geometry.prototype.getVertexBuffer = function (kind) {
  27569. if (!this.isReady()) {
  27570. return null;
  27571. }
  27572. return this._vertexBuffers[kind];
  27573. };
  27574. Geometry.prototype.getVertexBuffers = function () {
  27575. if (!this.isReady()) {
  27576. return null;
  27577. }
  27578. return this._vertexBuffers;
  27579. };
  27580. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27581. if (!this._vertexBuffers) {
  27582. if (this._delayInfo) {
  27583. return this._delayInfo.indexOf(kind) !== -1;
  27584. }
  27585. return false;
  27586. }
  27587. return this._vertexBuffers[kind] !== undefined;
  27588. };
  27589. Geometry.prototype.getVerticesDataKinds = function () {
  27590. var result = [];
  27591. if (!this._vertexBuffers && this._delayInfo) {
  27592. for (var kind in this._delayInfo) {
  27593. result.push(kind);
  27594. }
  27595. }
  27596. else {
  27597. for (kind in this._vertexBuffers) {
  27598. result.push(kind);
  27599. }
  27600. }
  27601. return result;
  27602. };
  27603. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27604. if (this._indexBuffer) {
  27605. this._engine._releaseBuffer(this._indexBuffer);
  27606. }
  27607. this._indices = indices;
  27608. if (this._meshes.length !== 0 && this._indices) {
  27609. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27610. }
  27611. if (totalVertices !== undefined) {
  27612. this._totalVertices = totalVertices;
  27613. }
  27614. var meshes = this._meshes;
  27615. var numOfMeshes = meshes.length;
  27616. for (var index = 0; index < numOfMeshes; index++) {
  27617. meshes[index]._createGlobalSubMesh();
  27618. }
  27619. this.notifyUpdate();
  27620. };
  27621. Geometry.prototype.getTotalIndices = function () {
  27622. if (!this.isReady()) {
  27623. return 0;
  27624. }
  27625. return this._indices.length;
  27626. };
  27627. Geometry.prototype.getIndices = function (copyWhenShared) {
  27628. if (!this.isReady()) {
  27629. return null;
  27630. }
  27631. var orig = this._indices;
  27632. if (!copyWhenShared || this._meshes.length === 1) {
  27633. return orig;
  27634. }
  27635. else {
  27636. var len = orig.length;
  27637. var copy = [];
  27638. for (var i = 0; i < len; i++) {
  27639. copy.push(orig[i]);
  27640. }
  27641. return copy;
  27642. }
  27643. };
  27644. Geometry.prototype.getIndexBuffer = function () {
  27645. if (!this.isReady()) {
  27646. return null;
  27647. }
  27648. return this._indexBuffer;
  27649. };
  27650. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27651. var meshes = this._meshes;
  27652. var index = meshes.indexOf(mesh);
  27653. if (index === -1) {
  27654. return;
  27655. }
  27656. for (var kind in this._vertexBuffers) {
  27657. this._vertexBuffers[kind].dispose();
  27658. }
  27659. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27660. this._indexBuffer = null;
  27661. }
  27662. meshes.splice(index, 1);
  27663. mesh._geometry = null;
  27664. if (meshes.length === 0 && shouldDispose) {
  27665. this.dispose();
  27666. }
  27667. };
  27668. Geometry.prototype.applyToMesh = function (mesh) {
  27669. if (mesh._geometry === this) {
  27670. return;
  27671. }
  27672. var previousGeometry = mesh._geometry;
  27673. if (previousGeometry) {
  27674. previousGeometry.releaseForMesh(mesh);
  27675. }
  27676. var meshes = this._meshes;
  27677. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27678. mesh._geometry = this;
  27679. this._scene.pushGeometry(this);
  27680. meshes.push(mesh);
  27681. if (this.isReady()) {
  27682. this._applyToMesh(mesh);
  27683. }
  27684. else {
  27685. mesh._boundingInfo = this._boundingInfo;
  27686. }
  27687. };
  27688. Geometry.prototype._applyToMesh = function (mesh) {
  27689. var numOfMeshes = this._meshes.length;
  27690. // vertexBuffers
  27691. for (var kind in this._vertexBuffers) {
  27692. if (numOfMeshes === 1) {
  27693. this._vertexBuffers[kind].create();
  27694. }
  27695. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27696. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27697. mesh._resetPointsArrayCache();
  27698. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27699. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27700. mesh._createGlobalSubMesh();
  27701. //bounding info was just created again, world matrix should be applied again.
  27702. mesh._updateBoundingInfo();
  27703. }
  27704. }
  27705. // indexBuffer
  27706. if (numOfMeshes === 1 && this._indices) {
  27707. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27708. }
  27709. if (this._indexBuffer) {
  27710. this._indexBuffer.references = numOfMeshes;
  27711. }
  27712. };
  27713. Geometry.prototype.notifyUpdate = function (kind) {
  27714. if (this.onGeometryUpdated) {
  27715. this.onGeometryUpdated(this, kind);
  27716. }
  27717. };
  27718. Geometry.prototype.load = function (scene, onLoaded) {
  27719. var _this = this;
  27720. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27721. return;
  27722. }
  27723. if (this.isReady()) {
  27724. if (onLoaded) {
  27725. onLoaded();
  27726. }
  27727. return;
  27728. }
  27729. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27730. scene._addPendingData(this);
  27731. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27732. _this._delayLoadingFunction(JSON.parse(data), _this);
  27733. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27734. _this._delayInfo = [];
  27735. scene._removePendingData(_this);
  27736. var meshes = _this._meshes;
  27737. var numOfMeshes = meshes.length;
  27738. for (var index = 0; index < numOfMeshes; index++) {
  27739. _this._applyToMesh(meshes[index]);
  27740. }
  27741. if (onLoaded) {
  27742. onLoaded();
  27743. }
  27744. }, function () { }, scene.database);
  27745. };
  27746. Geometry.prototype.isDisposed = function () {
  27747. return this._isDisposed;
  27748. };
  27749. Geometry.prototype.dispose = function () {
  27750. var meshes = this._meshes;
  27751. var numOfMeshes = meshes.length;
  27752. var index;
  27753. for (index = 0; index < numOfMeshes; index++) {
  27754. this.releaseForMesh(meshes[index]);
  27755. }
  27756. this._meshes = [];
  27757. for (var kind in this._vertexBuffers) {
  27758. this._vertexBuffers[kind].dispose();
  27759. }
  27760. this._vertexBuffers = [];
  27761. this._totalVertices = 0;
  27762. if (this._indexBuffer) {
  27763. this._engine._releaseBuffer(this._indexBuffer);
  27764. }
  27765. this._indexBuffer = null;
  27766. this._indices = [];
  27767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27768. this.delayLoadingFile = null;
  27769. this._delayLoadingFunction = null;
  27770. this._delayInfo = [];
  27771. this._boundingInfo = null; // todo: .dispose()
  27772. this._scene.removeGeometry(this);
  27773. this._isDisposed = true;
  27774. };
  27775. Geometry.prototype.copy = function (id) {
  27776. var vertexData = new BABYLON.VertexData();
  27777. vertexData.indices = [];
  27778. var indices = this.getIndices();
  27779. for (var index = 0; index < indices.length; index++) {
  27780. vertexData.indices.push(indices[index]);
  27781. }
  27782. var updatable = false;
  27783. var stopChecking = false;
  27784. for (var kind in this._vertexBuffers) {
  27785. // using slice() to make a copy of the array and not just reference it
  27786. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27787. if (!stopChecking) {
  27788. updatable = this.getVertexBuffer(kind).isUpdatable();
  27789. stopChecking = !updatable;
  27790. }
  27791. }
  27792. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27793. geometry.delayLoadState = this.delayLoadState;
  27794. geometry.delayLoadingFile = this.delayLoadingFile;
  27795. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27796. for (kind in this._delayInfo) {
  27797. geometry._delayInfo = geometry._delayInfo || [];
  27798. geometry._delayInfo.push(kind);
  27799. }
  27800. // Bounding info
  27801. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27802. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27803. return geometry;
  27804. };
  27805. // Statics
  27806. Geometry.ExtractFromMesh = function (mesh, id) {
  27807. var geometry = mesh._geometry;
  27808. if (!geometry) {
  27809. return null;
  27810. }
  27811. return geometry.copy(id);
  27812. };
  27813. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27814. // be aware Math.random() could cause collisions
  27815. Geometry.RandomId = function () {
  27816. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27817. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27818. return v.toString(16);
  27819. });
  27820. };
  27821. return Geometry;
  27822. })();
  27823. BABYLON.Geometry = Geometry;
  27824. /////// Primitives //////////////////////////////////////////////
  27825. var Geometry;
  27826. (function (Geometry) {
  27827. var Primitives;
  27828. (function (Primitives) {
  27829. /// Abstract class
  27830. var _Primitive = (function (_super) {
  27831. __extends(_Primitive, _super);
  27832. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27833. this._beingRegenerated = true;
  27834. this._canBeRegenerated = canBeRegenerated;
  27835. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27836. this._beingRegenerated = false;
  27837. }
  27838. _Primitive.prototype.canBeRegenerated = function () {
  27839. return this._canBeRegenerated;
  27840. };
  27841. _Primitive.prototype.regenerate = function () {
  27842. if (!this._canBeRegenerated) {
  27843. return;
  27844. }
  27845. this._beingRegenerated = true;
  27846. this.setAllVerticesData(this._regenerateVertexData(), false);
  27847. this._beingRegenerated = false;
  27848. };
  27849. _Primitive.prototype.asNewGeometry = function (id) {
  27850. return _super.prototype.copy.call(this, id);
  27851. };
  27852. // overrides
  27853. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27854. if (!this._beingRegenerated) {
  27855. return;
  27856. }
  27857. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27858. };
  27859. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27860. if (!this._beingRegenerated) {
  27861. return;
  27862. }
  27863. _super.prototype.setVerticesData.call(this, kind, data, false);
  27864. };
  27865. // to override
  27866. // protected
  27867. _Primitive.prototype._regenerateVertexData = function () {
  27868. throw new Error("Abstract method");
  27869. };
  27870. _Primitive.prototype.copy = function (id) {
  27871. throw new Error("Must be overriden in sub-classes.");
  27872. };
  27873. return _Primitive;
  27874. })(Geometry);
  27875. Primitives._Primitive = _Primitive;
  27876. var Ribbon = (function (_super) {
  27877. __extends(Ribbon, _super);
  27878. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27879. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27880. this.pathArray = pathArray;
  27881. this.closeArray = closeArray;
  27882. this.closePath = closePath;
  27883. this.offset = offset;
  27884. this.side = side;
  27885. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27886. }
  27887. Ribbon.prototype._regenerateVertexData = function () {
  27888. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27889. };
  27890. Ribbon.prototype.copy = function (id) {
  27891. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27892. };
  27893. return Ribbon;
  27894. })(_Primitive);
  27895. Primitives.Ribbon = Ribbon;
  27896. var Box = (function (_super) {
  27897. __extends(Box, _super);
  27898. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27899. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27900. this.size = size;
  27901. this.side = side;
  27902. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27903. }
  27904. Box.prototype._regenerateVertexData = function () {
  27905. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27906. };
  27907. Box.prototype.copy = function (id) {
  27908. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27909. };
  27910. return Box;
  27911. })(_Primitive);
  27912. Primitives.Box = Box;
  27913. var Sphere = (function (_super) {
  27914. __extends(Sphere, _super);
  27915. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27916. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27917. this.segments = segments;
  27918. this.diameter = diameter;
  27919. this.side = side;
  27920. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27921. }
  27922. Sphere.prototype._regenerateVertexData = function () {
  27923. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27924. };
  27925. Sphere.prototype.copy = function (id) {
  27926. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27927. };
  27928. return Sphere;
  27929. })(_Primitive);
  27930. Primitives.Sphere = Sphere;
  27931. var Cylinder = (function (_super) {
  27932. __extends(Cylinder, _super);
  27933. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27934. if (subdivisions === void 0) { subdivisions = 1; }
  27935. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27936. this.height = height;
  27937. this.diameterTop = diameterTop;
  27938. this.diameterBottom = diameterBottom;
  27939. this.tessellation = tessellation;
  27940. this.subdivisions = subdivisions;
  27941. this.side = side;
  27942. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27943. }
  27944. Cylinder.prototype._regenerateVertexData = function () {
  27945. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27946. };
  27947. Cylinder.prototype.copy = function (id) {
  27948. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27949. };
  27950. return Cylinder;
  27951. })(_Primitive);
  27952. Primitives.Cylinder = Cylinder;
  27953. var Torus = (function (_super) {
  27954. __extends(Torus, _super);
  27955. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27956. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27957. this.diameter = diameter;
  27958. this.thickness = thickness;
  27959. this.tessellation = tessellation;
  27960. this.side = side;
  27961. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27962. }
  27963. Torus.prototype._regenerateVertexData = function () {
  27964. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27965. };
  27966. Torus.prototype.copy = function (id) {
  27967. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27968. };
  27969. return Torus;
  27970. })(_Primitive);
  27971. Primitives.Torus = Torus;
  27972. var Ground = (function (_super) {
  27973. __extends(Ground, _super);
  27974. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27975. this.width = width;
  27976. this.height = height;
  27977. this.subdivisions = subdivisions;
  27978. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27979. }
  27980. Ground.prototype._regenerateVertexData = function () {
  27981. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27982. };
  27983. Ground.prototype.copy = function (id) {
  27984. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27985. };
  27986. return Ground;
  27987. })(_Primitive);
  27988. Primitives.Ground = Ground;
  27989. var TiledGround = (function (_super) {
  27990. __extends(TiledGround, _super);
  27991. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27992. this.xmin = xmin;
  27993. this.zmin = zmin;
  27994. this.xmax = xmax;
  27995. this.zmax = zmax;
  27996. this.subdivisions = subdivisions;
  27997. this.precision = precision;
  27998. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27999. }
  28000. TiledGround.prototype._regenerateVertexData = function () {
  28001. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  28002. };
  28003. TiledGround.prototype.copy = function (id) {
  28004. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28005. };
  28006. return TiledGround;
  28007. })(_Primitive);
  28008. Primitives.TiledGround = TiledGround;
  28009. var Plane = (function (_super) {
  28010. __extends(Plane, _super);
  28011. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28012. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28013. this.size = size;
  28014. this.side = side;
  28015. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28016. }
  28017. Plane.prototype._regenerateVertexData = function () {
  28018. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  28019. };
  28020. Plane.prototype.copy = function (id) {
  28021. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28022. };
  28023. return Plane;
  28024. })(_Primitive);
  28025. Primitives.Plane = Plane;
  28026. var TorusKnot = (function (_super) {
  28027. __extends(TorusKnot, _super);
  28028. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28029. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28030. this.radius = radius;
  28031. this.tube = tube;
  28032. this.radialSegments = radialSegments;
  28033. this.tubularSegments = tubularSegments;
  28034. this.p = p;
  28035. this.q = q;
  28036. this.side = side;
  28037. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28038. }
  28039. TorusKnot.prototype._regenerateVertexData = function () {
  28040. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  28041. };
  28042. TorusKnot.prototype.copy = function (id) {
  28043. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28044. };
  28045. return TorusKnot;
  28046. })(_Primitive);
  28047. Primitives.TorusKnot = TorusKnot;
  28048. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28049. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28050. })(BABYLON || (BABYLON = {}));
  28051. //# sourceMappingURL=babylon.geometry.js.map
  28052. var __extends = (this && this.__extends) || function (d, b) {
  28053. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28054. function __() { this.constructor = d; }
  28055. __.prototype = b.prototype;
  28056. d.prototype = new __();
  28057. };
  28058. var BABYLON;
  28059. (function (BABYLON) {
  28060. var GroundMesh = (function (_super) {
  28061. __extends(GroundMesh, _super);
  28062. function GroundMesh(name, scene) {
  28063. _super.call(this, name, scene);
  28064. this.generateOctree = false;
  28065. this._worldInverse = new BABYLON.Matrix();
  28066. }
  28067. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28068. get: function () {
  28069. return this._subdivisions;
  28070. },
  28071. enumerable: true,
  28072. configurable: true
  28073. });
  28074. GroundMesh.prototype.optimize = function (chunksCount) {
  28075. this.subdivide(this._subdivisions);
  28076. this.createOrUpdateSubmeshesOctree(32);
  28077. };
  28078. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28079. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  28080. this.getWorldMatrix().invertToRef(this._worldInverse);
  28081. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  28082. var pickInfo = this.intersects(ray);
  28083. if (pickInfo.hit) {
  28084. return pickInfo.pickedPoint.y;
  28085. }
  28086. return 0;
  28087. };
  28088. return GroundMesh;
  28089. })(BABYLON.Mesh);
  28090. BABYLON.GroundMesh = GroundMesh;
  28091. })(BABYLON || (BABYLON = {}));
  28092. //# sourceMappingURL=babylon.groundMesh.js.map
  28093. var __extends = (this && this.__extends) || function (d, b) {
  28094. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28095. function __() { this.constructor = d; }
  28096. __.prototype = b.prototype;
  28097. d.prototype = new __();
  28098. };
  28099. var BABYLON;
  28100. (function (BABYLON) {
  28101. var LinesMesh = (function (_super) {
  28102. __extends(LinesMesh, _super);
  28103. function LinesMesh(name, scene, updatable) {
  28104. if (updatable === void 0) { updatable = false; }
  28105. _super.call(this, name, scene);
  28106. this.color = new BABYLON.Color3(1, 1, 1);
  28107. this.alpha = 1;
  28108. this._indices = new Array();
  28109. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28110. attributes: ["position"],
  28111. uniforms: ["worldViewProjection", "color"],
  28112. needAlphaBlending: true
  28113. });
  28114. }
  28115. Object.defineProperty(LinesMesh.prototype, "material", {
  28116. get: function () {
  28117. return this._colorShader;
  28118. },
  28119. enumerable: true,
  28120. configurable: true
  28121. });
  28122. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28123. get: function () {
  28124. return false;
  28125. },
  28126. enumerable: true,
  28127. configurable: true
  28128. });
  28129. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28130. get: function () {
  28131. return false;
  28132. },
  28133. enumerable: true,
  28134. configurable: true
  28135. });
  28136. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28137. var engine = this.getScene().getEngine();
  28138. var indexToBind = this._geometry.getIndexBuffer();
  28139. // VBOs
  28140. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28141. // Color
  28142. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28143. };
  28144. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28145. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28146. return;
  28147. }
  28148. var engine = this.getScene().getEngine();
  28149. // Draw order
  28150. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28151. };
  28152. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28153. return null;
  28154. };
  28155. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28156. this._colorShader.dispose();
  28157. _super.prototype.dispose.call(this, doNotRecurse);
  28158. };
  28159. return LinesMesh;
  28160. })(BABYLON.Mesh);
  28161. BABYLON.LinesMesh = LinesMesh;
  28162. })(BABYLON || (BABYLON = {}));
  28163. //# sourceMappingURL=babylon.linesMesh.js.map
  28164. var BABYLON;
  28165. (function (BABYLON) {
  28166. var OutlineRenderer = (function () {
  28167. function OutlineRenderer(scene) {
  28168. this._scene = scene;
  28169. }
  28170. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  28171. var _this = this;
  28172. if (useOverlay === void 0) { useOverlay = false; }
  28173. var scene = this._scene;
  28174. var engine = this._scene.getEngine();
  28175. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28176. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  28177. return;
  28178. }
  28179. var mesh = subMesh.getRenderingMesh();
  28180. var material = subMesh.getMaterial();
  28181. engine.enableEffect(this._effect);
  28182. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  28183. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  28184. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28185. // Bones
  28186. if (mesh.useBones) {
  28187. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28188. }
  28189. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  28190. // Alpha test
  28191. if (material && material.needAlphaTesting()) {
  28192. var alphaTexture = material.getAlphaTestTexture();
  28193. this._effect.setTexture("diffuseSampler", alphaTexture);
  28194. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28195. }
  28196. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  28197. };
  28198. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  28199. var defines = [];
  28200. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  28201. var mesh = subMesh.getMesh();
  28202. var material = subMesh.getMaterial();
  28203. // Alpha test
  28204. if (material && material.needAlphaTesting()) {
  28205. defines.push("#define ALPHATEST");
  28206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28207. attribs.push(BABYLON.VertexBuffer.UVKind);
  28208. defines.push("#define UV1");
  28209. }
  28210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28211. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28212. defines.push("#define UV2");
  28213. }
  28214. }
  28215. // Bones
  28216. if (mesh.useBones) {
  28217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28219. defines.push("#define BONES");
  28220. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28221. }
  28222. // Instances
  28223. if (useInstances) {
  28224. defines.push("#define INSTANCES");
  28225. attribs.push("world0");
  28226. attribs.push("world1");
  28227. attribs.push("world2");
  28228. attribs.push("world3");
  28229. }
  28230. // Get correct effect
  28231. var join = defines.join("\n");
  28232. if (this._cachedDefines !== join) {
  28233. this._cachedDefines = join;
  28234. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  28235. }
  28236. return this._effect.isReady();
  28237. };
  28238. return OutlineRenderer;
  28239. })();
  28240. BABYLON.OutlineRenderer = OutlineRenderer;
  28241. })(BABYLON || (BABYLON = {}));
  28242. //# sourceMappingURL=babylon.outlineRenderer.js.map
  28243. var BABYLON;
  28244. (function (BABYLON) {
  28245. var MeshAssetTask = (function () {
  28246. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  28247. this.name = name;
  28248. this.meshesNames = meshesNames;
  28249. this.rootUrl = rootUrl;
  28250. this.sceneFilename = sceneFilename;
  28251. this.isCompleted = false;
  28252. }
  28253. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28254. var _this = this;
  28255. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  28256. _this.loadedMeshes = meshes;
  28257. _this.loadedParticleSystems = particleSystems;
  28258. _this.loadedSkeletons = skeletons;
  28259. _this.isCompleted = true;
  28260. if (_this.onSuccess) {
  28261. _this.onSuccess(_this);
  28262. }
  28263. onSuccess();
  28264. }, null, function () {
  28265. if (_this.onError) {
  28266. _this.onError(_this);
  28267. }
  28268. onError();
  28269. });
  28270. };
  28271. return MeshAssetTask;
  28272. })();
  28273. BABYLON.MeshAssetTask = MeshAssetTask;
  28274. var TextFileAssetTask = (function () {
  28275. function TextFileAssetTask(name, url) {
  28276. this.name = name;
  28277. this.url = url;
  28278. this.isCompleted = false;
  28279. }
  28280. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28281. var _this = this;
  28282. BABYLON.Tools.LoadFile(this.url, function (data) {
  28283. _this.text = data;
  28284. _this.isCompleted = true;
  28285. if (_this.onSuccess) {
  28286. _this.onSuccess(_this);
  28287. }
  28288. onSuccess();
  28289. }, null, scene.database, false, function () {
  28290. if (_this.onError) {
  28291. _this.onError(_this);
  28292. }
  28293. onError();
  28294. });
  28295. };
  28296. return TextFileAssetTask;
  28297. })();
  28298. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28299. var BinaryFileAssetTask = (function () {
  28300. function BinaryFileAssetTask(name, url) {
  28301. this.name = name;
  28302. this.url = url;
  28303. this.isCompleted = false;
  28304. }
  28305. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28306. var _this = this;
  28307. BABYLON.Tools.LoadFile(this.url, function (data) {
  28308. _this.data = data;
  28309. _this.isCompleted = true;
  28310. if (_this.onSuccess) {
  28311. _this.onSuccess(_this);
  28312. }
  28313. onSuccess();
  28314. }, null, scene.database, true, function () {
  28315. if (_this.onError) {
  28316. _this.onError(_this);
  28317. }
  28318. onError();
  28319. });
  28320. };
  28321. return BinaryFileAssetTask;
  28322. })();
  28323. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28324. var ImageAssetTask = (function () {
  28325. function ImageAssetTask(name, url) {
  28326. this.name = name;
  28327. this.url = url;
  28328. this.isCompleted = false;
  28329. }
  28330. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28331. var _this = this;
  28332. var img = new Image();
  28333. img.onload = function () {
  28334. _this.image = img;
  28335. _this.isCompleted = true;
  28336. if (_this.onSuccess) {
  28337. _this.onSuccess(_this);
  28338. }
  28339. onSuccess();
  28340. };
  28341. img.onerror = function () {
  28342. if (_this.onError) {
  28343. _this.onError(_this);
  28344. }
  28345. onError();
  28346. };
  28347. img.src = this.url;
  28348. };
  28349. return ImageAssetTask;
  28350. })();
  28351. BABYLON.ImageAssetTask = ImageAssetTask;
  28352. var TextureAssetTask = (function () {
  28353. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28355. this.name = name;
  28356. this.url = url;
  28357. this.noMipmap = noMipmap;
  28358. this.invertY = invertY;
  28359. this.samplingMode = samplingMode;
  28360. this.isCompleted = false;
  28361. }
  28362. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28363. var _this = this;
  28364. var onload = function () {
  28365. _this.isCompleted = true;
  28366. if (_this.onSuccess) {
  28367. _this.onSuccess(_this);
  28368. }
  28369. onSuccess();
  28370. };
  28371. var onerror = function () {
  28372. if (_this.onError) {
  28373. _this.onError(_this);
  28374. }
  28375. onError();
  28376. };
  28377. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28378. };
  28379. return TextureAssetTask;
  28380. })();
  28381. BABYLON.TextureAssetTask = TextureAssetTask;
  28382. var AssetsManager = (function () {
  28383. function AssetsManager(scene) {
  28384. this._tasks = new Array();
  28385. this._waitingTasksCount = 0;
  28386. this.useDefaultLoadingScreen = true;
  28387. this._scene = scene;
  28388. }
  28389. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28390. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28391. this._tasks.push(task);
  28392. return task;
  28393. };
  28394. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28395. var task = new TextFileAssetTask(taskName, url);
  28396. this._tasks.push(task);
  28397. return task;
  28398. };
  28399. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28400. var task = new BinaryFileAssetTask(taskName, url);
  28401. this._tasks.push(task);
  28402. return task;
  28403. };
  28404. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28405. var task = new ImageAssetTask(taskName, url);
  28406. this._tasks.push(task);
  28407. return task;
  28408. };
  28409. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28411. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28412. this._tasks.push(task);
  28413. return task;
  28414. };
  28415. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28416. this._waitingTasksCount--;
  28417. if (this._waitingTasksCount === 0) {
  28418. if (this.onFinish) {
  28419. this.onFinish(this._tasks);
  28420. }
  28421. this._scene.getEngine().hideLoadingUI();
  28422. }
  28423. };
  28424. AssetsManager.prototype._runTask = function (task) {
  28425. var _this = this;
  28426. task.run(this._scene, function () {
  28427. if (_this.onTaskSuccess) {
  28428. _this.onTaskSuccess(task);
  28429. }
  28430. _this._decreaseWaitingTasksCount();
  28431. }, function () {
  28432. if (_this.onTaskError) {
  28433. _this.onTaskError(task);
  28434. }
  28435. _this._decreaseWaitingTasksCount();
  28436. });
  28437. };
  28438. AssetsManager.prototype.reset = function () {
  28439. this._tasks = new Array();
  28440. return this;
  28441. };
  28442. AssetsManager.prototype.load = function () {
  28443. this._waitingTasksCount = this._tasks.length;
  28444. if (this._waitingTasksCount === 0) {
  28445. if (this.onFinish) {
  28446. this.onFinish(this._tasks);
  28447. }
  28448. return this;
  28449. }
  28450. if (this.useDefaultLoadingScreen) {
  28451. this._scene.getEngine().displayLoadingUI();
  28452. }
  28453. for (var index = 0; index < this._tasks.length; index++) {
  28454. var task = this._tasks[index];
  28455. this._runTask(task);
  28456. }
  28457. return this;
  28458. };
  28459. return AssetsManager;
  28460. })();
  28461. BABYLON.AssetsManager = AssetsManager;
  28462. })(BABYLON || (BABYLON = {}));
  28463. //# sourceMappingURL=babylon.assetsManager.js.map
  28464. var __extends = (this && this.__extends) || function (d, b) {
  28465. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28466. function __() { this.constructor = d; }
  28467. __.prototype = b.prototype;
  28468. d.prototype = new __();
  28469. };
  28470. var BABYLON;
  28471. (function (BABYLON) {
  28472. var VRDeviceOrientationFreeCamera = (function (_super) {
  28473. __extends(VRDeviceOrientationFreeCamera, _super);
  28474. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  28475. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28476. _super.call(this, name, position, scene);
  28477. this._alpha = 0;
  28478. this._beta = 0;
  28479. this._gamma = 0;
  28480. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28481. metrics.compensateDistorsion = compensateDistorsion;
  28482. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28483. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28484. }
  28485. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28486. this._alpha = +evt.alpha | 0;
  28487. this._beta = +evt.beta | 0;
  28488. this._gamma = +evt.gamma | 0;
  28489. if (this._gamma < 0) {
  28490. this._gamma = 90 + this._gamma;
  28491. }
  28492. else {
  28493. // Incline it in the correct angle.
  28494. this._gamma = 270 - this._gamma;
  28495. }
  28496. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28497. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28498. this.rotation.z = this._beta / 180.0 * Math.PI;
  28499. };
  28500. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28501. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28502. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28503. };
  28504. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28505. _super.prototype.detachControl.call(this, element);
  28506. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28507. };
  28508. return VRDeviceOrientationFreeCamera;
  28509. })(BABYLON.FreeCamera);
  28510. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28511. })(BABYLON || (BABYLON = {}));
  28512. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28513. var __extends = (this && this.__extends) || function (d, b) {
  28514. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28515. function __() { this.constructor = d; }
  28516. __.prototype = b.prototype;
  28517. d.prototype = new __();
  28518. };
  28519. var BABYLON;
  28520. (function (BABYLON) {
  28521. var WebVRFreeCamera = (function (_super) {
  28522. __extends(WebVRFreeCamera, _super);
  28523. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  28524. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28525. _super.call(this, name, position, scene);
  28526. this._hmdDevice = null;
  28527. this._sensorDevice = null;
  28528. this._cacheState = null;
  28529. this._cacheQuaternion = new BABYLON.Quaternion();
  28530. this._cacheRotation = BABYLON.Vector3.Zero();
  28531. this._vrEnabled = false;
  28532. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28533. metrics.compensateDistorsion = compensateDistorsion;
  28534. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28535. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28536. }
  28537. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28538. var size = devices.length;
  28539. var i = 0;
  28540. // Reset devices.
  28541. this._sensorDevice = null;
  28542. this._hmdDevice = null;
  28543. // Search for a HmdDevice.
  28544. while (i < size && this._hmdDevice === null) {
  28545. if (devices[i] instanceof HMDVRDevice) {
  28546. this._hmdDevice = devices[i];
  28547. }
  28548. i++;
  28549. }
  28550. i = 0;
  28551. while (i < size && this._sensorDevice === null) {
  28552. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28553. this._sensorDevice = devices[i];
  28554. }
  28555. i++;
  28556. }
  28557. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28558. };
  28559. WebVRFreeCamera.prototype._checkInputs = function () {
  28560. if (this._vrEnabled) {
  28561. this._cacheState = this._sensorDevice.getState();
  28562. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28563. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28564. this.rotation.x = -this._cacheRotation.z;
  28565. this.rotation.y = -this._cacheRotation.y;
  28566. this.rotation.z = this._cacheRotation.x;
  28567. }
  28568. _super.prototype._checkInputs.call(this);
  28569. };
  28570. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28571. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28572. if (navigator.getVRDevices) {
  28573. navigator.getVRDevices().then(this._getWebVRDevices);
  28574. }
  28575. else if (navigator.mozGetVRDevices) {
  28576. navigator.mozGetVRDevices(this._getWebVRDevices);
  28577. }
  28578. };
  28579. WebVRFreeCamera.prototype.detachControl = function (element) {
  28580. _super.prototype.detachControl.call(this, element);
  28581. this._vrEnabled = false;
  28582. };
  28583. return WebVRFreeCamera;
  28584. })(BABYLON.FreeCamera);
  28585. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28586. })(BABYLON || (BABYLON = {}));
  28587. //# sourceMappingURL=babylon.webVRCamera.js.map
  28588. var __extends = (this && this.__extends) || function (d, b) {
  28589. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28590. function __() { this.constructor = d; }
  28591. __.prototype = b.prototype;
  28592. d.prototype = new __();
  28593. };
  28594. var BABYLON;
  28595. (function (BABYLON) {
  28596. // Standard optimizations
  28597. var SceneOptimization = (function () {
  28598. function SceneOptimization(priority) {
  28599. if (priority === void 0) { priority = 0; }
  28600. this.priority = priority;
  28601. this.apply = function (scene) {
  28602. return true; // Return true if everything that can be done was applied
  28603. };
  28604. }
  28605. return SceneOptimization;
  28606. })();
  28607. BABYLON.SceneOptimization = SceneOptimization;
  28608. var TextureOptimization = (function (_super) {
  28609. __extends(TextureOptimization, _super);
  28610. function TextureOptimization(priority, maximumSize) {
  28611. var _this = this;
  28612. if (priority === void 0) { priority = 0; }
  28613. if (maximumSize === void 0) { maximumSize = 1024; }
  28614. _super.call(this, priority);
  28615. this.priority = priority;
  28616. this.maximumSize = maximumSize;
  28617. this.apply = function (scene) {
  28618. var allDone = true;
  28619. for (var index = 0; index < scene.textures.length; index++) {
  28620. var texture = scene.textures[index];
  28621. if (!texture.canRescale) {
  28622. continue;
  28623. }
  28624. var currentSize = texture.getSize();
  28625. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28626. if (maxDimension > _this.maximumSize) {
  28627. texture.scale(0.5);
  28628. allDone = false;
  28629. }
  28630. }
  28631. return allDone;
  28632. };
  28633. }
  28634. return TextureOptimization;
  28635. })(SceneOptimization);
  28636. BABYLON.TextureOptimization = TextureOptimization;
  28637. var HardwareScalingOptimization = (function (_super) {
  28638. __extends(HardwareScalingOptimization, _super);
  28639. function HardwareScalingOptimization(priority, maximumScale) {
  28640. var _this = this;
  28641. if (priority === void 0) { priority = 0; }
  28642. if (maximumScale === void 0) { maximumScale = 2; }
  28643. _super.call(this, priority);
  28644. this.priority = priority;
  28645. this.maximumScale = maximumScale;
  28646. this._currentScale = 1;
  28647. this.apply = function (scene) {
  28648. _this._currentScale++;
  28649. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28650. return _this._currentScale >= _this.maximumScale;
  28651. };
  28652. }
  28653. return HardwareScalingOptimization;
  28654. })(SceneOptimization);
  28655. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28656. var ShadowsOptimization = (function (_super) {
  28657. __extends(ShadowsOptimization, _super);
  28658. function ShadowsOptimization() {
  28659. _super.apply(this, arguments);
  28660. this.apply = function (scene) {
  28661. scene.shadowsEnabled = false;
  28662. return true;
  28663. };
  28664. }
  28665. return ShadowsOptimization;
  28666. })(SceneOptimization);
  28667. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28668. var PostProcessesOptimization = (function (_super) {
  28669. __extends(PostProcessesOptimization, _super);
  28670. function PostProcessesOptimization() {
  28671. _super.apply(this, arguments);
  28672. this.apply = function (scene) {
  28673. scene.postProcessesEnabled = false;
  28674. return true;
  28675. };
  28676. }
  28677. return PostProcessesOptimization;
  28678. })(SceneOptimization);
  28679. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28680. var LensFlaresOptimization = (function (_super) {
  28681. __extends(LensFlaresOptimization, _super);
  28682. function LensFlaresOptimization() {
  28683. _super.apply(this, arguments);
  28684. this.apply = function (scene) {
  28685. scene.lensFlaresEnabled = false;
  28686. return true;
  28687. };
  28688. }
  28689. return LensFlaresOptimization;
  28690. })(SceneOptimization);
  28691. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28692. var ParticlesOptimization = (function (_super) {
  28693. __extends(ParticlesOptimization, _super);
  28694. function ParticlesOptimization() {
  28695. _super.apply(this, arguments);
  28696. this.apply = function (scene) {
  28697. scene.particlesEnabled = false;
  28698. return true;
  28699. };
  28700. }
  28701. return ParticlesOptimization;
  28702. })(SceneOptimization);
  28703. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28704. var RenderTargetsOptimization = (function (_super) {
  28705. __extends(RenderTargetsOptimization, _super);
  28706. function RenderTargetsOptimization() {
  28707. _super.apply(this, arguments);
  28708. this.apply = function (scene) {
  28709. scene.renderTargetsEnabled = false;
  28710. return true;
  28711. };
  28712. }
  28713. return RenderTargetsOptimization;
  28714. })(SceneOptimization);
  28715. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28716. var MergeMeshesOptimization = (function (_super) {
  28717. __extends(MergeMeshesOptimization, _super);
  28718. function MergeMeshesOptimization() {
  28719. var _this = this;
  28720. _super.apply(this, arguments);
  28721. this._canBeMerged = function (abstractMesh) {
  28722. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28723. return false;
  28724. }
  28725. var mesh = abstractMesh;
  28726. if (!mesh.isVisible || !mesh.isEnabled()) {
  28727. return false;
  28728. }
  28729. if (mesh.instances.length > 0) {
  28730. return false;
  28731. }
  28732. if (mesh.skeleton || mesh.hasLODLevels) {
  28733. return false;
  28734. }
  28735. return true;
  28736. };
  28737. this.apply = function (scene) {
  28738. var globalPool = scene.meshes.slice(0);
  28739. var globalLength = globalPool.length;
  28740. for (var index = 0; index < globalLength; index++) {
  28741. var currentPool = new Array();
  28742. var current = globalPool[index];
  28743. // Checks
  28744. if (!_this._canBeMerged(current)) {
  28745. continue;
  28746. }
  28747. currentPool.push(current);
  28748. // Find compatible meshes
  28749. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28750. var otherMesh = globalPool[subIndex];
  28751. if (!_this._canBeMerged(otherMesh)) {
  28752. continue;
  28753. }
  28754. if (otherMesh.material !== current.material) {
  28755. continue;
  28756. }
  28757. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28758. continue;
  28759. }
  28760. currentPool.push(otherMesh);
  28761. globalLength--;
  28762. globalPool.splice(subIndex, 1);
  28763. subIndex--;
  28764. }
  28765. if (currentPool.length < 2) {
  28766. continue;
  28767. }
  28768. // Merge meshes
  28769. BABYLON.Mesh.MergeMeshes(currentPool);
  28770. }
  28771. return true;
  28772. };
  28773. }
  28774. return MergeMeshesOptimization;
  28775. })(SceneOptimization);
  28776. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28777. // Options
  28778. var SceneOptimizerOptions = (function () {
  28779. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28780. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28781. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28782. this.targetFrameRate = targetFrameRate;
  28783. this.trackerDuration = trackerDuration;
  28784. this.optimizations = new Array();
  28785. }
  28786. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28787. var result = new SceneOptimizerOptions(targetFrameRate);
  28788. var priority = 0;
  28789. result.optimizations.push(new MergeMeshesOptimization(priority));
  28790. result.optimizations.push(new ShadowsOptimization(priority));
  28791. result.optimizations.push(new LensFlaresOptimization(priority));
  28792. // Next priority
  28793. priority++;
  28794. result.optimizations.push(new PostProcessesOptimization(priority));
  28795. result.optimizations.push(new ParticlesOptimization(priority));
  28796. // Next priority
  28797. priority++;
  28798. result.optimizations.push(new TextureOptimization(priority, 1024));
  28799. return result;
  28800. };
  28801. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28802. var result = new SceneOptimizerOptions(targetFrameRate);
  28803. var priority = 0;
  28804. result.optimizations.push(new MergeMeshesOptimization(priority));
  28805. result.optimizations.push(new ShadowsOptimization(priority));
  28806. result.optimizations.push(new LensFlaresOptimization(priority));
  28807. // Next priority
  28808. priority++;
  28809. result.optimizations.push(new PostProcessesOptimization(priority));
  28810. result.optimizations.push(new ParticlesOptimization(priority));
  28811. // Next priority
  28812. priority++;
  28813. result.optimizations.push(new TextureOptimization(priority, 512));
  28814. // Next priority
  28815. priority++;
  28816. result.optimizations.push(new RenderTargetsOptimization(priority));
  28817. // Next priority
  28818. priority++;
  28819. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28820. return result;
  28821. };
  28822. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28823. var result = new SceneOptimizerOptions(targetFrameRate);
  28824. var priority = 0;
  28825. result.optimizations.push(new MergeMeshesOptimization(priority));
  28826. result.optimizations.push(new ShadowsOptimization(priority));
  28827. result.optimizations.push(new LensFlaresOptimization(priority));
  28828. // Next priority
  28829. priority++;
  28830. result.optimizations.push(new PostProcessesOptimization(priority));
  28831. result.optimizations.push(new ParticlesOptimization(priority));
  28832. // Next priority
  28833. priority++;
  28834. result.optimizations.push(new TextureOptimization(priority, 256));
  28835. // Next priority
  28836. priority++;
  28837. result.optimizations.push(new RenderTargetsOptimization(priority));
  28838. // Next priority
  28839. priority++;
  28840. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28841. return result;
  28842. };
  28843. return SceneOptimizerOptions;
  28844. })();
  28845. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28846. // Scene optimizer tool
  28847. var SceneOptimizer = (function () {
  28848. function SceneOptimizer() {
  28849. }
  28850. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28851. // TODO: add an epsilon
  28852. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28853. if (onSuccess) {
  28854. onSuccess();
  28855. }
  28856. return;
  28857. }
  28858. // Apply current level of optimizations
  28859. var allDone = true;
  28860. var noOptimizationApplied = true;
  28861. for (var index = 0; index < options.optimizations.length; index++) {
  28862. var optimization = options.optimizations[index];
  28863. if (optimization.priority === currentPriorityLevel) {
  28864. noOptimizationApplied = false;
  28865. allDone = allDone && optimization.apply(scene);
  28866. }
  28867. }
  28868. // If no optimization was applied, this is a failure :(
  28869. if (noOptimizationApplied) {
  28870. if (onFailure) {
  28871. onFailure();
  28872. }
  28873. return;
  28874. }
  28875. // If all optimizations were done, move to next level
  28876. if (allDone) {
  28877. currentPriorityLevel++;
  28878. }
  28879. // Let's the system running for a specific amount of time before checking FPS
  28880. scene.executeWhenReady(function () {
  28881. setTimeout(function () {
  28882. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28883. }, options.trackerDuration);
  28884. });
  28885. };
  28886. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28887. if (!options) {
  28888. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28889. }
  28890. // Let's the system running for a specific amount of time before checking FPS
  28891. scene.executeWhenReady(function () {
  28892. setTimeout(function () {
  28893. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28894. }, options.trackerDuration);
  28895. });
  28896. };
  28897. return SceneOptimizer;
  28898. })();
  28899. BABYLON.SceneOptimizer = SceneOptimizer;
  28900. })(BABYLON || (BABYLON = {}));
  28901. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28902. var BABYLON;
  28903. (function (BABYLON) {
  28904. var Internals;
  28905. (function (Internals) {
  28906. var MeshLODLevel = (function () {
  28907. function MeshLODLevel(distance, mesh) {
  28908. this.distance = distance;
  28909. this.mesh = mesh;
  28910. }
  28911. return MeshLODLevel;
  28912. })();
  28913. Internals.MeshLODLevel = MeshLODLevel;
  28914. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28915. })(BABYLON || (BABYLON = {}));
  28916. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28917. var BABYLON;
  28918. (function (BABYLON) {
  28919. var AudioEngine = (function () {
  28920. function AudioEngine() {
  28921. this._audioContext = null;
  28922. this._audioContextInitialized = false;
  28923. this.canUseWebAudio = false;
  28924. this.WarnedWebAudioUnsupported = false;
  28925. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28926. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28927. this.canUseWebAudio = true;
  28928. }
  28929. }
  28930. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28931. get: function () {
  28932. if (!this._audioContextInitialized) {
  28933. this._initializeAudioContext();
  28934. }
  28935. return this._audioContext;
  28936. },
  28937. enumerable: true,
  28938. configurable: true
  28939. });
  28940. AudioEngine.prototype._initializeAudioContext = function () {
  28941. try {
  28942. if (this.canUseWebAudio) {
  28943. this._audioContext = new AudioContext();
  28944. // create a global volume gain node
  28945. this.masterGain = this._audioContext.createGain();
  28946. this.masterGain.gain.value = 1;
  28947. this.masterGain.connect(this._audioContext.destination);
  28948. this._audioContextInitialized = true;
  28949. }
  28950. }
  28951. catch (e) {
  28952. this.canUseWebAudio = false;
  28953. BABYLON.Tools.Error("Web Audio: " + e.message);
  28954. }
  28955. };
  28956. AudioEngine.prototype.dispose = function () {
  28957. if (this.canUseWebAudio && this._audioContextInitialized) {
  28958. if (this._connectedAnalyser) {
  28959. this._connectedAnalyser.stopDebugCanvas();
  28960. this._connectedAnalyser.dispose();
  28961. this.masterGain.disconnect();
  28962. this.masterGain.connect(this._audioContext.destination);
  28963. this._connectedAnalyser = null;
  28964. }
  28965. this.masterGain.gain.value = 1;
  28966. }
  28967. this.WarnedWebAudioUnsupported = false;
  28968. };
  28969. AudioEngine.prototype.getGlobalVolume = function () {
  28970. if (this.canUseWebAudio && this._audioContextInitialized) {
  28971. return this.masterGain.gain.value;
  28972. }
  28973. else {
  28974. return -1;
  28975. }
  28976. };
  28977. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28978. if (this.canUseWebAudio && this._audioContextInitialized) {
  28979. this.masterGain.gain.value = newVolume;
  28980. }
  28981. };
  28982. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28983. if (this._connectedAnalyser) {
  28984. this._connectedAnalyser.stopDebugCanvas();
  28985. }
  28986. if (this.canUseWebAudio && this._audioContextInitialized) {
  28987. this._connectedAnalyser = analyser;
  28988. this.masterGain.disconnect();
  28989. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28990. }
  28991. };
  28992. return AudioEngine;
  28993. })();
  28994. BABYLON.AudioEngine = AudioEngine;
  28995. })(BABYLON || (BABYLON = {}));
  28996. //# sourceMappingURL=babylon.audioEngine.js.map
  28997. var BABYLON;
  28998. (function (BABYLON) {
  28999. var Sound = (function () {
  29000. /**
  29001. * Create a sound and attach it to a scene
  29002. * @param name Name of your sound
  29003. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29004. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29005. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  29006. */
  29007. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29008. var _this = this;
  29009. this.autoplay = false;
  29010. this.loop = false;
  29011. this.useCustomAttenuation = false;
  29012. this.spatialSound = false;
  29013. this.refDistance = 1;
  29014. this.rolloffFactor = 1;
  29015. this.maxDistance = 100;
  29016. this.distanceModel = "linear";
  29017. this._panningModel = "equalpower";
  29018. this._playbackRate = 1;
  29019. this._startTime = 0;
  29020. this._startOffset = 0;
  29021. this._position = BABYLON.Vector3.Zero();
  29022. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29023. this._volume = 1;
  29024. this._isLoaded = false;
  29025. this._isReadyToPlay = false;
  29026. this.isPlaying = false;
  29027. this.isPaused = false;
  29028. this._isDirectional = false;
  29029. // Used if you'd like to create a directional sound.
  29030. // If not set, the sound will be omnidirectional
  29031. this._coneInnerAngle = 360;
  29032. this._coneOuterAngle = 360;
  29033. this._coneOuterGain = 0;
  29034. this.name = name;
  29035. this._scene = scene;
  29036. this._readyToPlayCallback = readyToPlayCallback;
  29037. // Default custom attenuation function is a linear attenuation
  29038. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29039. if (currentDistance < maxDistance) {
  29040. return currentVolume * (1 - currentDistance / maxDistance);
  29041. }
  29042. else {
  29043. return 0;
  29044. }
  29045. };
  29046. if (options) {
  29047. this.autoplay = options.autoplay || false;
  29048. this.loop = options.loop || false;
  29049. // if volume === 0, we need another way to check this option
  29050. if (options.volume !== undefined) {
  29051. this._volume = options.volume;
  29052. }
  29053. this.spatialSound = options.spatialSound || false;
  29054. this.maxDistance = options.maxDistance || 100;
  29055. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29056. this.rolloffFactor = options.rolloffFactor || 1;
  29057. this.refDistance = options.refDistance || 1;
  29058. this.distanceModel = options.distanceModel || "linear";
  29059. this._playbackRate = options.playbackRate || 1;
  29060. }
  29061. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29062. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29063. this._soundGain.gain.value = this._volume;
  29064. this._inputAudioNode = this._soundGain;
  29065. this._ouputAudioNode = this._soundGain;
  29066. if (this.spatialSound) {
  29067. this._createSpatialParameters();
  29068. }
  29069. this._scene.mainSoundTrack.AddSound(this);
  29070. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29071. if (urlOrArrayBuffer) {
  29072. // If it's an URL
  29073. if (typeof (urlOrArrayBuffer) === "string") {
  29074. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  29075. }
  29076. else {
  29077. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29078. this._soundLoaded(urlOrArrayBuffer);
  29079. }
  29080. else {
  29081. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29082. }
  29083. }
  29084. }
  29085. }
  29086. else {
  29087. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29088. this._scene.mainSoundTrack.AddSound(this);
  29089. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29090. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29091. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29092. }
  29093. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29094. if (this._readyToPlayCallback) {
  29095. window.setTimeout(function () {
  29096. _this._readyToPlayCallback();
  29097. }, 1000);
  29098. }
  29099. }
  29100. }
  29101. Sound.prototype.dispose = function () {
  29102. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29103. if (this.isPlaying) {
  29104. this.stop();
  29105. }
  29106. this._isReadyToPlay = false;
  29107. if (this.soundTrackId === -1) {
  29108. this._scene.mainSoundTrack.RemoveSound(this);
  29109. }
  29110. else {
  29111. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29112. }
  29113. if (this._soundGain) {
  29114. this._soundGain.disconnect();
  29115. this._soundGain = null;
  29116. }
  29117. if (this._soundPanner) {
  29118. this._soundPanner.disconnect();
  29119. this._soundPanner = null;
  29120. }
  29121. if (this._soundSource) {
  29122. this._soundSource.disconnect();
  29123. this._soundSource = null;
  29124. }
  29125. this._audioBuffer = null;
  29126. if (this._connectedMesh) {
  29127. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29128. this._connectedMesh = null;
  29129. }
  29130. }
  29131. };
  29132. Sound.prototype._soundLoaded = function (audioData) {
  29133. var _this = this;
  29134. this._isLoaded = true;
  29135. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29136. _this._audioBuffer = buffer;
  29137. _this._isReadyToPlay = true;
  29138. if (_this.autoplay) {
  29139. _this.play();
  29140. }
  29141. if (_this._readyToPlayCallback) {
  29142. _this._readyToPlayCallback();
  29143. }
  29144. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  29145. };
  29146. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29147. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29148. this._audioBuffer = audioBuffer;
  29149. this._isReadyToPlay = true;
  29150. }
  29151. };
  29152. Sound.prototype.updateOptions = function (options) {
  29153. if (options) {
  29154. this.loop = options.loop || this.loop;
  29155. this.maxDistance = options.maxDistance || this.maxDistance;
  29156. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29157. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29158. this.refDistance = options.refDistance || this.refDistance;
  29159. this.distanceModel = options.distanceModel || this.distanceModel;
  29160. this._playbackRate = options.playbackRate || this._playbackRate;
  29161. this._updateSpatialParameters();
  29162. if (this.isPlaying) {
  29163. this._soundSource.playbackRate.value = this._playbackRate;
  29164. }
  29165. }
  29166. };
  29167. Sound.prototype._createSpatialParameters = function () {
  29168. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29169. if (this._scene.headphone) {
  29170. this._panningModel = "HRTF";
  29171. }
  29172. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29173. this._updateSpatialParameters();
  29174. this._soundPanner.connect(this._ouputAudioNode);
  29175. this._inputAudioNode = this._soundPanner;
  29176. }
  29177. };
  29178. Sound.prototype._updateSpatialParameters = function () {
  29179. if (this.spatialSound) {
  29180. if (this.useCustomAttenuation) {
  29181. // Tricks to disable in a way embedded Web Audio attenuation
  29182. this._soundPanner.distanceModel = "linear";
  29183. this._soundPanner.maxDistance = Number.MAX_VALUE;
  29184. this._soundPanner.refDistance = 1;
  29185. this._soundPanner.rolloffFactor = 1;
  29186. this._soundPanner.panningModel = this._panningModel;
  29187. }
  29188. else {
  29189. this._soundPanner.distanceModel = this.distanceModel;
  29190. this._soundPanner.maxDistance = this.maxDistance;
  29191. this._soundPanner.refDistance = this.refDistance;
  29192. this._soundPanner.rolloffFactor = this.rolloffFactor;
  29193. this._soundPanner.panningModel = this._panningModel;
  29194. }
  29195. }
  29196. };
  29197. Sound.prototype.switchPanningModelToHRTF = function () {
  29198. this._panningModel = "HRTF";
  29199. this._switchPanningModel();
  29200. };
  29201. Sound.prototype.switchPanningModelToEqualPower = function () {
  29202. this._panningModel = "equalpower";
  29203. this._switchPanningModel();
  29204. };
  29205. Sound.prototype._switchPanningModel = function () {
  29206. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29207. this._soundPanner.panningModel = this._panningModel;
  29208. }
  29209. };
  29210. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29211. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29212. this._ouputAudioNode.disconnect();
  29213. this._ouputAudioNode.connect(soundTrackAudioNode);
  29214. }
  29215. };
  29216. /**
  29217. * Transform this sound into a directional source
  29218. * @param coneInnerAngle Size of the inner cone in degree
  29219. * @param coneOuterAngle Size of the outer cone in degree
  29220. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29221. */
  29222. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29223. if (coneOuterAngle < coneInnerAngle) {
  29224. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29225. return;
  29226. }
  29227. this._coneInnerAngle = coneInnerAngle;
  29228. this._coneOuterAngle = coneOuterAngle;
  29229. this._coneOuterGain = coneOuterGain;
  29230. this._isDirectional = true;
  29231. if (this.isPlaying && this.loop) {
  29232. this.stop();
  29233. this.play();
  29234. }
  29235. };
  29236. Sound.prototype.setPosition = function (newPosition) {
  29237. this._position = newPosition;
  29238. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29239. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29240. }
  29241. };
  29242. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  29243. this._localDirection = newLocalDirection;
  29244. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  29245. this._updateDirection();
  29246. }
  29247. };
  29248. Sound.prototype._updateDirection = function () {
  29249. var mat = this._connectedMesh.getWorldMatrix();
  29250. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29251. direction.normalize();
  29252. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29253. };
  29254. Sound.prototype.updateDistanceFromListener = function () {
  29255. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29256. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29257. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29258. }
  29259. };
  29260. Sound.prototype.setAttenuationFunction = function (callback) {
  29261. this._customAttenuationFunction = callback;
  29262. };
  29263. /**
  29264. * Play the sound
  29265. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29266. */
  29267. Sound.prototype.play = function (time) {
  29268. var _this = this;
  29269. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29270. try {
  29271. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29272. if (!this._soundSource) {
  29273. if (this.spatialSound) {
  29274. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29275. if (this._isDirectional) {
  29276. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29277. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29278. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29279. if (this._connectedMesh) {
  29280. this._updateDirection();
  29281. }
  29282. else {
  29283. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29284. }
  29285. }
  29286. }
  29287. }
  29288. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29289. this._soundSource.buffer = this._audioBuffer;
  29290. this._soundSource.connect(this._inputAudioNode);
  29291. this._soundSource.loop = this.loop;
  29292. this._soundSource.playbackRate.value = this._playbackRate;
  29293. this._startTime = startTime;
  29294. this._soundSource.onended = function () { _this._onended(); };
  29295. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29296. this.isPlaying = true;
  29297. this.isPaused = false;
  29298. }
  29299. catch (ex) {
  29300. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29301. }
  29302. }
  29303. };
  29304. Sound.prototype._onended = function () {
  29305. this.isPlaying = false;
  29306. if (this.onended) {
  29307. this.onended();
  29308. }
  29309. };
  29310. /**
  29311. * Stop the sound
  29312. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29313. */
  29314. Sound.prototype.stop = function (time) {
  29315. if (this.isPlaying) {
  29316. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29317. this._soundSource.stop(stopTime);
  29318. this.isPlaying = false;
  29319. }
  29320. };
  29321. Sound.prototype.pause = function () {
  29322. if (this.isPlaying) {
  29323. this.stop(0);
  29324. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29325. this.isPaused = true;
  29326. }
  29327. };
  29328. Sound.prototype.setVolume = function (newVolume, time) {
  29329. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29330. if (time) {
  29331. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29332. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29333. }
  29334. else {
  29335. this._soundGain.gain.value = newVolume;
  29336. }
  29337. }
  29338. this._volume = newVolume;
  29339. };
  29340. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29341. this._playbackRate = newPlaybackRate;
  29342. if (this.isPlaying) {
  29343. this._soundSource.playbackRate.value = this._playbackRate;
  29344. }
  29345. };
  29346. Sound.prototype.getVolume = function () {
  29347. return this._volume;
  29348. };
  29349. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29350. var _this = this;
  29351. this._connectedMesh = meshToConnectTo;
  29352. if (!this.spatialSound) {
  29353. this.spatialSound = true;
  29354. this._createSpatialParameters();
  29355. if (this.isPlaying && this.loop) {
  29356. this.stop();
  29357. this.play();
  29358. }
  29359. }
  29360. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29361. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29362. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29363. };
  29364. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29365. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29366. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29367. this._updateDirection();
  29368. }
  29369. };
  29370. return Sound;
  29371. })();
  29372. BABYLON.Sound = Sound;
  29373. })(BABYLON || (BABYLON = {}));
  29374. //# sourceMappingURL=babylon.sound.js.map
  29375. var BABYLON;
  29376. (function (BABYLON) {
  29377. var SoundTrack = (function () {
  29378. function SoundTrack(scene, options) {
  29379. this.id = -1;
  29380. this._isMainTrack = false;
  29381. this._scene = scene;
  29382. this._audioEngine = BABYLON.Engine.audioEngine;
  29383. this.soundCollection = new Array();
  29384. if (this._audioEngine.canUseWebAudio) {
  29385. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  29386. this._outputAudioNode.connect(this._audioEngine.masterGain);
  29387. if (options) {
  29388. if (options.volume) {
  29389. this._outputAudioNode.gain.value = options.volume;
  29390. }
  29391. if (options.mainTrack) {
  29392. this._isMainTrack = options.mainTrack;
  29393. }
  29394. }
  29395. }
  29396. if (!this._isMainTrack) {
  29397. this._scene.soundTracks.push(this);
  29398. this.id = this._scene.soundTracks.length - 1;
  29399. }
  29400. }
  29401. SoundTrack.prototype.dispose = function () {
  29402. if (this._audioEngine.canUseWebAudio) {
  29403. if (this._connectedAnalyser) {
  29404. this._connectedAnalyser.stopDebugCanvas();
  29405. }
  29406. while (this.soundCollection.length) {
  29407. this.soundCollection[0].dispose();
  29408. }
  29409. this._outputAudioNode.disconnect();
  29410. this._outputAudioNode = null;
  29411. }
  29412. };
  29413. SoundTrack.prototype.AddSound = function (sound) {
  29414. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29415. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  29416. }
  29417. if (sound.soundTrackId) {
  29418. if (sound.soundTrackId === -1) {
  29419. this._scene.mainSoundTrack.RemoveSound(sound);
  29420. }
  29421. else {
  29422. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29423. }
  29424. }
  29425. this.soundCollection.push(sound);
  29426. sound.soundTrackId = this.id;
  29427. };
  29428. SoundTrack.prototype.RemoveSound = function (sound) {
  29429. var index = this.soundCollection.indexOf(sound);
  29430. if (index !== -1) {
  29431. this.soundCollection.splice(index, 1);
  29432. }
  29433. };
  29434. SoundTrack.prototype.setVolume = function (newVolume) {
  29435. if (this._audioEngine.canUseWebAudio) {
  29436. this._outputAudioNode.gain.value = newVolume;
  29437. }
  29438. };
  29439. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29440. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29441. for (var i = 0; i < this.soundCollection.length; i++) {
  29442. this.soundCollection[i].switchPanningModelToHRTF();
  29443. }
  29444. }
  29445. };
  29446. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29447. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29448. for (var i = 0; i < this.soundCollection.length; i++) {
  29449. this.soundCollection[i].switchPanningModelToEqualPower();
  29450. }
  29451. }
  29452. };
  29453. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29454. if (this._connectedAnalyser) {
  29455. this._connectedAnalyser.stopDebugCanvas();
  29456. }
  29457. this._connectedAnalyser = analyser;
  29458. if (this._audioEngine.canUseWebAudio) {
  29459. this._outputAudioNode.disconnect();
  29460. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  29461. }
  29462. };
  29463. return SoundTrack;
  29464. })();
  29465. BABYLON.SoundTrack = SoundTrack;
  29466. })(BABYLON || (BABYLON = {}));
  29467. //# sourceMappingURL=babylon.soundtrack.js.map
  29468. var BABYLON;
  29469. (function (BABYLON) {
  29470. var DebugLayer = (function () {
  29471. function DebugLayer(scene) {
  29472. var _this = this;
  29473. this._transformationMatrix = BABYLON.Matrix.Identity();
  29474. this._enabled = false;
  29475. this._labelsEnabled = false;
  29476. this._displayStatistics = true;
  29477. this._displayTree = false;
  29478. this._displayLogs = false;
  29479. this._identityMatrix = BABYLON.Matrix.Identity();
  29480. this.axisRatio = 0.02;
  29481. this.accentColor = "orange";
  29482. this._scene = scene;
  29483. this._syncPositions = function () {
  29484. var engine = _this._scene.getEngine();
  29485. var canvasRect = engine.getRenderingCanvasClientRect();
  29486. if (_this._showUI) {
  29487. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29488. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29489. _this._statsDiv.style.width = "400px";
  29490. _this._statsDiv.style.height = "auto";
  29491. _this._statsSubsetDiv.style.maxHeight = "240px";
  29492. _this._optionsDiv.style.left = "0px";
  29493. _this._optionsDiv.style.top = "10px";
  29494. _this._optionsDiv.style.width = "200px";
  29495. _this._optionsDiv.style.height = "auto";
  29496. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29497. _this._logDiv.style.left = "0px";
  29498. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29499. _this._logDiv.style.width = "600px";
  29500. _this._logDiv.style.height = "160px";
  29501. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29502. _this._treeDiv.style.top = "10px";
  29503. _this._treeDiv.style.width = "300px";
  29504. _this._treeDiv.style.height = "auto";
  29505. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29506. }
  29507. _this._globalDiv.style.left = canvasRect.left + "px";
  29508. _this._globalDiv.style.top = canvasRect.top + "px";
  29509. _this._drawingCanvas.style.left = "0px";
  29510. _this._drawingCanvas.style.top = "0px";
  29511. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29512. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29513. var devicePixelRatio = window.devicePixelRatio || 1;
  29514. var context = _this._drawingContext;
  29515. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29516. context.mozBackingStorePixelRatio ||
  29517. context.msBackingStorePixelRatio ||
  29518. context.oBackingStorePixelRatio ||
  29519. context.backingStorePixelRatio || 1;
  29520. _this._ratio = devicePixelRatio / backingStoreRatio;
  29521. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29522. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29523. };
  29524. this._onCanvasClick = function (evt) {
  29525. _this._clickPosition = {
  29526. x: evt.clientX * _this._ratio,
  29527. y: evt.clientY * _this._ratio
  29528. };
  29529. };
  29530. this._syncUI = function () {
  29531. if (_this._showUI) {
  29532. if (_this._displayStatistics) {
  29533. _this._displayStats();
  29534. _this._statsDiv.style.display = "";
  29535. }
  29536. else {
  29537. _this._statsDiv.style.display = "none";
  29538. }
  29539. if (_this._displayLogs) {
  29540. _this._logDiv.style.display = "";
  29541. }
  29542. else {
  29543. _this._logDiv.style.display = "none";
  29544. }
  29545. if (_this._displayTree) {
  29546. _this._treeDiv.style.display = "";
  29547. if (_this._needToRefreshMeshesTree) {
  29548. _this._needToRefreshMeshesTree = false;
  29549. _this._refreshMeshesTreeContent();
  29550. }
  29551. }
  29552. else {
  29553. _this._treeDiv.style.display = "none";
  29554. }
  29555. }
  29556. };
  29557. this._syncData = function () {
  29558. if (_this._labelsEnabled || !_this._showUI) {
  29559. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29560. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29561. var engine = _this._scene.getEngine();
  29562. var viewport = _this._camera.viewport;
  29563. var globalViewport = viewport.toGlobal(engine);
  29564. // Meshes
  29565. var meshes = _this._camera.getActiveMeshes();
  29566. for (var index = 0; index < meshes.length; index++) {
  29567. var mesh = meshes.data[index];
  29568. var position = mesh.getBoundingInfo().boundingSphere.center;
  29569. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29570. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29571. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29572. }
  29573. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29574. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29575. }
  29576. }
  29577. // Cameras
  29578. var cameras = _this._scene.cameras;
  29579. for (index = 0; index < cameras.length; index++) {
  29580. var camera = cameras[index];
  29581. if (camera === _this._camera) {
  29582. continue;
  29583. }
  29584. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29585. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29586. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29587. _this._camera.detachControl(engine.getRenderingCanvas());
  29588. _this._camera = camera;
  29589. _this._camera.attachControl(engine.getRenderingCanvas());
  29590. }, function () { return "purple"; });
  29591. }
  29592. }
  29593. // Lights
  29594. var lights = _this._scene.lights;
  29595. for (index = 0; index < lights.length; index++) {
  29596. var light = lights[index];
  29597. if (light.position) {
  29598. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29599. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29600. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29601. light.setEnabled(!light.isEnabled());
  29602. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29603. }
  29604. }
  29605. }
  29606. }
  29607. _this._clickPosition = undefined;
  29608. };
  29609. }
  29610. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29611. while (this._treeSubsetDiv.hasChildNodes()) {
  29612. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29613. }
  29614. // Add meshes
  29615. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29616. sortedArray.sort(function (a, b) {
  29617. if (a.name === b.name) {
  29618. return 0;
  29619. }
  29620. return (a.name > b.name) ? 1 : -1;
  29621. });
  29622. for (var index = 0; index < sortedArray.length; index++) {
  29623. var mesh = sortedArray[index];
  29624. if (!mesh.isEnabled()) {
  29625. continue;
  29626. }
  29627. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29628. m.isVisible = element.checked;
  29629. }, mesh);
  29630. }
  29631. };
  29632. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29633. this._drawingContext.beginPath();
  29634. this._drawingContext.moveTo(zero.x, zero.y);
  29635. this._drawingContext.lineTo(unit.x, unit.y);
  29636. this._drawingContext.strokeStyle = color;
  29637. this._drawingContext.lineWidth = 4;
  29638. this._drawingContext.stroke();
  29639. this._drawingContext.font = "normal 14px Segoe UI";
  29640. this._drawingContext.fillStyle = color;
  29641. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29642. };
  29643. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29644. var position = mesh.getBoundingInfo().boundingSphere.center;
  29645. var worldMatrix = mesh.getWorldMatrix();
  29646. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29647. var unit = (unprojectedVector.subtract(position)).length();
  29648. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29649. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29650. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29651. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29652. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29653. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29654. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29655. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29656. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29657. };
  29658. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29659. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29660. this._drawingContext.font = "normal 12px Segoe UI";
  29661. var textMetrics = this._drawingContext.measureText(text);
  29662. var centerX = projectedPosition.x - textMetrics.width / 2;
  29663. var centerY = projectedPosition.y;
  29664. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29665. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29666. onClick();
  29667. }
  29668. this._drawingContext.beginPath();
  29669. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29670. this._drawingContext.fillStyle = getFillStyle();
  29671. this._drawingContext.globalAlpha = 0.5;
  29672. this._drawingContext.fill();
  29673. this._drawingContext.globalAlpha = 1.0;
  29674. this._drawingContext.strokeStyle = '#FFFFFF';
  29675. this._drawingContext.lineWidth = 1;
  29676. this._drawingContext.stroke();
  29677. this._drawingContext.fillStyle = "#FFFFFF";
  29678. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29679. this._drawingContext.beginPath();
  29680. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29681. this._drawingContext.fill();
  29682. }
  29683. };
  29684. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29685. if (!this._clickPosition) {
  29686. return false;
  29687. }
  29688. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29689. return false;
  29690. }
  29691. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29692. return false;
  29693. }
  29694. return true;
  29695. };
  29696. DebugLayer.prototype.isVisible = function () {
  29697. return this._enabled;
  29698. };
  29699. DebugLayer.prototype.hide = function () {
  29700. if (!this._enabled) {
  29701. return;
  29702. }
  29703. this._enabled = false;
  29704. var engine = this._scene.getEngine();
  29705. this._scene.unregisterBeforeRender(this._syncData);
  29706. this._scene.unregisterAfterRender(this._syncUI);
  29707. document.body.removeChild(this._globalDiv);
  29708. window.removeEventListener("resize", this._syncPositions);
  29709. this._scene.forceShowBoundingBoxes = false;
  29710. this._scene.forceWireframe = false;
  29711. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29712. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29713. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29714. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29715. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29716. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29717. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29718. this._scene.shadowsEnabled = true;
  29719. this._scene.particlesEnabled = true;
  29720. this._scene.postProcessesEnabled = true;
  29721. this._scene.collisionsEnabled = true;
  29722. this._scene.lightsEnabled = true;
  29723. this._scene.texturesEnabled = true;
  29724. this._scene.lensFlaresEnabled = true;
  29725. this._scene.proceduralTexturesEnabled = true;
  29726. this._scene.renderTargetsEnabled = true;
  29727. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29728. };
  29729. DebugLayer.prototype.show = function (showUI, camera) {
  29730. if (showUI === void 0) { showUI = true; }
  29731. if (camera === void 0) { camera = null; }
  29732. if (this._enabled) {
  29733. return;
  29734. }
  29735. this._enabled = true;
  29736. if (camera) {
  29737. this._camera = camera;
  29738. }
  29739. else {
  29740. this._camera = this._scene.activeCamera;
  29741. }
  29742. this._showUI = showUI;
  29743. var engine = this._scene.getEngine();
  29744. this._globalDiv = document.createElement("div");
  29745. document.body.appendChild(this._globalDiv);
  29746. this._generateDOMelements();
  29747. window.addEventListener("resize", this._syncPositions);
  29748. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29749. this._syncPositions();
  29750. this._scene.registerBeforeRender(this._syncData);
  29751. this._scene.registerAfterRender(this._syncUI);
  29752. };
  29753. DebugLayer.prototype._clearLabels = function () {
  29754. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29755. for (var index = 0; index < this._scene.meshes.length; index++) {
  29756. var mesh = this._scene.meshes[index];
  29757. mesh.renderOverlay = false;
  29758. }
  29759. };
  29760. DebugLayer.prototype._generateheader = function (root, text) {
  29761. var header = document.createElement("div");
  29762. header.innerHTML = text + "&nbsp;";
  29763. header.style.textAlign = "right";
  29764. header.style.width = "100%";
  29765. header.style.color = "white";
  29766. header.style.backgroundColor = "Black";
  29767. header.style.padding = "5px 5px 4px 0px";
  29768. header.style.marginLeft = "-5px";
  29769. header.style.fontWeight = "bold";
  29770. root.appendChild(header);
  29771. };
  29772. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29773. var label = document.createElement("label");
  29774. label.innerHTML = title;
  29775. label.style.color = color;
  29776. root.appendChild(label);
  29777. root.appendChild(document.createElement("br"));
  29778. };
  29779. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29780. if (tag === void 0) { tag = null; }
  29781. var label = document.createElement("label");
  29782. var boundingBoxesCheckbox = document.createElement("input");
  29783. boundingBoxesCheckbox.type = "checkbox";
  29784. boundingBoxesCheckbox.checked = initialState;
  29785. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29786. task(evt.target, tag);
  29787. });
  29788. label.appendChild(boundingBoxesCheckbox);
  29789. var container = document.createElement("span");
  29790. var leftPart = document.createElement("span");
  29791. var rightPart = document.createElement("span");
  29792. rightPart.style.cssFloat = "right";
  29793. leftPart.innerHTML = leftTitle;
  29794. rightPart.innerHTML = rightTitle;
  29795. rightPart.style.fontSize = "12px";
  29796. rightPart.style.maxWidth = "200px";
  29797. container.appendChild(leftPart);
  29798. container.appendChild(rightPart);
  29799. label.appendChild(container);
  29800. root.appendChild(label);
  29801. root.appendChild(document.createElement("br"));
  29802. };
  29803. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29804. if (tag === void 0) { tag = null; }
  29805. var label = document.createElement("label");
  29806. var checkBox = document.createElement("input");
  29807. checkBox.type = "checkbox";
  29808. checkBox.checked = initialState;
  29809. checkBox.addEventListener("change", function (evt) {
  29810. task(evt.target, tag);
  29811. });
  29812. label.appendChild(checkBox);
  29813. label.appendChild(document.createTextNode(title));
  29814. root.appendChild(label);
  29815. root.appendChild(document.createElement("br"));
  29816. };
  29817. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29818. if (tag === void 0) { tag = null; }
  29819. var button = document.createElement("button");
  29820. button.innerHTML = title;
  29821. button.style.height = "24px";
  29822. button.style.color = "#444444";
  29823. button.style.border = "1px solid white";
  29824. button.className = "debugLayerButton";
  29825. button.addEventListener("click", function (evt) {
  29826. task(evt.target, tag);
  29827. });
  29828. root.appendChild(button);
  29829. root.appendChild(document.createElement("br"));
  29830. };
  29831. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29832. if (tag === void 0) { tag = null; }
  29833. var label = document.createElement("label");
  29834. var boundingBoxesRadio = document.createElement("input");
  29835. boundingBoxesRadio.type = "radio";
  29836. boundingBoxesRadio.name = name;
  29837. boundingBoxesRadio.checked = initialState;
  29838. boundingBoxesRadio.addEventListener("change", function (evt) {
  29839. task(evt.target, tag);
  29840. });
  29841. label.appendChild(boundingBoxesRadio);
  29842. label.appendChild(document.createTextNode(title));
  29843. root.appendChild(label);
  29844. root.appendChild(document.createElement("br"));
  29845. };
  29846. DebugLayer.prototype._generateDOMelements = function () {
  29847. var _this = this;
  29848. this._globalDiv.id = "DebugLayer";
  29849. this._globalDiv.style.position = "absolute";
  29850. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29851. this._globalDiv.style.fontSize = "14px";
  29852. this._globalDiv.style.color = "white";
  29853. // Drawing canvas
  29854. this._drawingCanvas = document.createElement("canvas");
  29855. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29856. this._drawingCanvas.style.position = "absolute";
  29857. this._drawingCanvas.style.pointerEvents = "none";
  29858. this._drawingContext = this._drawingCanvas.getContext("2d");
  29859. this._globalDiv.appendChild(this._drawingCanvas);
  29860. if (this._showUI) {
  29861. var background = "rgba(128, 128, 128, 0.4)";
  29862. var border = "rgb(180, 180, 180) solid 1px";
  29863. // Stats
  29864. this._statsDiv = document.createElement("div");
  29865. this._statsDiv.id = "DebugLayerStats";
  29866. this._statsDiv.style.border = border;
  29867. this._statsDiv.style.position = "absolute";
  29868. this._statsDiv.style.background = background;
  29869. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29870. this._generateheader(this._statsDiv, "STATISTICS");
  29871. this._statsSubsetDiv = document.createElement("div");
  29872. this._statsSubsetDiv.style.paddingTop = "5px";
  29873. this._statsSubsetDiv.style.paddingBottom = "5px";
  29874. this._statsSubsetDiv.style.overflowY = "auto";
  29875. this._statsDiv.appendChild(this._statsSubsetDiv);
  29876. // Tree
  29877. this._treeDiv = document.createElement("div");
  29878. this._treeDiv.id = "DebugLayerTree";
  29879. this._treeDiv.style.border = border;
  29880. this._treeDiv.style.position = "absolute";
  29881. this._treeDiv.style.background = background;
  29882. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29883. this._treeDiv.style.display = "none";
  29884. this._generateheader(this._treeDiv, "MESHES TREE");
  29885. this._treeSubsetDiv = document.createElement("div");
  29886. this._treeSubsetDiv.style.paddingTop = "5px";
  29887. this._treeSubsetDiv.style.paddingRight = "5px";
  29888. this._treeSubsetDiv.style.overflowY = "auto";
  29889. this._treeSubsetDiv.style.maxHeight = "300px";
  29890. this._treeDiv.appendChild(this._treeSubsetDiv);
  29891. this._needToRefreshMeshesTree = true;
  29892. // Logs
  29893. this._logDiv = document.createElement("div");
  29894. this._logDiv.style.border = border;
  29895. this._logDiv.id = "DebugLayerLogs";
  29896. this._logDiv.style.position = "absolute";
  29897. this._logDiv.style.background = background;
  29898. this._logDiv.style.padding = "0px 0px 0px 5px";
  29899. this._logDiv.style.display = "none";
  29900. this._generateheader(this._logDiv, "LOGS");
  29901. this._logSubsetDiv = document.createElement("div");
  29902. this._logSubsetDiv.style.height = "127px";
  29903. this._logSubsetDiv.style.paddingTop = "5px";
  29904. this._logSubsetDiv.style.overflowY = "auto";
  29905. this._logSubsetDiv.style.fontSize = "12px";
  29906. this._logSubsetDiv.style.fontFamily = "consolas";
  29907. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29908. this._logDiv.appendChild(this._logSubsetDiv);
  29909. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29910. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29911. };
  29912. // Options
  29913. this._optionsDiv = document.createElement("div");
  29914. this._optionsDiv.id = "DebugLayerOptions";
  29915. this._optionsDiv.style.border = border;
  29916. this._optionsDiv.style.position = "absolute";
  29917. this._optionsDiv.style.background = background;
  29918. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29919. this._optionsDiv.style.overflowY = "auto";
  29920. this._generateheader(this._optionsDiv, "OPTIONS");
  29921. this._optionsSubsetDiv = document.createElement("div");
  29922. this._optionsSubsetDiv.style.paddingTop = "5px";
  29923. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29924. this._optionsSubsetDiv.style.overflowY = "auto";
  29925. this._optionsSubsetDiv.style.maxHeight = "200px";
  29926. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29927. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29928. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29929. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29930. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29931. _this._displayTree = element.checked;
  29932. _this._needToRefreshMeshesTree = true;
  29933. });
  29934. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29935. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29936. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29937. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29938. _this._labelsEnabled = element.checked;
  29939. if (!_this._labelsEnabled) {
  29940. _this._clearLabels();
  29941. }
  29942. });
  29943. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29944. if (element.checked) {
  29945. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29946. }
  29947. else {
  29948. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29949. }
  29950. });
  29951. ;
  29952. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29953. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29954. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29955. if (element.checked) {
  29956. _this._scene.forceWireframe = false;
  29957. _this._scene.forcePointsCloud = false;
  29958. }
  29959. });
  29960. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29961. if (element.checked) {
  29962. _this._scene.forceWireframe = true;
  29963. _this._scene.forcePointsCloud = false;
  29964. }
  29965. });
  29966. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29967. if (element.checked) {
  29968. _this._scene.forceWireframe = false;
  29969. _this._scene.forcePointsCloud = true;
  29970. }
  29971. });
  29972. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29973. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29974. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29975. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29976. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29977. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29978. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29979. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29980. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29981. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29982. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29983. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29984. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29985. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29986. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29987. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29988. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29989. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29990. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29991. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29992. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29993. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29994. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29995. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29996. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29997. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29998. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29999. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  30000. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  30001. if (element.checked) {
  30002. _this._scene.headphone = true;
  30003. }
  30004. });
  30005. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  30006. if (element.checked) {
  30007. _this._scene.headphone = false;
  30008. }
  30009. });
  30010. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  30011. _this._scene.audioEnabled = !element.checked;
  30012. });
  30013. }
  30014. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30015. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  30016. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  30017. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30018. this._globalDiv.appendChild(this._statsDiv);
  30019. this._globalDiv.appendChild(this._logDiv);
  30020. this._globalDiv.appendChild(this._optionsDiv);
  30021. this._globalDiv.appendChild(this._treeDiv);
  30022. }
  30023. };
  30024. DebugLayer.prototype._displayStats = function () {
  30025. var scene = this._scene;
  30026. var engine = scene.getEngine();
  30027. var glInfo = engine.getGlInfo();
  30028. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  30029. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30030. + "<b>Count</b><br>"
  30031. + "Total meshes: " + scene.meshes.length + "<br>"
  30032. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  30033. + "Total materials: " + scene.materials.length + "<br>"
  30034. + "Total textures: " + scene.textures.length + "<br>"
  30035. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  30036. + "Active indices: " + scene.getActiveIndices() + "<br>"
  30037. + "Active bones: " + scene.getActiveBones() + "<br>"
  30038. + "Active particles: " + scene.getActiveParticles() + "<br>"
  30039. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  30040. + "<b>Duration</b><br>"
  30041. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  30042. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  30043. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  30044. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  30045. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  30046. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  30047. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  30048. + "</div>"
  30049. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30050. + "<b>Extensions</b><br>"
  30051. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  30052. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  30053. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  30054. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  30055. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  30056. + "<b>Caps.</b><br>"
  30057. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  30058. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  30059. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  30060. + "</div><br>"
  30061. + "<b>Info</b><br>"
  30062. + glInfo.version + "<br>"
  30063. + glInfo.renderer + "<br>";
  30064. if (this.customStatsFunction) {
  30065. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  30066. }
  30067. };
  30068. return DebugLayer;
  30069. })();
  30070. BABYLON.DebugLayer = DebugLayer;
  30071. })(BABYLON || (BABYLON = {}));
  30072. //# sourceMappingURL=babylon.debugLayer.js.map
  30073. var __extends = (this && this.__extends) || function (d, b) {
  30074. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30075. function __() { this.constructor = d; }
  30076. __.prototype = b.prototype;
  30077. d.prototype = new __();
  30078. };
  30079. var BABYLON;
  30080. (function (BABYLON) {
  30081. var RawTexture = (function (_super) {
  30082. __extends(RawTexture, _super);
  30083. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  30084. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30085. if (invertY === void 0) { invertY = false; }
  30086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30087. _super.call(this, null, scene, !generateMipMaps, invertY);
  30088. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  30089. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30090. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30091. }
  30092. // Statics
  30093. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30094. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30095. if (invertY === void 0) { invertY = false; }
  30096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30097. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  30098. };
  30099. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30100. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30101. if (invertY === void 0) { invertY = false; }
  30102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30103. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30104. };
  30105. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30106. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30107. if (invertY === void 0) { invertY = false; }
  30108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30109. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30110. };
  30111. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30112. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30113. if (invertY === void 0) { invertY = false; }
  30114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30115. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  30116. };
  30117. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30118. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30119. if (invertY === void 0) { invertY = false; }
  30120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30121. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  30122. };
  30123. return RawTexture;
  30124. })(BABYLON.Texture);
  30125. BABYLON.RawTexture = RawTexture;
  30126. })(BABYLON || (BABYLON = {}));
  30127. //# sourceMappingURL=babylon.rawTexture.js.map
  30128. var __extends = (this && this.__extends) || function (d, b) {
  30129. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30130. function __() { this.constructor = d; }
  30131. __.prototype = b.prototype;
  30132. d.prototype = new __();
  30133. };
  30134. var BABYLON;
  30135. (function (BABYLON) {
  30136. var IndexedVector2 = (function (_super) {
  30137. __extends(IndexedVector2, _super);
  30138. function IndexedVector2(original, index) {
  30139. _super.call(this, original.x, original.y);
  30140. this.index = index;
  30141. }
  30142. return IndexedVector2;
  30143. })(BABYLON.Vector2);
  30144. var PolygonPoints = (function () {
  30145. function PolygonPoints() {
  30146. this.elements = new Array();
  30147. }
  30148. PolygonPoints.prototype.add = function (originalPoints) {
  30149. var _this = this;
  30150. var result = new Array();
  30151. originalPoints.forEach(function (point) {
  30152. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  30153. var newPoint = new IndexedVector2(point, _this.elements.length);
  30154. result.push(newPoint);
  30155. _this.elements.push(newPoint);
  30156. }
  30157. });
  30158. return result;
  30159. };
  30160. PolygonPoints.prototype.computeBounds = function () {
  30161. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30162. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30163. this.elements.forEach(function (point) {
  30164. // x
  30165. if (point.x < lmin.x) {
  30166. lmin.x = point.x;
  30167. }
  30168. else if (point.x > lmax.x) {
  30169. lmax.x = point.x;
  30170. }
  30171. // y
  30172. if (point.y < lmin.y) {
  30173. lmin.y = point.y;
  30174. }
  30175. else if (point.y > lmax.y) {
  30176. lmax.y = point.y;
  30177. }
  30178. });
  30179. return {
  30180. min: lmin,
  30181. max: lmax,
  30182. width: lmax.x - lmin.x,
  30183. height: lmax.y - lmin.y
  30184. };
  30185. };
  30186. return PolygonPoints;
  30187. })();
  30188. var Polygon = (function () {
  30189. function Polygon() {
  30190. }
  30191. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  30192. return [
  30193. new BABYLON.Vector2(xmin, ymin),
  30194. new BABYLON.Vector2(xmax, ymin),
  30195. new BABYLON.Vector2(xmax, ymax),
  30196. new BABYLON.Vector2(xmin, ymax)
  30197. ];
  30198. };
  30199. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  30200. if (cx === void 0) { cx = 0; }
  30201. if (cy === void 0) { cy = 0; }
  30202. if (numberOfSides === void 0) { numberOfSides = 32; }
  30203. var result = new Array();
  30204. var angle = 0;
  30205. var increment = (Math.PI * 2) / numberOfSides;
  30206. for (var i = 0; i < numberOfSides; i++) {
  30207. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  30208. angle -= increment;
  30209. }
  30210. return result;
  30211. };
  30212. Polygon.Parse = function (input) {
  30213. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  30214. var i, result = [];
  30215. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  30216. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  30217. }
  30218. return result;
  30219. };
  30220. Polygon.StartingAt = function (x, y) {
  30221. return BABYLON.Path2.StartingAt(x, y);
  30222. };
  30223. return Polygon;
  30224. })();
  30225. BABYLON.Polygon = Polygon;
  30226. var PolygonMeshBuilder = (function () {
  30227. function PolygonMeshBuilder(name, contours, scene) {
  30228. this._points = new PolygonPoints();
  30229. this._outlinepoints = new PolygonPoints();
  30230. this._holes = [];
  30231. if (!("poly2tri" in window)) {
  30232. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  30233. }
  30234. this._name = name;
  30235. this._scene = scene;
  30236. var points;
  30237. if (contours instanceof BABYLON.Path2) {
  30238. points = contours.getPoints();
  30239. }
  30240. else {
  30241. points = contours;
  30242. }
  30243. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  30244. this._outlinepoints.add(points);
  30245. }
  30246. PolygonMeshBuilder.prototype.addHole = function (hole) {
  30247. this._swctx.addHole(this._points.add(hole));
  30248. var holepoints = new PolygonPoints();
  30249. holepoints.add(hole);
  30250. this._holes.push(holepoints);
  30251. return this;
  30252. };
  30253. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  30254. var _this = this;
  30255. if (updatable === void 0) { updatable = false; }
  30256. var result = new BABYLON.Mesh(this._name, this._scene);
  30257. var normals = [];
  30258. var positions = [];
  30259. var uvs = [];
  30260. var bounds = this._points.computeBounds();
  30261. this._points.elements.forEach(function (p) {
  30262. normals.push(0, 1.0, 0);
  30263. positions.push(p.x, 0, p.y);
  30264. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  30265. });
  30266. var indices = [];
  30267. this._swctx.triangulate();
  30268. this._swctx.getTriangles().forEach(function (triangle) {
  30269. triangle.getPoints().forEach(function (point) {
  30270. indices.push(point.index);
  30271. });
  30272. });
  30273. if (depth > 0) {
  30274. var positionscount = (positions.length / 3); //get the current pointcount
  30275. this._points.elements.forEach(function (p) {
  30276. normals.push(0, -1.0, 0);
  30277. positions.push(p.x, -depth, p.y);
  30278. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  30279. });
  30280. var p1; //we need to change order of point so the triangles are made in the rigth way.
  30281. var p2;
  30282. var poscounter = 0;
  30283. this._swctx.getTriangles().forEach(function (triangle) {
  30284. triangle.getPoints().forEach(function (point) {
  30285. switch (poscounter) {
  30286. case 0:
  30287. p1 = point;
  30288. break;
  30289. case 1:
  30290. p2 = point;
  30291. break;
  30292. case 2:
  30293. indices.push(point.index + positionscount);
  30294. indices.push(p2.index + positionscount);
  30295. indices.push(p1.index + positionscount);
  30296. poscounter = -1;
  30297. break;
  30298. }
  30299. poscounter++;
  30300. //indices.push((<IndexedVector2>point).index + positionscount);
  30301. });
  30302. });
  30303. //Add the sides
  30304. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30305. this._holes.forEach(function (hole) {
  30306. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30307. });
  30308. }
  30309. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  30310. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  30311. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  30312. result.setIndices(indices);
  30313. return result;
  30314. };
  30315. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30316. var StartIndex = positions.length / 3;
  30317. var ulength = 0;
  30318. for (var i = 0; i < points.elements.length; i++) {
  30319. var p = points.elements[i];
  30320. var p1;
  30321. if ((i + 1) > points.elements.length - 1) {
  30322. p1 = points.elements[0];
  30323. }
  30324. else {
  30325. p1 = points.elements[i + 1];
  30326. }
  30327. positions.push(p.x, 0, p.y);
  30328. positions.push(p.x, -depth, p.y);
  30329. positions.push(p1.x, 0, p1.y);
  30330. positions.push(p1.x, -depth, p1.y);
  30331. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30332. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30333. var v3 = v2.subtract(v1);
  30334. var v4 = new BABYLON.Vector3(0, 1, 0);
  30335. var vn = BABYLON.Vector3.Cross(v3, v4);
  30336. vn = vn.normalize();
  30337. uvs.push(ulength / bounds.width, 0);
  30338. uvs.push(ulength / bounds.width, 1);
  30339. ulength += v3.length();
  30340. uvs.push((ulength / bounds.width), 0);
  30341. uvs.push((ulength / bounds.width), 1);
  30342. if (!flip) {
  30343. normals.push(-vn.x, -vn.y, -vn.z);
  30344. normals.push(-vn.x, -vn.y, -vn.z);
  30345. normals.push(-vn.x, -vn.y, -vn.z);
  30346. normals.push(-vn.x, -vn.y, -vn.z);
  30347. indices.push(StartIndex);
  30348. indices.push(StartIndex + 1);
  30349. indices.push(StartIndex + 2);
  30350. indices.push(StartIndex + 1);
  30351. indices.push(StartIndex + 3);
  30352. indices.push(StartIndex + 2);
  30353. }
  30354. else {
  30355. normals.push(vn.x, vn.y, vn.z);
  30356. normals.push(vn.x, vn.y, vn.z);
  30357. normals.push(vn.x, vn.y, vn.z);
  30358. normals.push(vn.x, vn.y, vn.z);
  30359. indices.push(StartIndex);
  30360. indices.push(StartIndex + 2);
  30361. indices.push(StartIndex + 1);
  30362. indices.push(StartIndex + 1);
  30363. indices.push(StartIndex + 2);
  30364. indices.push(StartIndex + 3);
  30365. }
  30366. StartIndex += 4;
  30367. }
  30368. ;
  30369. };
  30370. return PolygonMeshBuilder;
  30371. })();
  30372. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30373. })(BABYLON || (BABYLON = {}));
  30374. //# sourceMappingURL=babylon.polygonMesh.js.map
  30375. var BABYLON;
  30376. (function (BABYLON) {
  30377. var SimplificationSettings = (function () {
  30378. function SimplificationSettings(quality, distance, optimizeMesh) {
  30379. this.quality = quality;
  30380. this.distance = distance;
  30381. this.optimizeMesh = optimizeMesh;
  30382. }
  30383. return SimplificationSettings;
  30384. })();
  30385. BABYLON.SimplificationSettings = SimplificationSettings;
  30386. var SimplificationQueue = (function () {
  30387. function SimplificationQueue() {
  30388. this.running = false;
  30389. this._simplificationArray = [];
  30390. }
  30391. SimplificationQueue.prototype.addTask = function (task) {
  30392. this._simplificationArray.push(task);
  30393. };
  30394. SimplificationQueue.prototype.executeNext = function () {
  30395. var task = this._simplificationArray.pop();
  30396. if (task) {
  30397. this.running = true;
  30398. this.runSimplification(task);
  30399. }
  30400. else {
  30401. this.running = false;
  30402. }
  30403. };
  30404. SimplificationQueue.prototype.runSimplification = function (task) {
  30405. var _this = this;
  30406. if (task.parallelProcessing) {
  30407. //parallel simplifier
  30408. task.settings.forEach(function (setting) {
  30409. var simplifier = _this.getSimplifier(task);
  30410. simplifier.simplify(setting, function (newMesh) {
  30411. task.mesh.addLODLevel(setting.distance, newMesh);
  30412. newMesh.isVisible = true;
  30413. //check if it is the last
  30414. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30415. //all done, run the success callback.
  30416. task.successCallback();
  30417. }
  30418. _this.executeNext();
  30419. });
  30420. });
  30421. }
  30422. else {
  30423. //single simplifier.
  30424. var simplifier = this.getSimplifier(task);
  30425. var runDecimation = function (setting, callback) {
  30426. simplifier.simplify(setting, function (newMesh) {
  30427. task.mesh.addLODLevel(setting.distance, newMesh);
  30428. newMesh.isVisible = true;
  30429. //run the next quality level
  30430. callback();
  30431. });
  30432. };
  30433. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30434. runDecimation(task.settings[loop.index], function () {
  30435. loop.executeNext();
  30436. });
  30437. }, function () {
  30438. //execution ended, run the success callback.
  30439. if (task.successCallback) {
  30440. task.successCallback();
  30441. }
  30442. _this.executeNext();
  30443. });
  30444. }
  30445. };
  30446. SimplificationQueue.prototype.getSimplifier = function (task) {
  30447. switch (task.simplificationType) {
  30448. case SimplificationType.QUADRATIC:
  30449. default:
  30450. return new QuadraticErrorSimplification(task.mesh);
  30451. }
  30452. };
  30453. return SimplificationQueue;
  30454. })();
  30455. BABYLON.SimplificationQueue = SimplificationQueue;
  30456. /**
  30457. * The implemented types of simplification.
  30458. * At the moment only Quadratic Error Decimation is implemented.
  30459. */
  30460. (function (SimplificationType) {
  30461. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30462. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30463. var SimplificationType = BABYLON.SimplificationType;
  30464. var DecimationTriangle = (function () {
  30465. function DecimationTriangle(vertices) {
  30466. this.vertices = vertices;
  30467. this.error = new Array(4);
  30468. this.deleted = false;
  30469. this.isDirty = false;
  30470. this.deletePending = false;
  30471. this.borderFactor = 0;
  30472. }
  30473. return DecimationTriangle;
  30474. })();
  30475. BABYLON.DecimationTriangle = DecimationTriangle;
  30476. var DecimationVertex = (function () {
  30477. function DecimationVertex(position, id) {
  30478. this.position = position;
  30479. this.id = id;
  30480. this.isBorder = true;
  30481. this.q = new QuadraticMatrix();
  30482. this.triangleCount = 0;
  30483. this.triangleStart = 0;
  30484. this.originalOffsets = [];
  30485. }
  30486. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30487. this.position.copyFrom(newPosition);
  30488. };
  30489. return DecimationVertex;
  30490. })();
  30491. BABYLON.DecimationVertex = DecimationVertex;
  30492. var QuadraticMatrix = (function () {
  30493. function QuadraticMatrix(data) {
  30494. this.data = new Array(10);
  30495. for (var i = 0; i < 10; ++i) {
  30496. if (data && data[i]) {
  30497. this.data[i] = data[i];
  30498. }
  30499. else {
  30500. this.data[i] = 0;
  30501. }
  30502. }
  30503. }
  30504. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30505. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30506. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30507. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30508. return det;
  30509. };
  30510. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30511. for (var i = 0; i < 10; ++i) {
  30512. this.data[i] += matrix.data[i];
  30513. }
  30514. };
  30515. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30516. for (var i = 0; i < 10; ++i) {
  30517. this.data[i] += data[i];
  30518. }
  30519. };
  30520. QuadraticMatrix.prototype.add = function (matrix) {
  30521. var m = new QuadraticMatrix();
  30522. for (var i = 0; i < 10; ++i) {
  30523. m.data[i] = this.data[i] + matrix.data[i];
  30524. }
  30525. return m;
  30526. };
  30527. QuadraticMatrix.FromData = function (a, b, c, d) {
  30528. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30529. };
  30530. //returning an array to avoid garbage collection
  30531. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30532. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30533. };
  30534. return QuadraticMatrix;
  30535. })();
  30536. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30537. var Reference = (function () {
  30538. function Reference(vertexId, triangleId) {
  30539. this.vertexId = vertexId;
  30540. this.triangleId = triangleId;
  30541. }
  30542. return Reference;
  30543. })();
  30544. BABYLON.Reference = Reference;
  30545. /**
  30546. * An implementation of the Quadratic Error simplification algorithm.
  30547. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30548. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30549. * @author RaananW
  30550. */
  30551. var QuadraticErrorSimplification = (function () {
  30552. function QuadraticErrorSimplification(_mesh) {
  30553. this._mesh = _mesh;
  30554. this.initialized = false;
  30555. this.syncIterations = 5000;
  30556. this.aggressiveness = 7;
  30557. this.decimationIterations = 100;
  30558. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30559. }
  30560. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30561. var _this = this;
  30562. this.initDecimatedMesh();
  30563. //iterating through the submeshes array, one after the other.
  30564. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30565. _this.initWithMesh(loop.index, function () {
  30566. _this.runDecimation(settings, loop.index, function () {
  30567. loop.executeNext();
  30568. });
  30569. }, settings.optimizeMesh);
  30570. }, function () {
  30571. setTimeout(function () {
  30572. successCallback(_this._reconstructedMesh);
  30573. }, 0);
  30574. });
  30575. };
  30576. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30577. var _this = this;
  30578. var gCount = 0;
  30579. triangle.vertices.forEach(function (vertex) {
  30580. var count = 0;
  30581. var vPos = vertex.position;
  30582. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30583. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30584. ++count;
  30585. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30586. ++count;
  30587. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30588. ++count;
  30589. if (count > 1) {
  30590. ++gCount;
  30591. }
  30592. ;
  30593. });
  30594. if (gCount > 1) {
  30595. console.log(triangle, gCount);
  30596. }
  30597. return gCount > 1;
  30598. };
  30599. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30600. var _this = this;
  30601. var targetCount = ~~(this.triangles.length * settings.quality);
  30602. var deletedTriangles = 0;
  30603. var triangleCount = this.triangles.length;
  30604. var iterationFunction = function (iteration, callback) {
  30605. setTimeout(function () {
  30606. if (iteration % 5 === 0) {
  30607. _this.updateMesh(iteration === 0);
  30608. }
  30609. for (var i = 0; i < _this.triangles.length; ++i) {
  30610. _this.triangles[i].isDirty = false;
  30611. }
  30612. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30613. var trianglesIterator = function (i) {
  30614. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30615. var t = _this.triangles[tIdx];
  30616. if (!t)
  30617. return;
  30618. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30619. return;
  30620. }
  30621. for (var j = 0; j < 3; ++j) {
  30622. if (t.error[j] < threshold) {
  30623. var deleted0 = [];
  30624. var deleted1 = [];
  30625. var v0 = t.vertices[j];
  30626. var v1 = t.vertices[(j + 1) % 3];
  30627. if (v0.isBorder !== v1.isBorder)
  30628. continue;
  30629. var p = BABYLON.Vector3.Zero();
  30630. var n = BABYLON.Vector3.Zero();
  30631. var uv = BABYLON.Vector2.Zero();
  30632. var color = new BABYLON.Color4(0, 0, 0, 1);
  30633. _this.calculateError(v0, v1, p, n, uv, color);
  30634. var delTr = [];
  30635. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30636. continue;
  30637. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30638. continue;
  30639. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30640. continue;
  30641. var uniqueArray = [];
  30642. delTr.forEach(function (deletedT) {
  30643. if (uniqueArray.indexOf(deletedT) === -1) {
  30644. deletedT.deletePending = true;
  30645. uniqueArray.push(deletedT);
  30646. }
  30647. });
  30648. if (uniqueArray.length % 2 != 0) {
  30649. continue;
  30650. }
  30651. v0.q = v1.q.add(v0.q);
  30652. v0.updatePosition(p);
  30653. var tStart = _this.references.length;
  30654. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30655. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30656. var tCount = _this.references.length - tStart;
  30657. if (tCount <= v0.triangleCount) {
  30658. if (tCount) {
  30659. for (var c = 0; c < tCount; c++) {
  30660. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30661. }
  30662. }
  30663. }
  30664. else {
  30665. v0.triangleStart = tStart;
  30666. }
  30667. v0.triangleCount = tCount;
  30668. break;
  30669. }
  30670. }
  30671. };
  30672. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30673. }, 0);
  30674. };
  30675. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30676. if (triangleCount - deletedTriangles <= targetCount)
  30677. loop.breakLoop();
  30678. else {
  30679. iterationFunction(loop.index, function () {
  30680. loop.executeNext();
  30681. });
  30682. }
  30683. }, function () {
  30684. setTimeout(function () {
  30685. //reconstruct this part of the mesh
  30686. _this.reconstructMesh(submeshIndex);
  30687. successCallback();
  30688. }, 0);
  30689. });
  30690. };
  30691. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30692. var _this = this;
  30693. this.vertices = [];
  30694. this.triangles = [];
  30695. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30696. var indices = this._mesh.getIndices();
  30697. var submesh = this._mesh.subMeshes[submeshIndex];
  30698. var findInVertices = function (positionToSearch) {
  30699. if (optimizeMesh) {
  30700. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30701. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30702. return _this.vertices[ii];
  30703. }
  30704. }
  30705. }
  30706. return null;
  30707. };
  30708. var vertexReferences = [];
  30709. var vertexInit = function (i) {
  30710. var offset = i + submesh.verticesStart;
  30711. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30712. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30713. vertex.originalOffsets.push(offset);
  30714. if (vertex.id == _this.vertices.length) {
  30715. _this.vertices.push(vertex);
  30716. }
  30717. vertexReferences.push(vertex.id);
  30718. };
  30719. //var totalVertices = mesh.getTotalVertices();
  30720. var totalVertices = submesh.verticesCount;
  30721. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30722. var indicesInit = function (i) {
  30723. var offset = (submesh.indexStart / 3) + i;
  30724. var pos = (offset * 3);
  30725. var i0 = indices[pos + 0];
  30726. var i1 = indices[pos + 1];
  30727. var i2 = indices[pos + 2];
  30728. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30729. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30730. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30731. var triangle = new DecimationTriangle([v0, v1, v2]);
  30732. triangle.originalOffset = pos;
  30733. _this.triangles.push(triangle);
  30734. };
  30735. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30736. _this.init(callback);
  30737. });
  30738. });
  30739. };
  30740. QuadraticErrorSimplification.prototype.init = function (callback) {
  30741. var _this = this;
  30742. var triangleInit1 = function (i) {
  30743. var t = _this.triangles[i];
  30744. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30745. for (var j = 0; j < 3; j++) {
  30746. 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))));
  30747. }
  30748. };
  30749. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30750. var triangleInit2 = function (i) {
  30751. var t = _this.triangles[i];
  30752. for (var j = 0; j < 3; ++j) {
  30753. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30754. }
  30755. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30756. };
  30757. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30758. _this.initialized = true;
  30759. callback();
  30760. });
  30761. });
  30762. };
  30763. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30764. var newTriangles = [];
  30765. var i;
  30766. for (i = 0; i < this.vertices.length; ++i) {
  30767. this.vertices[i].triangleCount = 0;
  30768. }
  30769. var t;
  30770. var j;
  30771. for (i = 0; i < this.triangles.length; ++i) {
  30772. if (!this.triangles[i].deleted) {
  30773. t = this.triangles[i];
  30774. for (j = 0; j < 3; ++j) {
  30775. t.vertices[j].triangleCount = 1;
  30776. }
  30777. newTriangles.push(t);
  30778. }
  30779. }
  30780. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30781. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30782. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30783. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30784. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30785. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30786. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30787. var vertexCount = 0;
  30788. for (i = 0; i < this.vertices.length; ++i) {
  30789. var vertex = this.vertices[i];
  30790. vertex.id = vertexCount;
  30791. if (vertex.triangleCount) {
  30792. vertex.originalOffsets.forEach(function (originalOffset) {
  30793. newPositionData.push(vertex.position.x);
  30794. newPositionData.push(vertex.position.y);
  30795. newPositionData.push(vertex.position.z);
  30796. newNormalData.push(normalData[originalOffset * 3]);
  30797. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30798. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30799. if (uvs && uvs.length) {
  30800. newUVsData.push(uvs[(originalOffset * 2)]);
  30801. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30802. }
  30803. else if (colorsData && colorsData.length) {
  30804. newColorsData.push(colorsData[(originalOffset * 4)]);
  30805. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30806. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30807. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30808. }
  30809. ++vertexCount;
  30810. });
  30811. }
  30812. }
  30813. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30814. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30815. var submeshesArray = this._reconstructedMesh.subMeshes;
  30816. this._reconstructedMesh.subMeshes = [];
  30817. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30818. var originalIndices = this._mesh.getIndices();
  30819. for (i = 0; i < newTriangles.length; ++i) {
  30820. var t = newTriangles[i];
  30821. //now get the new referencing point for each vertex
  30822. [0, 1, 2].forEach(function (idx) {
  30823. var id = originalIndices[t.originalOffset + idx];
  30824. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30825. if (offset < 0)
  30826. offset = 0;
  30827. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30828. });
  30829. }
  30830. //overwriting the old vertex buffers and indices.
  30831. this._reconstructedMesh.setIndices(newIndicesArray);
  30832. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30833. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30834. if (newUVsData.length > 0)
  30835. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30836. if (newColorsData.length > 0)
  30837. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30838. //create submesh
  30839. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30840. if (submeshIndex > 0) {
  30841. this._reconstructedMesh.subMeshes = [];
  30842. submeshesArray.forEach(function (submesh) {
  30843. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30844. });
  30845. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30846. }
  30847. };
  30848. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30849. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30850. this._reconstructedMesh.material = this._mesh.material;
  30851. this._reconstructedMesh.parent = this._mesh.parent;
  30852. this._reconstructedMesh.isVisible = false;
  30853. };
  30854. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30855. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30856. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30857. if (t.deleted)
  30858. continue;
  30859. var s = this.references[vertex1.triangleStart + i].vertexId;
  30860. var v1 = t.vertices[(s + 1) % 3];
  30861. var v2 = t.vertices[(s + 2) % 3];
  30862. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30863. deletedArray[i] = true;
  30864. delTr.push(t);
  30865. continue;
  30866. }
  30867. var d1 = v1.position.subtract(point);
  30868. d1 = d1.normalize();
  30869. var d2 = v2.position.subtract(point);
  30870. d2 = d2.normalize();
  30871. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30872. return true;
  30873. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30874. deletedArray[i] = false;
  30875. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30876. return true;
  30877. }
  30878. return false;
  30879. };
  30880. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30881. var newDeleted = deletedTriangles;
  30882. for (var i = 0; i < vertex.triangleCount; ++i) {
  30883. var ref = this.references[vertex.triangleStart + i];
  30884. var t = this.triangles[ref.triangleId];
  30885. if (t.deleted)
  30886. continue;
  30887. if (deletedArray[i] && t.deletePending) {
  30888. t.deleted = true;
  30889. newDeleted++;
  30890. continue;
  30891. }
  30892. t.vertices[ref.vertexId] = origVertex;
  30893. t.isDirty = true;
  30894. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30895. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30896. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30897. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30898. this.references.push(ref);
  30899. }
  30900. return newDeleted;
  30901. };
  30902. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30903. for (var i = 0; i < this.vertices.length; ++i) {
  30904. var vCount = [];
  30905. var vId = [];
  30906. var v = this.vertices[i];
  30907. var j;
  30908. for (j = 0; j < v.triangleCount; ++j) {
  30909. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30910. for (var ii = 0; ii < 3; ii++) {
  30911. var ofs = 0;
  30912. var vv = triangle.vertices[ii];
  30913. while (ofs < vCount.length) {
  30914. if (vId[ofs] === vv.id)
  30915. break;
  30916. ++ofs;
  30917. }
  30918. if (ofs === vCount.length) {
  30919. vCount.push(1);
  30920. vId.push(vv.id);
  30921. }
  30922. else {
  30923. vCount[ofs]++;
  30924. }
  30925. }
  30926. }
  30927. for (j = 0; j < vCount.length; ++j) {
  30928. if (vCount[j] === 1) {
  30929. this.vertices[vId[j]].isBorder = true;
  30930. }
  30931. else {
  30932. this.vertices[vId[j]].isBorder = false;
  30933. }
  30934. }
  30935. }
  30936. };
  30937. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30938. if (identifyBorders === void 0) { identifyBorders = false; }
  30939. var i;
  30940. if (!identifyBorders) {
  30941. var newTrianglesVector = [];
  30942. for (i = 0; i < this.triangles.length; ++i) {
  30943. if (!this.triangles[i].deleted) {
  30944. newTrianglesVector.push(this.triangles[i]);
  30945. }
  30946. }
  30947. this.triangles = newTrianglesVector;
  30948. }
  30949. for (i = 0; i < this.vertices.length; ++i) {
  30950. this.vertices[i].triangleCount = 0;
  30951. this.vertices[i].triangleStart = 0;
  30952. }
  30953. var t;
  30954. var j;
  30955. var v;
  30956. for (i = 0; i < this.triangles.length; ++i) {
  30957. t = this.triangles[i];
  30958. for (j = 0; j < 3; ++j) {
  30959. v = t.vertices[j];
  30960. v.triangleCount++;
  30961. }
  30962. }
  30963. var tStart = 0;
  30964. for (i = 0; i < this.vertices.length; ++i) {
  30965. this.vertices[i].triangleStart = tStart;
  30966. tStart += this.vertices[i].triangleCount;
  30967. this.vertices[i].triangleCount = 0;
  30968. }
  30969. var newReferences = new Array(this.triangles.length * 3);
  30970. for (i = 0; i < this.triangles.length; ++i) {
  30971. t = this.triangles[i];
  30972. for (j = 0; j < 3; ++j) {
  30973. v = t.vertices[j];
  30974. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30975. v.triangleCount++;
  30976. }
  30977. }
  30978. this.references = newReferences;
  30979. if (identifyBorders) {
  30980. this.identifyBorder();
  30981. }
  30982. };
  30983. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30984. var x = point.x;
  30985. var y = point.y;
  30986. var z = point.z;
  30987. 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
  30988. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30989. };
  30990. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30991. var q = vertex1.q.add(vertex2.q);
  30992. var border = vertex1.isBorder && vertex2.isBorder;
  30993. var error = 0;
  30994. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30995. if (qDet !== 0 && !border) {
  30996. if (!pointResult) {
  30997. pointResult = BABYLON.Vector3.Zero();
  30998. }
  30999. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31000. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31001. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31002. error = this.vertexError(q, pointResult);
  31003. }
  31004. else {
  31005. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31006. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31007. var error1 = this.vertexError(q, vertex1.position);
  31008. var error2 = this.vertexError(q, vertex2.position);
  31009. var error3 = this.vertexError(q, p3);
  31010. error = Math.min(error1, error2, error3);
  31011. if (error === error1) {
  31012. if (pointResult) {
  31013. pointResult.copyFrom(vertex1.position);
  31014. }
  31015. }
  31016. else if (error === error2) {
  31017. if (pointResult) {
  31018. pointResult.copyFrom(vertex2.position);
  31019. }
  31020. }
  31021. else {
  31022. if (pointResult) {
  31023. pointResult.copyFrom(p3);
  31024. }
  31025. }
  31026. }
  31027. return error;
  31028. };
  31029. return QuadraticErrorSimplification;
  31030. })();
  31031. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31032. })(BABYLON || (BABYLON = {}));
  31033. //# sourceMappingURL=babylon.meshSimplification.js.map
  31034. var BABYLON;
  31035. (function (BABYLON) {
  31036. var Analyser = (function () {
  31037. function Analyser(scene) {
  31038. this.SMOOTHING = 0.75;
  31039. this.FFT_SIZE = 512;
  31040. this.BARGRAPHAMPLITUDE = 256;
  31041. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  31042. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  31043. this._scene = scene;
  31044. this._audioEngine = BABYLON.Engine.audioEngine;
  31045. if (this._audioEngine.canUseWebAudio) {
  31046. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  31047. this._webAudioAnalyser.minDecibels = -140;
  31048. this._webAudioAnalyser.maxDecibels = 0;
  31049. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31050. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31051. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  31052. }
  31053. }
  31054. Analyser.prototype.getFrequencyBinCount = function () {
  31055. if (this._audioEngine.canUseWebAudio) {
  31056. return this._webAudioAnalyser.frequencyBinCount;
  31057. }
  31058. else {
  31059. return 0;
  31060. }
  31061. };
  31062. Analyser.prototype.getByteFrequencyData = function () {
  31063. if (this._audioEngine.canUseWebAudio) {
  31064. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31065. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31066. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  31067. }
  31068. return this._byteFreqs;
  31069. };
  31070. Analyser.prototype.getByteTimeDomainData = function () {
  31071. if (this._audioEngine.canUseWebAudio) {
  31072. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31073. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31074. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  31075. }
  31076. return this._byteTime;
  31077. };
  31078. Analyser.prototype.getFloatFrequencyData = function () {
  31079. if (this._audioEngine.canUseWebAudio) {
  31080. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31081. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31082. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  31083. }
  31084. return this._floatFreqs;
  31085. };
  31086. Analyser.prototype.drawDebugCanvas = function () {
  31087. var _this = this;
  31088. if (this._audioEngine.canUseWebAudio) {
  31089. if (!this._debugCanvas) {
  31090. this._debugCanvas = document.createElement("canvas");
  31091. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  31092. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  31093. this._debugCanvas.style.position = "absolute";
  31094. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  31095. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  31096. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  31097. document.body.appendChild(this._debugCanvas);
  31098. this._registerFunc = function () {
  31099. _this.drawDebugCanvas();
  31100. };
  31101. this._scene.registerBeforeRender(this._registerFunc);
  31102. }
  31103. if (this._registerFunc) {
  31104. var workingArray = this.getByteFrequencyData();
  31105. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  31106. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  31107. // Draw the frequency domain chart.
  31108. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  31109. var value = workingArray[i];
  31110. var percent = value / this.BARGRAPHAMPLITUDE;
  31111. var height = this.DEBUGCANVASSIZE.height * percent;
  31112. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  31113. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  31114. var hue = i / this.getFrequencyBinCount() * 360;
  31115. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  31116. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  31117. }
  31118. }
  31119. }
  31120. };
  31121. Analyser.prototype.stopDebugCanvas = function () {
  31122. if (this._debugCanvas) {
  31123. this._scene.unregisterBeforeRender(this._registerFunc);
  31124. this._registerFunc = null;
  31125. document.body.removeChild(this._debugCanvas);
  31126. this._debugCanvas = null;
  31127. this._debugCanvasContext = null;
  31128. }
  31129. };
  31130. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  31131. if (this._audioEngine.canUseWebAudio) {
  31132. inputAudioNode.connect(this._webAudioAnalyser);
  31133. this._webAudioAnalyser.connect(outputAudioNode);
  31134. }
  31135. };
  31136. Analyser.prototype.dispose = function () {
  31137. if (this._audioEngine.canUseWebAudio) {
  31138. this._webAudioAnalyser.disconnect();
  31139. }
  31140. };
  31141. return Analyser;
  31142. })();
  31143. BABYLON.Analyser = Analyser;
  31144. })(BABYLON || (BABYLON = {}));
  31145. //# sourceMappingURL=babylon.analyser.js.map
  31146. var BABYLON;
  31147. (function (BABYLON) {
  31148. var DepthRenderer = (function () {
  31149. function DepthRenderer(scene, type) {
  31150. var _this = this;
  31151. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  31152. this._viewMatrix = BABYLON.Matrix.Zero();
  31153. this._projectionMatrix = BABYLON.Matrix.Zero();
  31154. this._transformMatrix = BABYLON.Matrix.Zero();
  31155. this._worldViewProjection = BABYLON.Matrix.Zero();
  31156. this._scene = scene;
  31157. var engine = scene.getEngine();
  31158. // Render target
  31159. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  31160. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31161. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31162. this._depthMap.refreshRate = 1;
  31163. this._depthMap.renderParticles = false;
  31164. this._depthMap.renderList = null;
  31165. // set default depth value to 1.0 (far away)
  31166. this._depthMap.onClear = function (engine) {
  31167. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  31168. };
  31169. // Custom render function
  31170. var renderSubMesh = function (subMesh) {
  31171. var mesh = subMesh.getRenderingMesh();
  31172. var scene = _this._scene;
  31173. var engine = scene.getEngine();
  31174. // Culling
  31175. engine.setState(subMesh.getMaterial().backFaceCulling);
  31176. // Managing instances
  31177. var batch = mesh._getInstancesRenderList(subMesh._id);
  31178. if (batch.mustReturn) {
  31179. return;
  31180. }
  31181. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31182. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31183. engine.enableEffect(_this._effect);
  31184. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  31185. var material = subMesh.getMaterial();
  31186. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31187. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  31188. // Alpha test
  31189. if (material && material.needAlphaTesting()) {
  31190. var alphaTexture = material.getAlphaTestTexture();
  31191. _this._effect.setTexture("diffuseSampler", alphaTexture);
  31192. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31193. }
  31194. // Bones
  31195. if (mesh.useBones) {
  31196. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31197. }
  31198. // Draw
  31199. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  31200. }
  31201. };
  31202. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  31203. var index;
  31204. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31205. renderSubMesh(opaqueSubMeshes.data[index]);
  31206. }
  31207. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31208. renderSubMesh(alphaTestSubMeshes.data[index]);
  31209. }
  31210. };
  31211. }
  31212. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  31213. var defines = [];
  31214. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31215. var mesh = subMesh.getMesh();
  31216. var scene = mesh.getScene();
  31217. var material = subMesh.getMaterial();
  31218. // Alpha test
  31219. if (material && material.needAlphaTesting()) {
  31220. defines.push("#define ALPHATEST");
  31221. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31222. attribs.push(BABYLON.VertexBuffer.UVKind);
  31223. defines.push("#define UV1");
  31224. }
  31225. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31226. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31227. defines.push("#define UV2");
  31228. }
  31229. }
  31230. // Bones
  31231. if (mesh.useBones) {
  31232. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31233. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31234. defines.push("#define BONES");
  31235. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31236. }
  31237. // Instances
  31238. if (useInstances) {
  31239. defines.push("#define INSTANCES");
  31240. attribs.push("world0");
  31241. attribs.push("world1");
  31242. attribs.push("world2");
  31243. attribs.push("world3");
  31244. }
  31245. // Get correct effect
  31246. var join = defines.join("\n");
  31247. if (this._cachedDefines !== join) {
  31248. this._cachedDefines = join;
  31249. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  31250. }
  31251. return this._effect.isReady();
  31252. };
  31253. DepthRenderer.prototype.getDepthMap = function () {
  31254. return this._depthMap;
  31255. };
  31256. // Methods
  31257. DepthRenderer.prototype.dispose = function () {
  31258. this._depthMap.dispose();
  31259. };
  31260. return DepthRenderer;
  31261. })();
  31262. BABYLON.DepthRenderer = DepthRenderer;
  31263. })(BABYLON || (BABYLON = {}));
  31264. //# sourceMappingURL=babylon.depthRenderer.js.map
  31265. var __extends = (this && this.__extends) || function (d, b) {
  31266. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31267. function __() { this.constructor = d; }
  31268. __.prototype = b.prototype;
  31269. d.prototype = new __();
  31270. };
  31271. var BABYLON;
  31272. (function (BABYLON) {
  31273. var SSAORenderingPipeline = (function (_super) {
  31274. __extends(SSAORenderingPipeline, _super);
  31275. /**
  31276. * @constructor
  31277. * @param {string} name - The rendering pipeline name
  31278. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31279. * @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 }
  31280. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31281. */
  31282. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  31283. var _this = this;
  31284. _super.call(this, scene.getEngine(), name);
  31285. // Members
  31286. /**
  31287. * The PassPostProcess id in the pipeline that contains the original scene color
  31288. * @type {string}
  31289. */
  31290. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  31291. /**
  31292. * The SSAO PostProcess id in the pipeline
  31293. * @type {string}
  31294. */
  31295. this.SSAORenderEffect = "SSAORenderEffect";
  31296. /**
  31297. * The horizontal blur PostProcess id in the pipeline
  31298. * @type {string}
  31299. */
  31300. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  31301. /**
  31302. * The vertical blur PostProcess id in the pipeline
  31303. * @type {string}
  31304. */
  31305. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  31306. /**
  31307. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  31308. * @type {string}
  31309. */
  31310. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31311. /**
  31312. * The output strength of the SSAO post-process. Default value is 1.0.
  31313. * @type {number}
  31314. */
  31315. this.totalStrength = 1.0;
  31316. /**
  31317. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31318. * @type {number}
  31319. */
  31320. this.radius = 0.0002;
  31321. /**
  31322. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31323. * Must not be equal to fallOff and superior to fallOff.
  31324. * Default value is 0.0075
  31325. * @type {number}
  31326. */
  31327. this.area = 0.0075;
  31328. /**
  31329. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31330. * Must not be equal to area and inferior to area.
  31331. * Default value is 0.0002
  31332. * @type {number}
  31333. */
  31334. this.fallOff = 0.0002;
  31335. this._firstUpdate = true;
  31336. this._scene = scene;
  31337. // Set up assets
  31338. this._createRandomTexture();
  31339. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31340. var ssaoRatio = ratio.ssaoRatio || ratio;
  31341. var combineRatio = ratio.combineRatio || ratio;
  31342. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31343. this._createSSAOPostProcess(ssaoRatio);
  31344. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31345. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31346. this._createSSAOCombinePostProcess(combineRatio);
  31347. // Set up pipeline
  31348. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  31349. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  31350. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  31351. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  31352. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  31353. // Finish
  31354. scene.postProcessRenderPipelineManager.addPipeline(this);
  31355. if (cameras)
  31356. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31357. }
  31358. // Public Methods
  31359. /**
  31360. * Returns the horizontal blur PostProcess
  31361. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31362. */
  31363. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31364. return this._blurHPostProcess;
  31365. };
  31366. /**
  31367. * Returns the vertical blur PostProcess
  31368. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31369. */
  31370. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31371. return this._blurVPostProcess;
  31372. };
  31373. /**
  31374. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31375. */
  31376. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31377. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31378. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31379. this._originalColorPostProcess = undefined;
  31380. this._ssaoPostProcess = undefined;
  31381. this._blurHPostProcess = undefined;
  31382. this._blurVPostProcess = undefined;
  31383. this._ssaoCombinePostProcess = undefined;
  31384. this._randomTexture.dispose();
  31385. if (disableDepthRender)
  31386. this._scene.disableDepthRenderer();
  31387. };
  31388. // Private Methods
  31389. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31390. var _this = this;
  31391. var sampleSphere = [
  31392. 0.5381, 0.1856, -0.4319,
  31393. 0.1379, 0.2486, 0.4430,
  31394. 0.3371, 0.5679, -0.0057,
  31395. -0.6999, -0.0451, -0.0019,
  31396. 0.0689, -0.1598, -0.8547,
  31397. 0.0560, 0.0069, -0.1843,
  31398. -0.0146, 0.1402, 0.0762,
  31399. 0.0100, -0.1924, -0.0344,
  31400. -0.3577, -0.5301, -0.4358,
  31401. -0.3169, 0.1063, 0.0158,
  31402. 0.0103, -0.5869, 0.0046,
  31403. -0.0897, -0.4940, 0.3287,
  31404. 0.7119, -0.0154, -0.0918,
  31405. -0.0533, 0.0596, -0.5411,
  31406. 0.0352, -0.0631, 0.5460,
  31407. -0.4776, 0.2847, -0.0271
  31408. ];
  31409. var samplesFactor = 1.0 / 16.0;
  31410. 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);
  31411. this._ssaoPostProcess.onApply = function (effect) {
  31412. if (_this._firstUpdate) {
  31413. effect.setArray3("sampleSphere", sampleSphere);
  31414. effect.setFloat("samplesFactor", samplesFactor);
  31415. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31416. _this._firstUpdate = false;
  31417. }
  31418. effect.setFloat("totalStrength", _this.totalStrength);
  31419. effect.setFloat("radius", _this.radius);
  31420. effect.setFloat("area", _this.area);
  31421. effect.setFloat("fallOff", _this.fallOff);
  31422. effect.setTexture("textureSampler", _this._depthTexture);
  31423. effect.setTexture("randomSampler", _this._randomTexture);
  31424. };
  31425. };
  31426. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31427. var _this = this;
  31428. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31429. this._ssaoCombinePostProcess.onApply = function (effect) {
  31430. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31431. };
  31432. };
  31433. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31434. var size = 512;
  31435. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31436. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31437. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31438. var context = this._randomTexture.getContext();
  31439. var rand = function (min, max) {
  31440. return Math.random() * (max - min) + min;
  31441. };
  31442. for (var x = 0; x < size; x++) {
  31443. for (var y = 0; y < size; y++) {
  31444. var randVector = BABYLON.Vector3.Zero();
  31445. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31446. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31447. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31448. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31449. context.fillRect(x, y, 1, 1);
  31450. }
  31451. }
  31452. this._randomTexture.update(false);
  31453. };
  31454. return SSAORenderingPipeline;
  31455. })(BABYLON.PostProcessRenderPipeline);
  31456. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31457. })(BABYLON || (BABYLON = {}));
  31458. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31459. var __extends = (this && this.__extends) || function (d, b) {
  31460. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31461. function __() { this.constructor = d; }
  31462. __.prototype = b.prototype;
  31463. d.prototype = new __();
  31464. };
  31465. var BABYLON;
  31466. (function (BABYLON) {
  31467. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31468. var VolumetricLightScatteringPostProcess = (function (_super) {
  31469. __extends(VolumetricLightScatteringPostProcess, _super);
  31470. /**
  31471. * @constructor
  31472. * @param {string} name - The post-process name
  31473. * @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)
  31474. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31475. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31476. * @param {number} samples - The post-process quality, default 100
  31477. * @param {number} samplingMode - The post-process filtering mode
  31478. * @param {BABYLON.Engine} engine - The babylon engine
  31479. * @param {boolean} reusable - If the post-process is reusable
  31480. */
  31481. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31482. var _this = this;
  31483. if (samples === void 0) { samples = 100; }
  31484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31485. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31486. this._screenCoordinates = BABYLON.Vector2.Zero();
  31487. /**
  31488. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31489. * @type {boolean}
  31490. */
  31491. this.useCustomMeshPosition = false;
  31492. /**
  31493. * If the post-process should inverse the light scattering direction
  31494. * @type {boolean}
  31495. */
  31496. this.invert = true;
  31497. /**
  31498. * Array containing the excluded meshes not rendered in the internal pass
  31499. */
  31500. this.excludedMeshes = new Array();
  31501. this.exposure = 0.3;
  31502. this.decay = 0.96815;
  31503. this.weight = 0.58767;
  31504. this.density = 0.926;
  31505. var scene = camera.getScene();
  31506. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31507. // Configure mesh
  31508. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31509. // Configure
  31510. this._createPass(scene, ratio.passRatio || ratio);
  31511. this.onApply = function (effect) {
  31512. _this._updateMeshScreenCoordinates(scene);
  31513. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31514. effect.setFloat("exposure", _this.exposure);
  31515. effect.setFloat("decay", _this.decay);
  31516. effect.setFloat("weight", _this.weight);
  31517. effect.setFloat("density", _this.density);
  31518. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31519. };
  31520. }
  31521. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31522. var mesh = subMesh.getMesh();
  31523. var defines = [];
  31524. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31525. var material = subMesh.getMaterial();
  31526. var needUV = false;
  31527. // Render this.mesh as default
  31528. if (mesh === this.mesh) {
  31529. defines.push("#define BASIC_RENDER");
  31530. defines.push("#define NEED_UV");
  31531. needUV = true;
  31532. }
  31533. // Alpha test
  31534. if (material) {
  31535. if (material.needAlphaTesting() || mesh === this.mesh)
  31536. defines.push("#define ALPHATEST");
  31537. if (material.opacityTexture !== undefined) {
  31538. defines.push("#define OPACITY");
  31539. if (material.opacityTexture.getAlphaFromRGB)
  31540. defines.push("#define OPACITYRGB");
  31541. if (!needUV)
  31542. defines.push("#define NEED_UV");
  31543. }
  31544. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31545. attribs.push(BABYLON.VertexBuffer.UVKind);
  31546. defines.push("#define UV1");
  31547. }
  31548. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31549. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31550. defines.push("#define UV2");
  31551. }
  31552. }
  31553. // Bones
  31554. if (mesh.useBones) {
  31555. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31556. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31557. defines.push("#define BONES");
  31558. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31559. }
  31560. // Instances
  31561. if (useInstances) {
  31562. defines.push("#define INSTANCES");
  31563. attribs.push("world0");
  31564. attribs.push("world1");
  31565. attribs.push("world2");
  31566. attribs.push("world3");
  31567. }
  31568. // Get correct effect
  31569. var join = defines.join("\n");
  31570. if (this._cachedDefines !== join) {
  31571. this._cachedDefines = join;
  31572. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31573. }
  31574. return this._volumetricLightScatteringPass.isReady();
  31575. };
  31576. /**
  31577. * Sets the new light position for light scattering effect
  31578. * @param {BABYLON.Vector3} The new custom light position
  31579. */
  31580. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31581. this._customMeshPosition = position;
  31582. };
  31583. /**
  31584. * Returns the light position for light scattering effect
  31585. * @return {BABYLON.Vector3} The custom light position
  31586. */
  31587. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31588. return this._customMeshPosition;
  31589. };
  31590. /**
  31591. * Disposes the internal assets and detaches the post-process from the camera
  31592. */
  31593. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31594. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31595. if (rttIndex !== -1) {
  31596. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31597. }
  31598. this._volumetricLightScatteringRTT.dispose();
  31599. _super.prototype.dispose.call(this, camera);
  31600. };
  31601. /**
  31602. * Returns the render target texture used by the post-process
  31603. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31604. */
  31605. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31606. return this._volumetricLightScatteringRTT;
  31607. };
  31608. // Private methods
  31609. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31610. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31611. return true;
  31612. }
  31613. return false;
  31614. };
  31615. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31616. var _this = this;
  31617. var engine = scene.getEngine();
  31618. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31619. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31620. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31621. this._volumetricLightScatteringRTT.renderList = null;
  31622. this._volumetricLightScatteringRTT.renderParticles = false;
  31623. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31624. // Custom render function for submeshes
  31625. var renderSubMesh = function (subMesh) {
  31626. var mesh = subMesh.getRenderingMesh();
  31627. if (_this._meshExcluded(mesh)) {
  31628. return;
  31629. }
  31630. var scene = mesh.getScene();
  31631. var engine = scene.getEngine();
  31632. // Culling
  31633. engine.setState(subMesh.getMaterial().backFaceCulling);
  31634. // Managing instances
  31635. var batch = mesh._getInstancesRenderList(subMesh._id);
  31636. if (batch.mustReturn) {
  31637. return;
  31638. }
  31639. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31640. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31641. engine.enableEffect(_this._volumetricLightScatteringPass);
  31642. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31643. var material = subMesh.getMaterial();
  31644. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31645. // Alpha test
  31646. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31647. var alphaTexture = material.getAlphaTestTexture();
  31648. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31649. if (alphaTexture) {
  31650. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31651. }
  31652. if (material.opacityTexture !== undefined) {
  31653. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31654. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31655. }
  31656. }
  31657. // Bones
  31658. if (mesh.useBones) {
  31659. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31660. }
  31661. // Draw
  31662. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31663. }
  31664. };
  31665. // Render target texture callbacks
  31666. var savedSceneClearColor;
  31667. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31668. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31669. savedSceneClearColor = scene.clearColor;
  31670. scene.clearColor = sceneClearColor;
  31671. };
  31672. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31673. scene.clearColor = savedSceneClearColor;
  31674. };
  31675. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31676. var engine = scene.getEngine();
  31677. var index;
  31678. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31679. renderSubMesh(opaqueSubMeshes.data[index]);
  31680. }
  31681. engine.setAlphaTesting(true);
  31682. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31683. renderSubMesh(alphaTestSubMeshes.data[index]);
  31684. }
  31685. engine.setAlphaTesting(false);
  31686. if (transparentSubMeshes.length) {
  31687. // Sort sub meshes
  31688. for (index = 0; index < transparentSubMeshes.length; index++) {
  31689. var submesh = transparentSubMeshes.data[index];
  31690. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31691. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31692. }
  31693. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31694. sortedArray.sort(function (a, b) {
  31695. // Alpha index first
  31696. if (a._alphaIndex > b._alphaIndex) {
  31697. return 1;
  31698. }
  31699. if (a._alphaIndex < b._alphaIndex) {
  31700. return -1;
  31701. }
  31702. // Then distance to camera
  31703. if (a._distanceToCamera < b._distanceToCamera) {
  31704. return 1;
  31705. }
  31706. if (a._distanceToCamera > b._distanceToCamera) {
  31707. return -1;
  31708. }
  31709. return 0;
  31710. });
  31711. // Render sub meshes
  31712. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31713. for (index = 0; index < sortedArray.length; index++) {
  31714. renderSubMesh(sortedArray[index]);
  31715. }
  31716. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31717. }
  31718. };
  31719. };
  31720. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31721. var transform = scene.getTransformMatrix();
  31722. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31723. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31724. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31725. if (this.invert)
  31726. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31727. };
  31728. // Static methods
  31729. /**
  31730. * Creates a default mesh for the Volumeric Light Scattering post-process
  31731. * @param {string} The mesh name
  31732. * @param {BABYLON.Scene} The scene where to create the mesh
  31733. * @return {BABYLON.Mesh} the default mesh
  31734. */
  31735. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31736. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31737. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31738. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31739. return mesh;
  31740. };
  31741. return VolumetricLightScatteringPostProcess;
  31742. })(BABYLON.PostProcess);
  31743. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31744. })(BABYLON || (BABYLON = {}));
  31745. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31746. var __extends = (this && this.__extends) || function (d, b) {
  31747. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31748. function __() { this.constructor = d; }
  31749. __.prototype = b.prototype;
  31750. d.prototype = new __();
  31751. };
  31752. var BABYLON;
  31753. (function (BABYLON) {
  31754. var LensRenderingPipeline = (function (_super) {
  31755. __extends(LensRenderingPipeline, _super);
  31756. /**
  31757. * @constructor
  31758. *
  31759. * Effect parameters are as follow:
  31760. * {
  31761. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31762. * edge_blur: number; // from 0 to x (1 for realism)
  31763. * distortion: number; // from 0 to x (1 for realism)
  31764. * grain_amount: number; // from 0 to 1
  31765. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31766. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31767. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31768. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31769. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31770. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31771. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31772. * }
  31773. * Note: if an effect parameter is unset, effect is disabled
  31774. *
  31775. * @param {string} name - The rendering pipeline name
  31776. * @param {object} parameters - An object containing all parameters (see above)
  31777. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31778. * @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)
  31779. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31780. */
  31781. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31782. var _this = this;
  31783. if (ratio === void 0) { ratio = 1.0; }
  31784. _super.call(this, scene.getEngine(), name);
  31785. // Lens effects can be of the following:
  31786. // - chromatic aberration (slight shift of RGB colors)
  31787. // - blur on the edge of the lens
  31788. // - lens distortion
  31789. // - depth-of-field blur & highlights enhancing
  31790. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31791. // - grain effect (noise or custom texture)
  31792. // Two additional texture samplers are needed:
  31793. // - depth map (for depth-of-field)
  31794. // - grain texture
  31795. /**
  31796. * The chromatic aberration PostProcess id in the pipeline
  31797. * @type {string}
  31798. */
  31799. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31800. /**
  31801. * The highlights enhancing PostProcess id in the pipeline
  31802. * @type {string}
  31803. */
  31804. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31805. /**
  31806. * The depth-of-field PostProcess id in the pipeline
  31807. * @type {string}
  31808. */
  31809. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31810. this._scene = scene;
  31811. // Fetch texture samplers
  31812. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31813. if (parameters.grain_texture) {
  31814. this._grainTexture = parameters.grain_texture;
  31815. }
  31816. else {
  31817. this._createGrainTexture();
  31818. }
  31819. // save parameters
  31820. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31821. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31822. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31823. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31824. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31825. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31826. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31827. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31828. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31829. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31830. // Create effects
  31831. this._createChromaticAberrationPostProcess(ratio);
  31832. this._createHighlightsPostProcess(ratio);
  31833. this._createDepthOfFieldPostProcess(ratio);
  31834. // Set up pipeline
  31835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31836. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31838. if (this._highlightsGain == -1) {
  31839. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31840. }
  31841. // Finish
  31842. scene.postProcessRenderPipelineManager.addPipeline(this);
  31843. if (cameras) {
  31844. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31845. }
  31846. }
  31847. // public methods (self explanatory)
  31848. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31849. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31850. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31851. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31852. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31853. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31854. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31855. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31856. LensRenderingPipeline.prototype.setFocusDepth = function (amount) { this._dofDepth = amount; };
  31857. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDepth = -1; };
  31858. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31859. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31860. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31861. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31862. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31863. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31864. this._highlightsGain = amount;
  31865. };
  31866. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31867. if (this._highlightsGain == -1) {
  31868. this._highlightsGain = 1.0;
  31869. }
  31870. this._highlightsThreshold = amount;
  31871. };
  31872. LensRenderingPipeline.prototype.disableHighlights = function () {
  31873. this._highlightsGain = -1;
  31874. };
  31875. /**
  31876. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31877. */
  31878. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31879. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31880. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31881. this._chromaticAberrationPostProcess = undefined;
  31882. this._highlightsPostProcess = undefined;
  31883. this._depthOfFieldPostProcess = undefined;
  31884. this._grainTexture.dispose();
  31885. if (disableDepthRender)
  31886. this._scene.disableDepthRenderer();
  31887. };
  31888. // colors shifting and distortion
  31889. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31890. var _this = this;
  31891. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31892. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31893. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31894. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31895. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31896. };
  31897. };
  31898. // highlights enhancing
  31899. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31900. var _this = this;
  31901. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31902. this._highlightsPostProcess.onApply = function (effect) {
  31903. effect.setFloat('gain', _this._highlightsGain);
  31904. effect.setFloat('threshold', _this._highlightsThreshold);
  31905. effect.setBool('pentagon', _this._dofPentagon);
  31906. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31907. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31908. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31909. };
  31910. };
  31911. // colors shifting and distortion
  31912. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31913. var _this = this;
  31914. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31915. "focus_depth", "aperture", "pentagon", "maxZ", "edge_blur", "chromatic_aberration",
  31916. "distortion", "blur_noise", "grain_amount", "screen_width", "screen_height", "highlights"
  31917. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31918. this._depthOfFieldPostProcess.onApply = function (effect) {
  31919. effect.setBool('blur_noise', _this._blurNoise);
  31920. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31921. effect.setFloat('grain_amount', _this._grainAmount);
  31922. effect.setTexture("depthSampler", _this._depthTexture);
  31923. effect.setTexture("grainSampler", _this._grainTexture);
  31924. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31925. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31926. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31927. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31928. effect.setFloat('distortion', _this._distortion);
  31929. effect.setFloat('focus_depth', _this._dofDepth);
  31930. effect.setFloat('aperture', _this._dofAperture);
  31931. effect.setFloat('edge_blur', _this._edgeBlur);
  31932. effect.setBool('highlights', (_this._highlightsGain != -1));
  31933. };
  31934. };
  31935. // creates a black and white random noise texture, 512x512
  31936. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31937. var size = 512;
  31938. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31939. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31940. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31941. var context = this._grainTexture.getContext();
  31942. var rand = function (min, max) {
  31943. return Math.random() * (max - min) + min;
  31944. };
  31945. var value;
  31946. for (var x = 0; x < size; x++) {
  31947. for (var y = 0; y < size; y++) {
  31948. value = Math.floor(rand(0.42, 0.58) * 255);
  31949. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31950. context.fillRect(x, y, 1, 1);
  31951. }
  31952. }
  31953. this._grainTexture.update(false);
  31954. };
  31955. return LensRenderingPipeline;
  31956. })(BABYLON.PostProcessRenderPipeline);
  31957. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31958. })(BABYLON || (BABYLON = {}));
  31959. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31960. //
  31961. // This post-process allows the modification of rendered colors by using
  31962. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31963. //
  31964. // The object needs to be provided an url to a texture containing the color
  31965. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31966. // Use an image editing software to tweak the LUT to match your needs.
  31967. //
  31968. // For an example of a color LUT, see here:
  31969. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31970. // For explanations on color grading, see here:
  31971. // http://udn.epicgames.com/Three/ColorGrading.html
  31972. //
  31973. var __extends = (this && this.__extends) || function (d, b) {
  31974. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31975. function __() { this.constructor = d; }
  31976. __.prototype = b.prototype;
  31977. d.prototype = new __();
  31978. };
  31979. var BABYLON;
  31980. (function (BABYLON) {
  31981. var ColorCorrectionPostProcess = (function (_super) {
  31982. __extends(ColorCorrectionPostProcess, _super);
  31983. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31984. var _this = this;
  31985. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31986. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31987. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31988. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31989. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31990. this.onApply = function (effect) {
  31991. effect.setTexture("colorTable", _this._colorTableTexture);
  31992. };
  31993. }
  31994. return ColorCorrectionPostProcess;
  31995. })(BABYLON.PostProcess);
  31996. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31997. })(BABYLON || (BABYLON = {}));
  31998. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31999. var __extends = (this && this.__extends) || function (d, b) {
  32000. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  32001. function __() { this.constructor = d; }
  32002. __.prototype = b.prototype;
  32003. d.prototype = new __();
  32004. };
  32005. var BABYLON;
  32006. (function (BABYLON) {
  32007. var StereoscopicFreeCamera = (function (_super) {
  32008. __extends(StereoscopicFreeCamera, _super);
  32009. function StereoscopicFreeCamera(name, position, eyeSpace, isVertical, scene) {
  32010. _super.call(this, name, position, scene);
  32011. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  32012. }
  32013. return StereoscopicFreeCamera;
  32014. })(BABYLON.FreeCamera);
  32015. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  32016. var StereoscopicArcRotateCamera = (function (_super) {
  32017. __extends(StereoscopicArcRotateCamera, _super);
  32018. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, isVertical, scene) {
  32019. _super.call(this, name, alpha, beta, radius, target, scene);
  32020. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  32021. }
  32022. return StereoscopicArcRotateCamera;
  32023. })(BABYLON.ArcRotateCamera);
  32024. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  32025. var StereoscopicGamepadCamera = (function (_super) {
  32026. __extends(StereoscopicGamepadCamera, _super);
  32027. function StereoscopicGamepadCamera(name, position, eyeSpace, isVertical, scene) {
  32028. _super.call(this, name, position, scene);
  32029. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  32030. }
  32031. return StereoscopicGamepadCamera;
  32032. })(BABYLON.GamepadCamera);
  32033. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  32034. })(BABYLON || (BABYLON = {}));
  32035. //# sourceMappingURL=babylon.stereoscopicCamera.js.map
  32036. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 skyColor;\r\nuniform vec3 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec3 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = vec4(c, 1);\r\n\r\n}","colorPixelShader":"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n\tgl_FragColor = color;\n}","colorVertexShader":"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn visibility;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn 1.0 - ChebychevInequality(moments, depth.z, bias);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., vSpecularColor.a));\r\n\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n\tresult.specular = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\tresult.specular = specComp * specularColor;\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform float maxZ;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform float focus_depth;\r\nuniform float aperture;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI 3.14159265\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(vec2 coords, float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = min(3.0, ceil(size / 1.0));\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\r\n\ttotal_weight += 8.18;\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\r\n\t\ttotal_weight += 5.96;\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\r\n\t\ttotal_weight += 2.97;\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\tcol.a = 1.0;\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b = 0.0; }\r\n\t// if(blur_level == 2.0) { col.r = 0.0; }\r\n\t// if(blur_level == 3.0) { col.g = 0.0; }\r\n\r\n\treturn col;\r\n}\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\r\n\tvec4 final_color;\r\n\tvec2 distorted_coords = getDistortedCoords(vUV);\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\t// blur from depth of field effect\r\n\tfloat dof_blur_amount = 0.0;\r\n\tfloat depth_bias = 0.0;\t\t// positive if the pixel is further than focus depth; negative if closer\r\n\tif (focus_depth != -1.0) {\r\n\t\tvec4 depth_sample = texture2D(depthSampler, distorted_coords);\r\n\t\tfloat depth = depth_sample.r;\r\n\t\tdepth_bias = depth - focus_depth;\r\n\r\n\t\t// compute blur amount with distance\r\n\t\tif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\r\n\t\telse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\r\n\r\n\t\tif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; }\t// no blur at all\r\n\t}\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\r\n\r\n\t\t// if further than focus depth & we have computed highlights: enhance highlights\r\n\t\tif (depth_bias > 0.0 && highlights) {\r\n\t\t\tgl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\r\n\t}\r\n}","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\t#ifndef BASIC_RENDER\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = diffuseColor;\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  32037. 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.id))}},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,r){return new t(i/255,o/255,r/255)},t.Lerp=function(i,o,r){var n=i.r+(o.r-i.r)*r,s=i.g+(o.g-i.g)*r,e=i.b+(o.b-i.b)*r;return new t(n,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,r){this.r=t,this.g=i,this.b=o,this.a=r}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,r){var n=new t(0,0,0,0);return t.LerpToRef(i,o,r,n),n},t.LerpToRef=function(t,i,o,r){r.r=t.r+(i.r-t.r)*o,r.g=t.g+(i.g-t.g)*o,r.b=t.b+(i.b-t.b)*o,r.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,r,n){return new t(i/255,o/255,r/255,n/255)},t}();t.Color4=o;var r=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,r,n,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+r.x)*s+(2*t.x-5*o.x+4*r.x-n.x)*e+(-t.x+3*o.x-3*r.x+n.x)*a),u=.5*(2*o.y+(-t.y+r.y)*s+(2*t.y-5*o.y+4*r.y-n.y)*e+(-t.y+3*o.y-3*r.y+n.y)*a);return new i(h,u)},i.Clamp=function(t,o,r){var n=t.x;n=n>r.x?r.x:n,n=n<o.x?o.x:n;var s=t.y;return s=s>r.y?r.y:s,s=s<o.y?o.y:s,new i(n,s)},i.Hermite=function(t,o,r,n,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+r.x*u+o.x*l+n.x*m,x=t.y*h+r.y*u+o.y*l+n.y*m;return new i(f,x)},i.Lerp=function(t,o,r){var n=t.x+(o.x-t.x)*r,s=t.y+(o.y-t.y)*r;return new i(n,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 r=t.x<o.x?t.x:o.x,n=t.y<o.y?t.y:o.y;return new i(r,n)},i.Maximize=function(t,o){var r=t.x>o.x?t.x:o.x,n=t.y>o.y?t.y:o.y;return new i(r,n)},i.Transform=function(t,o){var r=t.x*o.m[0]+t.y*o.m[4],n=t.x*o.m[1]+t.y*o.m[5];return new i(r,n)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,r=t.y-i.y;return o*o+r*r},i}();t.Vector2=r;var n=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)),r=Math.cos(.5*(this.z-this.x)),n=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=r*a,t.y=-n*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,r){return new i(this.x-t,this.y-o,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,r){return r.x=this.x-t,r.y=this.y-i,r.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,r){return new i(this.x*t,this.y*o,this.z*r)},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,r,n){var s=i.Dot(t,r)-n,e=i.Dot(o,r)-n,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,r){r.x=t,r.y=i,r.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 r=i.Zero();return i.TransformCoordinatesToRef(t,o,r),r},i.TransformCoordinatesToRef=function(t,i,o){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],n=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=r/e,o.y=n/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,r,n){var s=t*r.m[0]+i*r.m[4]+o*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+o*r.m[9]+r.m[13],a=t*r.m[2]+i*r.m[6]+o*r.m[10]+r.m[14],h=t*r.m[3]+i*r.m[7]+o*r.m[11]+r.m[15];n.x=s/h,n.y=e/h,n.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var r=SIMD.float32x4.loadXYZ(t._data,0),n=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(r,0,0,0,0),n),SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(r,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,r,n){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(r.m,0),u=SIMD.float32x4.load(r.m,4),l=SIMD.float32x4.load(r.m,8),m=SIMD.float32x4.load(r.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(n._data,0,f)},i.TransformNormal=function(t,o){var r=i.Zero();return i.TransformNormalToRef(t,o,r),r},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,r,n){n.x=t*r.m[0]+i*r.m[4]+o*r.m[8],n.y=t*r.m[1]+i*r.m[5]+o*r.m[9],n.z=t*r.m[2]+i*r.m[6]+o*r.m[10]},i.CatmullRom=function(t,o,r,n,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+r.x)*s+(2*t.x-5*o.x+4*r.x-n.x)*e+(-t.x+3*o.x-3*r.x+n.x)*a),u=.5*(2*o.y+(-t.y+r.y)*s+(2*t.y-5*o.y+4*r.y-n.y)*e+(-t.y+3*o.y-3*r.y+n.y)*a),l=.5*(2*o.z+(-t.z+r.z)*s+(2*t.z-5*o.z+4*r.z-n.z)*e+(-t.z+3*o.z-3*r.z+n.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,r){var n=t.x;n=n>r.x?r.x:n,n=n<o.x?o.x:n;var s=t.y;s=s>r.y?r.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<o.z?o.z:e,new i(n,s,e)},i.Hermite=function(t,o,r,n,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+r.x*u+o.x*l+n.x*m,x=t.y*h+r.y*u+o.y*l+n.y*m,y=t.z*h+r.z*u+o.z*l+n.z*m;return new i(f,x,y)},i.Lerp=function(t,o,r){var n=t.x+(o.x-t.x)*r,s=t.y+(o.y-t.y)*r,e=t.z+(o.z-t.z)*r;return new i(n,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 r=i.Zero();return i.CrossToRef(t,o,r),r},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,r,n){var s=n.width,e=n.height,h=n.x,u=n.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(r).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,r,n,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/r*2-1,o.y=-(o.y/n*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,r,n,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/r*2-1,o.y=-(o.y/n*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,r=t.y-i.y,n=t.z-i.z;return o*o+r*r+n*n},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(o,r,n){var s,e,a,h=i.Normalize(o),u=(i.Normalize(r),i.Normalize(n)),l=f.X,m=f.Y,x=(f.Z,0),y=0,c=0,p=0,z=0,M=0,w=0,I=-1,d=(Math.PI,0),D=0;0==u.z?M=1:0==u.x?p=1:(w=u.z/u.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),e=new i(p,z,M),a=i.Cross(u,e),s=i.Cross(h,e),i.Dot(u,s)<0&&(I=1),D=i.Dot(h,e),c=Math.acos(D)*I,i.Dot(e,l)<0&&(c=Math.PI+c,e=e.scaleInPlace(-1),a=a.scaleInPlace(-1),d++);var S,v;return p=0,z=0,M=0,I=-1,0==u.z?p=1:(w=e.z/e.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),S=new t.Vector3(p,z,M),v=t.Vector3.Cross(S,e),s=t.Vector3.Cross(u,S),t.Vector3.Dot(e,s)<0&&(I=1),D=t.Vector3.Dot(u,S),y=Math.acos(D)*I,t.Vector3.Dot(v,m)<0&&(y=Math.PI+y,v=v.scaleInPlace(-1),S=S.scaleInPlace(-1),d++),I=-1,s=t.Vector3.Cross(l,e),t.Vector3.Dot(s,m)<0&&(I=1),D=t.Vector3.Dot(e,l),x=-Math.acos(D)*I,0>D&&2>d&&(x=Math.PI+x),new t.Vector3(y,x,c)},i}();t.Vector3=n;var s=function(){function i(t,i,o,r){this.x=t,this.y=i,this.z=o,this.w=r}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,r,n){return new i(this.x-t,this.y-o,this.z-r,this.w-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,n.w=this.w-r,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,r){return this.x===t&&this.y===i&&this.z===o&&this.w===r},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,r,n){return new i(this.x*t,this.y*o,this.z*r,this.w*n)},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,r){return this.x=t,this.y=i,this.z=o,this.w=r,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,r,n){n.x=t,n.y=i,n.z=o,n.w=r},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,r=t.y-i.y,n=t.z-i.z,s=t.w-i.w;return o*o+r*r+n*n+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,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=o,this.w=r}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,r){return this.x=t,this.y=i,this.z=o,this.w=r,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,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,n=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,r,n,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=n.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,r=this.z,n=this.w,s=i*o,e=i*r,a=n*o,h=n*r,u=n*i,l=o*r,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-r*r)):(t.x=Math.atan2(s-h,.5-f-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,r=this.z*this.z,n=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+r),t.m[1]=2*(n+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(n-s),t.m[5]=1-2*(r+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,r=t.m,n=r[0],s=r[4],e=r[8],a=r[1],h=r[5],u=r[9],l=r[2],m=r[6],f=r[10],x=n+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):n>h&&n>f?(o=2*Math.sqrt(1+n-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-n-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-n-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 r=new t,n=Math.sin(o/2);return r.w=Math.cos(o/2),r.x=i.x*n,r.y=i.y*n,r.z=i.z*n,r},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,r){var n=new t;return t.RotationYawPitchRollToRef(i,o,r,n),n},t.RotationYawPitchRollToRef=function(t,i,o,r){var n=.5*o,s=.5*i,e=.5*t,a=Math.sin(n),h=Math.cos(n),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);r.x=f*u*h+m*l*a,r.y=m*l*h-f*u*a,r.z=f*l*a-m*u*h,r.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,r){var n=new t;return t.RotationAlphaBetaGammaToRef(i,o,r,n),n},t.RotationAlphaBetaGammaToRef=function(t,i,o,r){var n=.5*(o+t),s=.5*(o-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(n)*Math.cos(e),r.w=Math.cos(n)*Math.cos(e)},t.Slerp=function(i,o,r){var n,s,e=r,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,n=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,n=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+n*o.x,s*i.y+n*o.y,s*i.z+n*o.z,s*i.w+n*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],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],n=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]*r+this.m[7]*n)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*n+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],r=this.m[2],n=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+r*g+n*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,V=e*m-a*l,E=s*f-h*u,Z=s*m-a*u,N=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-r*M+n*w)*R,t.m[5]=(i*z-r*I+n*d)*R,t.m[9]=-(i*M-o*I+n*D)*R,t.m[13]=(i*w-o*d+r*D)*R,t.m[2]=(o*_-r*b+n*A)*R,t.m[6]=-(i*_-r*F+n*P)*R,t.m[10]=(i*b-o*F+n*C)*R,t.m[14]=-(i*A-o*P+r*C)*R,t.m[3]=-(o*L-r*q+n*V)*R,t.m[7]=(i*L-r*E+n*Z)*R,t.m[11]=-(i*q-o*E+n*N)*R,t.m[15]=(i*V-o*Z+r*N)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,r,n,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),n=SIMD.float32x4.shuffle(c,p,2,3,6,7),r=SIMD.float32x4.shuffle(s,n,0,2,4,6),n=SIMD.float32x4.shuffle(n,s,1,3,5,7),s=SIMD.float32x4.mul(r,n),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,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,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(n,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),n),s=SIMD.float32x4.swizzle(s,1,0,3,2),r=SIMD.float32x4.swizzle(r,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,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(r,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(n,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(r,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,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(r,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,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(n,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 r=this.m[0],n=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]=r*w+n*S+s*R+e*F,i[o+1]=r*I+n*v+s*_+e*P,i[o+2]=r*d+n*g+s*b+e*C,i[o+3]=r*D+n*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 r=this.m,n=t.m,s=SIMD.float32x4.load(n,0),e=SIMD.float32x4.load(n,4),a=SIMD.float32x4.load(n,8),h=SIMD.float32x4.load(n,12),u=SIMD.float32x4.load(r,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(r,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(r,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(r,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]);\n\n},i.prototype.decompose=function(o,r,n){n.x=this.m[12],n.y=this.m[13],n.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 r.x=0,r.y=0,r.z=0,r.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,r),!0},i.FromArray=function(t,o){var r=new i;return o||(o=0),i.FromArrayToRef(t,o,r),r},i.FromArrayToRef=function(t,i,o){for(var r=0;16>r;r++)o.m[r]=t[r+i]},i.FromValuesToRef=function(t,i,o,r,n,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]=r,p.m[4]=n,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,r,n,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]=r,z.m[3]=n,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,r){var n=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),n=n.multiply(s),n.setTranslation(r),n},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),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,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),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-o,i.m[8]=o,i.m[10]=r,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),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=o,i.m[4]=-o,i.m[5]=r,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 r=Math.sin(-o),n=Math.cos(-o),s=1-n;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+n,e.m[1]=t.x*t.y*s-t.z*r,e.m[2]=t.x*t.z*s+t.y*r,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*r,e.m[5]=t.y*t.y*s+n,e.m[6]=t.y*t.z*s-t.x*r,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*r,e.m[9]=t.z*t.y*s+t.x*r,e.m[10]=t.z*t.z*s+n,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,r){var n=new i;return i.RotationYawPitchRollToRef(t,o,r,n),n},i.RotationYawPitchRollToRef=function(t,i,o,r){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,o,r){var n=i.Zero();return i.ScalingToRef(t,o,r,n),n},i.ScalingToRef=function(t,i,o,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=o,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,o,r){var n=i.Identity();return i.TranslationToRef(t,o,r,n),n},i.TranslationToRef=function(t,o,r,n){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,r,1,n)},i.LookAtLH=function(t,o,r){var n=i.Zero();return i.LookAtLHToRef(t,o,r,n),n},i.LookAtLHToRef=function(t,o,r,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),n.CrossToRef(r,this._zAxis,this._xAxis),this._xAxis.normalize(),n.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-n.Dot(this._xAxis,t),a=-n.Dot(this._yAxis,t),h=-n.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,r){var n=r.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(n,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(n,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(n,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(n,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,r,n){var s=i.Zero();return i.OrthoLHToRef(t,o,r,n,s),s},i.OrthoLHToRef=function(t,o,r,n,s){var e=2/t,a=2/o,h=1/(n-r),u=r/(r-n);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,r,n,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,r,n,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,r,n,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(n-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+o)/(o-r),e.m[14]=n/(n-s),e.m[15]=1},i.PerspectiveLH=function(t,o,r,n){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-n/(r-n),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*n/(r-n),s},i.PerspectiveFovLH=function(t,o,r,n){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,r,n,s),s},i.PerspectiveFovLHToRef=function(i,o,r,n,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]=-n/(r-n),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*n/(r-n)},i.GetFinalMatrix=function(t,o,r,n,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(r).multiply(n).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,r=t.normal.y,n=t.normal.z,s=-2*o,e=-2*r,a=-2*n;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=a*r,i.m[7]=0,i.m[8]=s*n,i.m[9]=e*n,i.m[10]=a*n+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=n.Zero(),i._yAxis=n.Zero(),i._zAxis=n.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,r){this.normal=new n(t,i,o),this.d=r}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),r=this.normal.x,n=this.normal.y,s=this.normal.z,e=this.d,h=r*o.m[0]+n*o.m[1]+s*o.m[2]+e*o.m[3],u=r*o.m[4]+n*o.m[5]+s*o.m[6]+e*o.m[7],l=r*o.m[8]+n*o.m[9]+s*o.m[10]+e*o.m[11],m=r*o.m[12]+n*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 r,n=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-n*u,f=n*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return r=0!==x?1/x:0,this.normal.x=l*r,this.normal.y=m*r,this.normal.z=f*r,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=n.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return n.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,r){var n=new t(0,0,0,0);return n.copyFromPoints(i,o,r),n},t.FromPositionAndNormal=function(i,o){var r=new t(0,0,0,0);return o.normalize(),r.normal=o,r.d=-(o.x*i.x+o.y*i.y+o.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return n.Dot(o,i)+r},t}();t.Plane=h;var u=function(){function t(t,i,o,r){this.x=t,this.y=i,this.width=o,this.height=r}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*o,this.y*r,this.width*o,this.height*r)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],r=0;6>r;r++)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,r=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 n=1/this.direction.x,s=(t.x-this.origin.x)*n,e=(i.x-this.origin.x)*n;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),r=Math.min(e,r),o>r)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(n=1/this.direction.y,s=(t.y-this.origin.y)*n,e=(i.y-this.origin.y)*n,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),r=Math.min(e,r),o>r)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(n=1/this.direction.z,s=(t.z-this.origin.z)*n,e=(i.z-this.origin.z)*n,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),r=Math.min(e,r),o>r)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,r=t.center.z-this.origin.z,n=i*i+o*o+r*r,s=t.radius*t.radius;if(s>=n)return!0;var e=i*this.direction.x+o*this.direction.y+r*this.direction.z;if(0>e)return!1;var a=n-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,r){this._edge1||(this._edge1=n.Zero(),this._edge2=n.Zero(),this._pvec=n.Zero(),this._tvec=n.Zero(),this._qvec=n.Zero()),o.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),n.CrossToRef(this.direction,this._edge2,this._pvec);var s=n.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=n.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;n.CrossToRef(this._tvec,this._edge1,this._qvec);var h=n.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=n.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,r,s,e,a,h){var u=n.Unproject(new n(t,o,0),r,s,e,a,h),l=n.Unproject(new n(t,o,1),r,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,r){void 0===r&&(r=a.Identity());var n=o.subtract(t),s=Math.sqrt(n.x*n.x+n.y*n.y+n.z*n.z);return n.normalize(),i.Transform(new i(t,n,s),r)},i.Transform=function(t,o){var r=n.TransformCoordinates(t.origin,o),s=n.TransformNormal(t.direction,o);return new i(r,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 n(1,0,0),t.Y=new n(0,1,0),t.Z=new n(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,r,n){for(var s=1-3*r+3*i,e=3*r-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)*n+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 r=o.subtract(i),n=Math.atan2(r.y,r.x);return new t(n)},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 n=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,e=(n-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 r((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 n(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 r(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var n=new r(i,o),s=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,n,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 r(i,o),u=new r(n,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.\"),r.Zero();for(var o=i*this.length(),n=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()+n;if(o>=n&&l>=o){var m=u.normalize(),f=o-n;return new r(a.x+m.x*f,a.y+m.y*f)}n=l}return t.Tools.Error(\"internal error\"),r.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],r=this._normalVector(this._curve[0],o,t);this._normals[0]=r,this._normals[0].normalize(),this._binormals[0]=n.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]=n.Cross(u,a),this._normals[l].normalize(),this._binormals[l]=n.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 r;if(void 0===o||null===o){var s;1!==i.y?s=new n(0,-1,0):1!==i.x?s=new n(1,0,0):1!==i.z&&(s=new n(0,0,1)),r=n.Cross(i,s)}else r=n.Cross(i,o),n.CrossToRef(r,i,r);return r.normalize(),r},t}();t.Path3D=w;var I=function(){function i(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return i.CreateQuadraticBezier=function(t,o,r,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,r){var n=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*r;return n},h=0;s>=h;h++)e.push(new n(a(h/s,t.x,o.x,r.x),a(h/s,t.y,o.y,r.y),a(h/s,t.z,o.z,r.z)));return new i(e)},i.CreateCubicBezier=function(t,o,r,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,r,n){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*r+t*t*t*n;return s},u=0;e>=u;u++)a.push(new n(h(u/e,t.x,o.x,r.x,s.x),h(u/e,t.y,o.y,r.y,s.y),h(u/e,t.z,o.z,r.z,s.z)));return new i(a)},i.CreateHermiteSpline=function(o,r,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(t.Vector3.Hermite(o,r,n,s,u*h));return new i(a)},i.prototype.getPoints=function(){return this._points},i.prototype.length=function(){return this._length},i.prototype[\"continue\"]=function(t){for(var o=this._points[this._points.length-1],r=this._points.slice(),n=t.getPoints(),s=1;s<n.length;s++)r.push(n[s].subtract(n[0]).add(o));var e=new i(r);return e},i.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},i}();t.Curve3=I;var d=function(){function t(t,i){void 0===t&&(t=n.Zero()),void 0===i&&(i=n.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=n.Zero()),void 0===i&&(i=n.Up()),void 0===o&&(o=r.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=n.TransformCoordinatesToRef,R=n.TransformCoordinatesFromFloatsToRef,_=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,n.TransformCoordinatesToRef=T,n.TransformCoordinatesFromFloatsToRef=R,i._isEnabled=!1},i.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,n.TransformCoordinatesToRef=n.TransformCoordinatesToRefSIMD,n.TransformCoordinatesFromFloatsToRef=n.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(t.Vector3.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(t.Vector3.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(t.Vector3.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),i._isEnabled=!0)},i._isEnabled=!1,i}();t.SIMDHelper=_,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&_.EnableSIMD()}(BABYLON||(BABYLON={}));";