babylon.2.1-rc.debug.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035
  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.__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.__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.__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.__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.__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.__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.__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.__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.__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.__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.__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.__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._keys = [];
  10757. this._viewMatrix = new BABYLON.Matrix();
  10758. this.checkCollisions = false;
  10759. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10760. this._collider = new BABYLON.Collider();
  10761. this._previousPosition = BABYLON.Vector3.Zero();
  10762. this._collisionVelocity = BABYLON.Vector3.Zero();
  10763. this._newPosition = BABYLON.Vector3.Zero();
  10764. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10765. if (collidedMesh === void 0) { collidedMesh = null; }
  10766. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10767. newPosition.multiplyInPlace(_this._collider.radius);
  10768. }
  10769. if (!collidedMesh) {
  10770. _this._previousPosition.copyFrom(_this.position);
  10771. _this.setPosition(_this._newPosition);
  10772. _this.position.copyFrom(_this._newPosition);
  10773. }
  10774. else {
  10775. _this.setPosition(_this._previousPosition);
  10776. _this.position.copyFrom(_this._previousPosition);
  10777. if (_this.onCollide) {
  10778. _this.onCollide(collidedMesh);
  10779. }
  10780. }
  10781. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._getTargetPosition(), _this.upVector, _this._viewMatrix);
  10782. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10783. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10784. _this._collisionTriggered = false;
  10785. };
  10786. if (!this.target) {
  10787. this.target = BABYLON.Vector3.Zero();
  10788. }
  10789. this.getViewMatrix();
  10790. }
  10791. ArcRotateCamera.prototype._getTargetPosition = function () {
  10792. return this.target.position || this.target;
  10793. };
  10794. // Cache
  10795. ArcRotateCamera.prototype._initCache = function () {
  10796. _super.prototype._initCache.call(this);
  10797. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10798. this._cache.alpha = undefined;
  10799. this._cache.beta = undefined;
  10800. this._cache.radius = undefined;
  10801. this._cache.targetScreenOffset = undefined;
  10802. };
  10803. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10804. if (!ignoreParentClass) {
  10805. _super.prototype._updateCache.call(this);
  10806. }
  10807. this._cache.target.copyFrom(this._getTargetPosition());
  10808. this._cache.alpha = this.alpha;
  10809. this._cache.beta = this.beta;
  10810. this._cache.radius = this.radius;
  10811. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10812. };
  10813. // Synchronized
  10814. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10815. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10816. return false;
  10817. return this._cache.target.equals(this._getTargetPosition())
  10818. && this._cache.alpha === this.alpha
  10819. && this._cache.beta === this.beta
  10820. && this._cache.radius === this.radius
  10821. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10822. };
  10823. // Methods
  10824. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10825. var _this = this;
  10826. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10827. var previousPinchDistance = 0;
  10828. var pointers = new BABYLON.SmartCollection();
  10829. if (this._attachedElement) {
  10830. return;
  10831. }
  10832. this._attachedElement = element;
  10833. var engine = this.getEngine();
  10834. if (this._onPointerDown === undefined) {
  10835. this._onPointerDown = function (evt) {
  10836. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10837. cacheSoloPointer = pointers.item(evt.pointerId);
  10838. if (!noPreventDefault) {
  10839. evt.preventDefault();
  10840. }
  10841. };
  10842. this._onPointerUp = function (evt) {
  10843. cacheSoloPointer = null;
  10844. previousPinchDistance = 0;
  10845. pointers.remove(evt.pointerId);
  10846. if (!noPreventDefault) {
  10847. evt.preventDefault();
  10848. }
  10849. };
  10850. this._onPointerMove = function (evt) {
  10851. if (!noPreventDefault) {
  10852. evt.preventDefault();
  10853. }
  10854. switch (pointers.count) {
  10855. case 1:
  10856. var offsetX = evt.clientX - cacheSoloPointer.x;
  10857. var offsetY = evt.clientY - cacheSoloPointer.y;
  10858. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10859. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10860. cacheSoloPointer.x = evt.clientX;
  10861. cacheSoloPointer.y = evt.clientY;
  10862. break;
  10863. case 2:
  10864. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10865. pointers.item(evt.pointerId).x = evt.clientX;
  10866. pointers.item(evt.pointerId).y = evt.clientY;
  10867. var direction = _this.pinchInwards ? 1 : -1;
  10868. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10869. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10870. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10871. if (previousPinchDistance === 0) {
  10872. previousPinchDistance = pinchSquaredDistance;
  10873. return;
  10874. }
  10875. if (pinchSquaredDistance !== previousPinchDistance) {
  10876. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10877. previousPinchDistance = pinchSquaredDistance;
  10878. }
  10879. break;
  10880. default:
  10881. if (pointers.item(evt.pointerId)) {
  10882. pointers.item(evt.pointerId).x = evt.clientX;
  10883. pointers.item(evt.pointerId).y = evt.clientY;
  10884. }
  10885. }
  10886. };
  10887. this._onMouseMove = function (evt) {
  10888. if (!engine.isPointerLock) {
  10889. return;
  10890. }
  10891. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10892. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10893. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10894. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10895. if (!noPreventDefault) {
  10896. evt.preventDefault();
  10897. }
  10898. };
  10899. this._wheel = function (event) {
  10900. var delta = 0;
  10901. if (event.wheelDelta) {
  10902. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10903. }
  10904. else if (event.detail) {
  10905. delta = -event.detail / _this.wheelPrecision;
  10906. }
  10907. if (delta)
  10908. _this.inertialRadiusOffset += delta;
  10909. if (event.preventDefault) {
  10910. if (!noPreventDefault) {
  10911. event.preventDefault();
  10912. }
  10913. }
  10914. };
  10915. this._onKeyDown = function (evt) {
  10916. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10917. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10918. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10919. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10920. var index = _this._keys.indexOf(evt.keyCode);
  10921. if (index === -1) {
  10922. _this._keys.push(evt.keyCode);
  10923. }
  10924. if (evt.preventDefault) {
  10925. if (!noPreventDefault) {
  10926. evt.preventDefault();
  10927. }
  10928. }
  10929. }
  10930. };
  10931. this._onKeyUp = function (evt) {
  10932. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10933. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10934. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10935. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10936. var index = _this._keys.indexOf(evt.keyCode);
  10937. if (index >= 0) {
  10938. _this._keys.splice(index, 1);
  10939. }
  10940. if (evt.preventDefault) {
  10941. if (!noPreventDefault) {
  10942. evt.preventDefault();
  10943. }
  10944. }
  10945. }
  10946. };
  10947. this._onLostFocus = function () {
  10948. _this._keys = [];
  10949. pointers.empty();
  10950. previousPinchDistance = 0;
  10951. cacheSoloPointer = null;
  10952. };
  10953. this._onGestureStart = function (e) {
  10954. if (window.MSGesture === undefined) {
  10955. return;
  10956. }
  10957. if (!_this._MSGestureHandler) {
  10958. _this._MSGestureHandler = new MSGesture();
  10959. _this._MSGestureHandler.target = element;
  10960. }
  10961. _this._MSGestureHandler.addPointer(e.pointerId);
  10962. };
  10963. this._onGesture = function (e) {
  10964. _this.radius *= e.scale;
  10965. if (e.preventDefault) {
  10966. if (!noPreventDefault) {
  10967. e.stopPropagation();
  10968. e.preventDefault();
  10969. }
  10970. }
  10971. };
  10972. this._reset = function () {
  10973. _this._keys = [];
  10974. _this.inertialAlphaOffset = 0;
  10975. _this.inertialBetaOffset = 0;
  10976. _this.inertialRadiusOffset = 0;
  10977. pointers.empty();
  10978. previousPinchDistance = 0;
  10979. cacheSoloPointer = null;
  10980. };
  10981. }
  10982. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10983. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10984. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10985. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10986. element.addEventListener("mousemove", this._onMouseMove, false);
  10987. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10988. element.addEventListener("MSGestureChange", this._onGesture, false);
  10989. element.addEventListener('mousewheel', this._wheel, false);
  10990. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10991. BABYLON.Tools.RegisterTopRootEvents([
  10992. { name: "keydown", handler: this._onKeyDown },
  10993. { name: "keyup", handler: this._onKeyUp },
  10994. { name: "blur", handler: this._onLostFocus }
  10995. ]);
  10996. };
  10997. ArcRotateCamera.prototype.detachControl = function (element) {
  10998. if (this._attachedElement !== element) {
  10999. return;
  11000. }
  11001. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11002. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11003. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11004. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11005. element.removeEventListener("mousemove", this._onMouseMove);
  11006. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11007. element.removeEventListener("MSGestureChange", this._onGesture);
  11008. element.removeEventListener('mousewheel', this._wheel);
  11009. element.removeEventListener('DOMMouseScroll', this._wheel);
  11010. BABYLON.Tools.UnregisterTopRootEvents([
  11011. { name: "keydown", handler: this._onKeyDown },
  11012. { name: "keyup", handler: this._onKeyUp },
  11013. { name: "blur", handler: this._onLostFocus }
  11014. ]);
  11015. this._MSGestureHandler = null;
  11016. this._attachedElement = null;
  11017. if (this._reset) {
  11018. this._reset();
  11019. }
  11020. };
  11021. ArcRotateCamera.prototype._checkInputs = function () {
  11022. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11023. if (this._collisionTriggered) {
  11024. return;
  11025. }
  11026. // Keyboard
  11027. for (var index = 0; index < this._keys.length; index++) {
  11028. var keyCode = this._keys[index];
  11029. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11030. this.inertialAlphaOffset -= 0.01;
  11031. }
  11032. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11033. this.inertialBetaOffset -= 0.01;
  11034. }
  11035. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11036. this.inertialAlphaOffset += 0.01;
  11037. }
  11038. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11039. this.inertialBetaOffset += 0.01;
  11040. }
  11041. }
  11042. // Inertia
  11043. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11044. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11045. this.beta += this.inertialBetaOffset;
  11046. this.radius -= this.inertialRadiusOffset;
  11047. this.inertialAlphaOffset *= this.inertia;
  11048. this.inertialBetaOffset *= this.inertia;
  11049. this.inertialRadiusOffset *= this.inertia;
  11050. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11051. this.inertialAlphaOffset = 0;
  11052. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11053. this.inertialBetaOffset = 0;
  11054. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11055. this.inertialRadiusOffset = 0;
  11056. }
  11057. // Limits
  11058. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11059. if (this.beta > Math.PI) {
  11060. this.beta = this.beta - (2 * Math.PI);
  11061. }
  11062. }
  11063. else {
  11064. if (this.beta < this.lowerBetaLimit) {
  11065. this.beta = this.lowerBetaLimit;
  11066. }
  11067. }
  11068. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11069. if (this.beta < -Math.PI) {
  11070. this.beta = this.beta + (2 * Math.PI);
  11071. }
  11072. }
  11073. else {
  11074. if (this.beta > this.upperBetaLimit) {
  11075. this.beta = this.upperBetaLimit;
  11076. }
  11077. }
  11078. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11079. this.alpha = this.lowerAlphaLimit;
  11080. }
  11081. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11082. this.alpha = this.upperAlphaLimit;
  11083. }
  11084. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11085. this.radius = this.lowerRadiusLimit;
  11086. }
  11087. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11088. this.radius = this.upperRadiusLimit;
  11089. }
  11090. _super.prototype._checkInputs.call(this);
  11091. };
  11092. ArcRotateCamera.prototype.setPosition = function (position) {
  11093. var radiusv3 = position.subtract(this._getTargetPosition());
  11094. this.radius = radiusv3.length();
  11095. // Alpha
  11096. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11097. if (radiusv3.z < 0) {
  11098. this.alpha = 2 * Math.PI - this.alpha;
  11099. }
  11100. // Beta
  11101. this.beta = Math.acos(radiusv3.y / this.radius);
  11102. };
  11103. ArcRotateCamera.prototype._getViewMatrix = function () {
  11104. // Compute
  11105. var cosa = Math.cos(this.alpha);
  11106. var sina = Math.sin(this.alpha);
  11107. var cosb = Math.cos(this.beta);
  11108. var sinb = Math.sin(this.beta);
  11109. var target = this._getTargetPosition();
  11110. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  11111. if (this.checkCollisions) {
  11112. this._collider.radius = this.collisionRadius;
  11113. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  11114. this._collisionTriggered = true;
  11115. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11116. }
  11117. var up = this.upVector.clone();
  11118. if (this.beta < 0) {
  11119. up = up.negate();
  11120. }
  11121. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11122. this._previousAlpha = this.alpha;
  11123. this._previousBeta = this.beta;
  11124. this._previousRadius = this.radius;
  11125. this._previousPosition.copyFrom(this.position);
  11126. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11127. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11128. return this._viewMatrix;
  11129. };
  11130. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11131. meshes = meshes || this.getScene().meshes;
  11132. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11133. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11134. this.radius = distance * this.zoomOnFactor;
  11135. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11136. };
  11137. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11138. var meshesOrMinMaxVector;
  11139. var distance;
  11140. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11141. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11142. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11143. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11144. }
  11145. else {
  11146. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11147. distance = meshesOrMinMaxVectorAndDistance.distance;
  11148. }
  11149. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11150. this.maxZ = distance * 2;
  11151. };
  11152. /**
  11153. * @override
  11154. * needs to be overridden, so sub has required properties to be copied
  11155. */
  11156. ArcRotateCamera.prototype.getSubCamera = function (name, isA) {
  11157. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  11158. return new BABYLON.ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  11159. };
  11160. /**
  11161. * @override
  11162. * needs to be overridden, adding copy of alpha, beta & radius
  11163. */
  11164. ArcRotateCamera.prototype._updateSubCameras = function () {
  11165. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  11166. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  11167. camA.alpha = this.alpha - this._subCamHalfSpace;
  11168. camB.alpha = this.alpha + this._subCamHalfSpace;
  11169. camA.beta = camB.beta = this.beta;
  11170. camA.radius = camB.radius = this.radius;
  11171. _super.prototype._updateSubCameras.call(this);
  11172. };
  11173. return ArcRotateCamera;
  11174. })(BABYLON.Camera);
  11175. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11176. })(BABYLON || (BABYLON = {}));
  11177. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11178. var __extends = this.__extends || function (d, b) {
  11179. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11180. function __() { this.constructor = d; }
  11181. __.prototype = b.prototype;
  11182. d.prototype = new __();
  11183. };
  11184. var BABYLON;
  11185. (function (BABYLON) {
  11186. // We're mainly based on the logic defined into the FreeCamera code
  11187. var DeviceOrientationCamera = (function (_super) {
  11188. __extends(DeviceOrientationCamera, _super);
  11189. function DeviceOrientationCamera(name, position, scene) {
  11190. var _this = this;
  11191. _super.call(this, name, position, scene);
  11192. this._offsetX = null;
  11193. this._offsetY = null;
  11194. this._orientationGamma = 0;
  11195. this._orientationBeta = 0;
  11196. this._initialOrientationGamma = 0;
  11197. this._initialOrientationBeta = 0;
  11198. this.angularSensibility = 10000.0;
  11199. this.moveSensibility = 50.0;
  11200. window.addEventListener("resize", function () {
  11201. _this._initialOrientationGamma = null;
  11202. }, false);
  11203. }
  11204. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11205. var _this = this;
  11206. if (this._attachedCanvas) {
  11207. return;
  11208. }
  11209. this._attachedCanvas = canvas;
  11210. if (!this._orientationChanged) {
  11211. this._orientationChanged = function (evt) {
  11212. if (!_this._initialOrientationGamma) {
  11213. _this._initialOrientationGamma = evt.gamma;
  11214. _this._initialOrientationBeta = evt.beta;
  11215. }
  11216. _this._orientationGamma = evt.gamma;
  11217. _this._orientationBeta = evt.beta;
  11218. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11219. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11220. };
  11221. }
  11222. window.addEventListener("deviceorientation", this._orientationChanged);
  11223. };
  11224. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11225. if (this._attachedCanvas != canvas) {
  11226. return;
  11227. }
  11228. window.removeEventListener("deviceorientation", this._orientationChanged);
  11229. this._attachedCanvas = null;
  11230. this._orientationGamma = 0;
  11231. this._orientationBeta = 0;
  11232. this._initialOrientationGamma = 0;
  11233. this._initialOrientationBeta = 0;
  11234. };
  11235. DeviceOrientationCamera.prototype._checkInputs = function () {
  11236. if (!this._offsetX) {
  11237. return;
  11238. }
  11239. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11240. var speed = this._computeLocalCameraSpeed();
  11241. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11242. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11243. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11244. _super.prototype._checkInputs.call(this);
  11245. };
  11246. return DeviceOrientationCamera;
  11247. })(BABYLON.FreeCamera);
  11248. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11249. })(BABYLON || (BABYLON = {}));
  11250. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11251. var __extends = this.__extends || function (d, b) {
  11252. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11253. function __() { this.constructor = d; }
  11254. __.prototype = b.prototype;
  11255. d.prototype = new __();
  11256. };
  11257. var BABYLON;
  11258. (function (BABYLON) {
  11259. var Gamepads = (function () {
  11260. function Gamepads(ongamedpadconnected) {
  11261. var _this = this;
  11262. this.babylonGamepads = [];
  11263. this.oneGamepadConnected = false;
  11264. this.isMonitoring = false;
  11265. this.gamepadEventSupported = 'GamepadEvent' in window;
  11266. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11267. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11268. 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=";
  11269. this._callbackGamepadConnected = ongamedpadconnected;
  11270. if (this.gamepadSupportAvailable) {
  11271. // Checking if the gamepad connected event is supported (like in Firefox)
  11272. if (this.gamepadEventSupported) {
  11273. window.addEventListener('gamepadconnected', function (evt) {
  11274. _this._onGamepadConnected(evt);
  11275. }, false);
  11276. window.addEventListener('gamepaddisconnected', function (evt) {
  11277. _this._onGamepadDisconnected(evt);
  11278. }, false);
  11279. }
  11280. else {
  11281. this._startMonitoringGamepads();
  11282. }
  11283. if (!this.oneGamepadConnected) {
  11284. this._insertGamepadDOMInstructions();
  11285. }
  11286. }
  11287. else {
  11288. this._insertGamepadDOMNotSupported();
  11289. }
  11290. }
  11291. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11292. Gamepads.gamepadDOMInfo = document.createElement("div");
  11293. var buttonAImage = document.createElement("img");
  11294. buttonAImage.src = this.buttonADataURL;
  11295. var spanMessage = document.createElement("span");
  11296. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11297. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11298. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11299. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11300. Gamepads.gamepadDOMInfo.style.width = "100%";
  11301. Gamepads.gamepadDOMInfo.style.height = "48px";
  11302. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11303. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11304. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11305. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11306. buttonAImage.style.position = "relative";
  11307. buttonAImage.style.bottom = "8px";
  11308. spanMessage.style.position = "relative";
  11309. spanMessage.style.fontSize = "32px";
  11310. spanMessage.style.bottom = "32px";
  11311. spanMessage.style.color = "green";
  11312. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11313. };
  11314. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11315. Gamepads.gamepadDOMInfo = document.createElement("div");
  11316. var spanMessage = document.createElement("span");
  11317. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11318. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11319. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11320. Gamepads.gamepadDOMInfo.style.width = "100%";
  11321. Gamepads.gamepadDOMInfo.style.height = "40px";
  11322. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11323. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11324. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11325. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11326. spanMessage.style.position = "relative";
  11327. spanMessage.style.fontSize = "32px";
  11328. spanMessage.style.color = "red";
  11329. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11330. };
  11331. Gamepads.prototype.dispose = function () {
  11332. if (Gamepads.gamepadDOMInfo) {
  11333. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11334. }
  11335. };
  11336. Gamepads.prototype._onGamepadConnected = function (evt) {
  11337. var newGamepad = this._addNewGamepad(evt.gamepad);
  11338. if (this._callbackGamepadConnected)
  11339. this._callbackGamepadConnected(newGamepad);
  11340. this._startMonitoringGamepads();
  11341. };
  11342. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11343. if (!this.oneGamepadConnected) {
  11344. this.oneGamepadConnected = true;
  11345. if (Gamepads.gamepadDOMInfo) {
  11346. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11347. Gamepads.gamepadDOMInfo = null;
  11348. }
  11349. }
  11350. var newGamepad;
  11351. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11352. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11353. }
  11354. else {
  11355. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  11356. }
  11357. this.babylonGamepads.push(newGamepad);
  11358. return newGamepad;
  11359. };
  11360. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11361. // Remove the gamepad from the list of gamepads to monitor.
  11362. for (var i in this.babylonGamepads) {
  11363. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11364. this.babylonGamepads.splice(i, 1);
  11365. break;
  11366. }
  11367. }
  11368. // If no gamepads are left, stop the polling loop.
  11369. if (this.babylonGamepads.length == 0) {
  11370. this._stopMonitoringGamepads();
  11371. }
  11372. };
  11373. Gamepads.prototype._startMonitoringGamepads = function () {
  11374. if (!this.isMonitoring) {
  11375. this.isMonitoring = true;
  11376. this._checkGamepadsStatus();
  11377. }
  11378. };
  11379. Gamepads.prototype._stopMonitoringGamepads = function () {
  11380. this.isMonitoring = false;
  11381. };
  11382. Gamepads.prototype._checkGamepadsStatus = function () {
  11383. var _this = this;
  11384. // updating gamepad objects
  11385. this._updateGamepadObjects();
  11386. for (var i in this.babylonGamepads) {
  11387. this.babylonGamepads[i].update();
  11388. }
  11389. if (this.isMonitoring) {
  11390. if (window.requestAnimationFrame) {
  11391. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11392. }
  11393. else if (window.mozRequestAnimationFrame) {
  11394. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11395. }
  11396. else if (window.webkitRequestAnimationFrame) {
  11397. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11398. }
  11399. }
  11400. };
  11401. // This function is called only on Chrome, which does not yet support
  11402. // connection/disconnection events, but requires you to monitor
  11403. // an array for changes.
  11404. Gamepads.prototype._updateGamepadObjects = function () {
  11405. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11406. for (var i = 0; i < gamepads.length; i++) {
  11407. if (gamepads[i]) {
  11408. if (!(gamepads[i].index in this.babylonGamepads)) {
  11409. var newGamepad = this._addNewGamepad(gamepads[i]);
  11410. if (this._callbackGamepadConnected) {
  11411. this._callbackGamepadConnected(newGamepad);
  11412. }
  11413. }
  11414. else {
  11415. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11416. }
  11417. }
  11418. }
  11419. };
  11420. return Gamepads;
  11421. })();
  11422. BABYLON.Gamepads = Gamepads;
  11423. var StickValues = (function () {
  11424. function StickValues(x, y) {
  11425. this.x = x;
  11426. this.y = y;
  11427. }
  11428. return StickValues;
  11429. })();
  11430. BABYLON.StickValues = StickValues;
  11431. var Gamepad = (function () {
  11432. function Gamepad(id, index, browserGamepad) {
  11433. this.id = id;
  11434. this.index = index;
  11435. this.browserGamepad = browserGamepad;
  11436. if (this.browserGamepad.axes.length >= 2) {
  11437. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11438. }
  11439. if (this.browserGamepad.axes.length >= 4) {
  11440. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11441. }
  11442. }
  11443. Gamepad.prototype.onleftstickchanged = function (callback) {
  11444. this._onleftstickchanged = callback;
  11445. };
  11446. Gamepad.prototype.onrightstickchanged = function (callback) {
  11447. this._onrightstickchanged = callback;
  11448. };
  11449. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11450. get: function () {
  11451. return this._leftStick;
  11452. },
  11453. set: function (newValues) {
  11454. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11455. this._onleftstickchanged(newValues);
  11456. }
  11457. this._leftStick = newValues;
  11458. },
  11459. enumerable: true,
  11460. configurable: true
  11461. });
  11462. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11463. get: function () {
  11464. return this._rightStick;
  11465. },
  11466. set: function (newValues) {
  11467. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11468. this._onrightstickchanged(newValues);
  11469. }
  11470. this._rightStick = newValues;
  11471. },
  11472. enumerable: true,
  11473. configurable: true
  11474. });
  11475. Gamepad.prototype.update = function () {
  11476. if (this._leftStick) {
  11477. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11478. }
  11479. if (this._rightStick) {
  11480. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11481. }
  11482. };
  11483. return Gamepad;
  11484. })();
  11485. BABYLON.Gamepad = Gamepad;
  11486. var GenericPad = (function (_super) {
  11487. __extends(GenericPad, _super);
  11488. function GenericPad(id, index, gamepad) {
  11489. _super.call(this, id, index, gamepad);
  11490. this.id = id;
  11491. this.index = index;
  11492. this.gamepad = gamepad;
  11493. this._buttons = new Array(gamepad.buttons.length);
  11494. }
  11495. GenericPad.prototype.onbuttondown = function (callback) {
  11496. this._onbuttondown = callback;
  11497. };
  11498. GenericPad.prototype.onbuttonup = function (callback) {
  11499. this._onbuttonup = callback;
  11500. };
  11501. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11502. if (newValue !== currentValue) {
  11503. if (this._onbuttondown && newValue === 1) {
  11504. this._onbuttondown(buttonIndex);
  11505. }
  11506. if (this._onbuttonup && newValue === 0) {
  11507. this._onbuttonup(buttonIndex);
  11508. }
  11509. }
  11510. return newValue;
  11511. };
  11512. GenericPad.prototype.update = function () {
  11513. _super.prototype.update.call(this);
  11514. for (var index = 0; index < this._buttons.length; index++) {
  11515. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11516. }
  11517. };
  11518. return GenericPad;
  11519. })(Gamepad);
  11520. BABYLON.GenericPad = GenericPad;
  11521. (function (Xbox360Button) {
  11522. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11523. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11524. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11525. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11526. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11527. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11528. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11529. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11530. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11531. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11532. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11533. var Xbox360Button = BABYLON.Xbox360Button;
  11534. (function (Xbox360Dpad) {
  11535. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11536. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11537. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11538. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11539. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11540. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11541. var Xbox360Pad = (function (_super) {
  11542. __extends(Xbox360Pad, _super);
  11543. function Xbox360Pad() {
  11544. _super.apply(this, arguments);
  11545. this._leftTrigger = 0;
  11546. this._rightTrigger = 0;
  11547. this._buttonA = 0;
  11548. this._buttonB = 0;
  11549. this._buttonX = 0;
  11550. this._buttonY = 0;
  11551. this._buttonBack = 0;
  11552. this._buttonStart = 0;
  11553. this._buttonLB = 0;
  11554. this._buttonRB = 0;
  11555. this._buttonLeftStick = 0;
  11556. this._buttonRightStick = 0;
  11557. this._dPadUp = 0;
  11558. this._dPadDown = 0;
  11559. this._dPadLeft = 0;
  11560. this._dPadRight = 0;
  11561. }
  11562. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11563. this._onlefttriggerchanged = callback;
  11564. };
  11565. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11566. this._onrighttriggerchanged = callback;
  11567. };
  11568. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11569. get: function () {
  11570. return this._leftTrigger;
  11571. },
  11572. set: function (newValue) {
  11573. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11574. this._onlefttriggerchanged(newValue);
  11575. }
  11576. this._leftTrigger = newValue;
  11577. },
  11578. enumerable: true,
  11579. configurable: true
  11580. });
  11581. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11582. get: function () {
  11583. return this._rightTrigger;
  11584. },
  11585. set: function (newValue) {
  11586. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11587. this._onrighttriggerchanged(newValue);
  11588. }
  11589. this._rightTrigger = newValue;
  11590. },
  11591. enumerable: true,
  11592. configurable: true
  11593. });
  11594. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11595. this._onbuttondown = callback;
  11596. };
  11597. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11598. this._onbuttonup = callback;
  11599. };
  11600. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11601. this._ondpaddown = callback;
  11602. };
  11603. Xbox360Pad.prototype.ondpadup = function (callback) {
  11604. this._ondpadup = callback;
  11605. };
  11606. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11607. if (newValue !== currentValue) {
  11608. if (this._onbuttondown && newValue === 1) {
  11609. this._onbuttondown(buttonType);
  11610. }
  11611. if (this._onbuttonup && newValue === 0) {
  11612. this._onbuttonup(buttonType);
  11613. }
  11614. }
  11615. return newValue;
  11616. };
  11617. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11618. if (newValue !== currentValue) {
  11619. if (this._ondpaddown && newValue === 1) {
  11620. this._ondpaddown(buttonType);
  11621. }
  11622. if (this._ondpadup && newValue === 0) {
  11623. this._ondpadup(buttonType);
  11624. }
  11625. }
  11626. return newValue;
  11627. };
  11628. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11629. get: function () {
  11630. return this._buttonA;
  11631. },
  11632. set: function (value) {
  11633. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11639. get: function () {
  11640. return this._buttonB;
  11641. },
  11642. set: function (value) {
  11643. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11649. get: function () {
  11650. return this._buttonX;
  11651. },
  11652. set: function (value) {
  11653. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11659. get: function () {
  11660. return this._buttonY;
  11661. },
  11662. set: function (value) {
  11663. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11669. get: function () {
  11670. return this._buttonStart;
  11671. },
  11672. set: function (value) {
  11673. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11679. get: function () {
  11680. return this._buttonBack;
  11681. },
  11682. set: function (value) {
  11683. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11689. get: function () {
  11690. return this._buttonLB;
  11691. },
  11692. set: function (value) {
  11693. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11699. get: function () {
  11700. return this._buttonRB;
  11701. },
  11702. set: function (value) {
  11703. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11709. get: function () {
  11710. return this._buttonLeftStick;
  11711. },
  11712. set: function (value) {
  11713. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11719. get: function () {
  11720. return this._buttonRightStick;
  11721. },
  11722. set: function (value) {
  11723. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11729. get: function () {
  11730. return this._dPadUp;
  11731. },
  11732. set: function (value) {
  11733. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11739. get: function () {
  11740. return this._dPadDown;
  11741. },
  11742. set: function (value) {
  11743. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11749. get: function () {
  11750. return this._dPadLeft;
  11751. },
  11752. set: function (value) {
  11753. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11759. get: function () {
  11760. return this._dPadRight;
  11761. },
  11762. set: function (value) {
  11763. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Xbox360Pad.prototype.update = function () {
  11769. _super.prototype.update.call(this);
  11770. this.buttonA = this.browserGamepad.buttons[0].value;
  11771. this.buttonB = this.browserGamepad.buttons[1].value;
  11772. this.buttonX = this.browserGamepad.buttons[2].value;
  11773. this.buttonY = this.browserGamepad.buttons[3].value;
  11774. this.buttonLB = this.browserGamepad.buttons[4].value;
  11775. this.buttonRB = this.browserGamepad.buttons[5].value;
  11776. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11777. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11778. this.buttonBack = this.browserGamepad.buttons[8].value;
  11779. this.buttonStart = this.browserGamepad.buttons[9].value;
  11780. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11781. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11782. this.dPadUp = this.browserGamepad.buttons[12].value;
  11783. this.dPadDown = this.browserGamepad.buttons[13].value;
  11784. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11785. this.dPadRight = this.browserGamepad.buttons[15].value;
  11786. };
  11787. return Xbox360Pad;
  11788. })(Gamepad);
  11789. BABYLON.Xbox360Pad = Xbox360Pad;
  11790. })(BABYLON || (BABYLON = {}));
  11791. //# sourceMappingURL=babylon.gamepads.js.map
  11792. var __extends = this.__extends || function (d, b) {
  11793. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11794. function __() { this.constructor = d; }
  11795. __.prototype = b.prototype;
  11796. d.prototype = new __();
  11797. };
  11798. var BABYLON;
  11799. (function (BABYLON) {
  11800. // We're mainly based on the logic defined into the FreeCamera code
  11801. var GamepadCamera = (function (_super) {
  11802. __extends(GamepadCamera, _super);
  11803. function GamepadCamera(name, position, scene) {
  11804. var _this = this;
  11805. _super.call(this, name, position, scene);
  11806. this.angularSensibility = 200;
  11807. this.moveSensibility = 75;
  11808. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11809. }
  11810. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11811. // Only the first gamepad can control the camera
  11812. if (gamepad.index === 0) {
  11813. this._gamepad = gamepad;
  11814. }
  11815. };
  11816. GamepadCamera.prototype._checkInputs = function () {
  11817. if (this._gamepad) {
  11818. var LSValues = this._gamepad.leftStick;
  11819. var normalizedLX = LSValues.x / this.moveSensibility;
  11820. var normalizedLY = LSValues.y / this.moveSensibility;
  11821. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11822. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11823. var RSValues = this._gamepad.rightStick;
  11824. var normalizedRX = RSValues.x / this.angularSensibility;
  11825. var normalizedRY = RSValues.y / this.angularSensibility;
  11826. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11827. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11828. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11829. var speed = this._computeLocalCameraSpeed() * 50.0;
  11830. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11831. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11832. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11833. }
  11834. _super.prototype._checkInputs.call(this);
  11835. };
  11836. GamepadCamera.prototype.dispose = function () {
  11837. this._gamepads.dispose();
  11838. _super.prototype.dispose.call(this);
  11839. };
  11840. return GamepadCamera;
  11841. })(BABYLON.FreeCamera);
  11842. BABYLON.GamepadCamera = GamepadCamera;
  11843. })(BABYLON || (BABYLON = {}));
  11844. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11845. var BABYLON;
  11846. (function (BABYLON) {
  11847. var RenderingManager = (function () {
  11848. function RenderingManager(scene) {
  11849. this._renderingGroups = new Array();
  11850. this._scene = scene;
  11851. }
  11852. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11853. if (this._scene._activeParticleSystems.length === 0) {
  11854. return;
  11855. }
  11856. // Particles
  11857. var beforeParticlesDate = BABYLON.Tools.Now;
  11858. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11859. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11860. if (particleSystem.renderingGroupId !== index) {
  11861. continue;
  11862. }
  11863. this._clearDepthBuffer();
  11864. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11865. this._scene._activeParticles += particleSystem.render();
  11866. }
  11867. }
  11868. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11869. };
  11870. RenderingManager.prototype._renderSprites = function (index) {
  11871. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11872. return;
  11873. }
  11874. // Sprites
  11875. var beforeSpritessDate = BABYLON.Tools.Now;
  11876. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11877. var spriteManager = this._scene.spriteManagers[id];
  11878. if (spriteManager.renderingGroupId === index) {
  11879. this._clearDepthBuffer();
  11880. spriteManager.render();
  11881. }
  11882. }
  11883. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11884. };
  11885. RenderingManager.prototype._clearDepthBuffer = function () {
  11886. if (this._depthBufferAlreadyCleaned) {
  11887. return;
  11888. }
  11889. this._scene.getEngine().clear(0, false, true);
  11890. this._depthBufferAlreadyCleaned = true;
  11891. };
  11892. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11893. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11894. this._depthBufferAlreadyCleaned = false;
  11895. var renderingGroup = this._renderingGroups[index];
  11896. var needToStepBack = false;
  11897. if (renderingGroup) {
  11898. this._clearDepthBuffer();
  11899. if (!renderingGroup.render(customRenderFunction)) {
  11900. this._renderingGroups.splice(index, 1);
  11901. needToStepBack = true;
  11902. }
  11903. }
  11904. if (renderSprites) {
  11905. this._renderSprites(index);
  11906. }
  11907. if (renderParticles) {
  11908. this._renderParticles(index, activeMeshes);
  11909. }
  11910. if (needToStepBack) {
  11911. index--;
  11912. }
  11913. }
  11914. };
  11915. RenderingManager.prototype.reset = function () {
  11916. for (var index in this._renderingGroups) {
  11917. var renderingGroup = this._renderingGroups[index];
  11918. renderingGroup.prepare();
  11919. }
  11920. };
  11921. RenderingManager.prototype.dispatch = function (subMesh) {
  11922. var mesh = subMesh.getMesh();
  11923. var renderingGroupId = mesh.renderingGroupId || 0;
  11924. if (!this._renderingGroups[renderingGroupId]) {
  11925. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11926. }
  11927. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11928. };
  11929. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11930. return RenderingManager;
  11931. })();
  11932. BABYLON.RenderingManager = RenderingManager;
  11933. })(BABYLON || (BABYLON = {}));
  11934. //# sourceMappingURL=babylon.renderingManager.js.map
  11935. var BABYLON;
  11936. (function (BABYLON) {
  11937. var RenderingGroup = (function () {
  11938. function RenderingGroup(index, scene) {
  11939. this.index = index;
  11940. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11941. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11942. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11943. this._scene = scene;
  11944. }
  11945. RenderingGroup.prototype.render = function (customRenderFunction) {
  11946. if (customRenderFunction) {
  11947. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11948. return true;
  11949. }
  11950. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11951. return false;
  11952. }
  11953. var engine = this._scene.getEngine();
  11954. // Opaque
  11955. var subIndex;
  11956. var submesh;
  11957. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11958. submesh = this._opaqueSubMeshes.data[subIndex];
  11959. submesh.render();
  11960. }
  11961. // Alpha test
  11962. engine.setAlphaTesting(true);
  11963. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11964. submesh = this._alphaTestSubMeshes.data[subIndex];
  11965. submesh.render();
  11966. }
  11967. engine.setAlphaTesting(false);
  11968. // Transparent
  11969. if (this._transparentSubMeshes.length) {
  11970. // Sorting
  11971. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11972. submesh = this._transparentSubMeshes.data[subIndex];
  11973. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11974. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11975. }
  11976. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11977. sortedArray.sort(function (a, b) {
  11978. // Alpha index first
  11979. if (a._alphaIndex > b._alphaIndex) {
  11980. return 1;
  11981. }
  11982. if (a._alphaIndex < b._alphaIndex) {
  11983. return -1;
  11984. }
  11985. // Then distance to camera
  11986. if (a._distanceToCamera < b._distanceToCamera) {
  11987. return 1;
  11988. }
  11989. if (a._distanceToCamera > b._distanceToCamera) {
  11990. return -1;
  11991. }
  11992. return 0;
  11993. });
  11994. // Rendering
  11995. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11996. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11997. submesh = sortedArray[subIndex];
  11998. submesh.render();
  11999. }
  12000. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12001. }
  12002. return true;
  12003. };
  12004. RenderingGroup.prototype.prepare = function () {
  12005. this._opaqueSubMeshes.reset();
  12006. this._transparentSubMeshes.reset();
  12007. this._alphaTestSubMeshes.reset();
  12008. };
  12009. RenderingGroup.prototype.dispatch = function (subMesh) {
  12010. var material = subMesh.getMaterial();
  12011. var mesh = subMesh.getMesh();
  12012. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12013. this._transparentSubMeshes.push(subMesh);
  12014. }
  12015. else if (material.needAlphaTesting()) {
  12016. this._alphaTestSubMeshes.push(subMesh);
  12017. }
  12018. else {
  12019. this._opaqueSubMeshes.push(subMesh); // Opaque
  12020. }
  12021. };
  12022. return RenderingGroup;
  12023. })();
  12024. BABYLON.RenderingGroup = RenderingGroup;
  12025. })(BABYLON || (BABYLON = {}));
  12026. //# sourceMappingURL=babylon.renderingGroup.js.map
  12027. var BABYLON;
  12028. (function (BABYLON) {
  12029. /**
  12030. * Represents a scene to be rendered by the engine.
  12031. * @see http://doc.babylonjs.com/page.php?p=21911
  12032. */
  12033. var Scene = (function () {
  12034. /**
  12035. * @constructor
  12036. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12037. */
  12038. function Scene(engine) {
  12039. // Members
  12040. this.autoClear = true;
  12041. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12042. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12043. this.forceWireframe = false;
  12044. this.forcePointsCloud = false;
  12045. this.forceShowBoundingBoxes = false;
  12046. this.animationsEnabled = true;
  12047. 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
  12048. // Fog
  12049. /**
  12050. * is fog enabled on this scene.
  12051. * @type {boolean}
  12052. */
  12053. this.fogEnabled = true;
  12054. this.fogMode = Scene.FOGMODE_NONE;
  12055. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12056. this.fogDensity = 0.1;
  12057. this.fogStart = 0;
  12058. this.fogEnd = 1000.0;
  12059. // Lights
  12060. /**
  12061. * is shadow enabled on this scene.
  12062. * @type {boolean}
  12063. */
  12064. this.shadowsEnabled = true;
  12065. /**
  12066. * is light enabled on this scene.
  12067. * @type {boolean}
  12068. */
  12069. this.lightsEnabled = true;
  12070. /**
  12071. * All of the lights added to this scene.
  12072. * @see BABYLON.Light
  12073. * @type {BABYLON.Light[]}
  12074. */
  12075. this.lights = new Array();
  12076. // Cameras
  12077. /**
  12078. * All of the cameras added to this scene.
  12079. * @see BABYLON.Camera
  12080. * @type {BABYLON.Camera[]}
  12081. */
  12082. this.cameras = new Array();
  12083. this.activeCameras = new Array();
  12084. // Meshes
  12085. /**
  12086. * All of the (abstract) meshes added to this scene.
  12087. * @see BABYLON.AbstractMesh
  12088. * @type {BABYLON.AbstractMesh[]}
  12089. */
  12090. this.meshes = new Array();
  12091. // Geometries
  12092. this._geometries = new Array();
  12093. this.materials = new Array();
  12094. this.multiMaterials = new Array();
  12095. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12096. // Textures
  12097. this.texturesEnabled = true;
  12098. this.textures = new Array();
  12099. // Particles
  12100. this.particlesEnabled = true;
  12101. this.particleSystems = new Array();
  12102. // Sprites
  12103. this.spritesEnabled = true;
  12104. this.spriteManagers = new Array();
  12105. // Layers
  12106. this.layers = new Array();
  12107. // Skeletons
  12108. this.skeletonsEnabled = true;
  12109. this.skeletons = new Array();
  12110. // Lens flares
  12111. this.lensFlaresEnabled = true;
  12112. this.lensFlareSystems = new Array();
  12113. // Collisions
  12114. this.collisionsEnabled = true;
  12115. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  12116. // Postprocesses
  12117. this.postProcessesEnabled = true;
  12118. // Customs render targets
  12119. this.renderTargetsEnabled = true;
  12120. this.dumpNextRenderTargets = false;
  12121. this.customRenderTargets = new Array();
  12122. // Imported meshes
  12123. this.importedMeshesFiles = new Array();
  12124. this._actionManagers = new Array();
  12125. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12126. // Procedural textures
  12127. this.proceduralTexturesEnabled = true;
  12128. this._proceduralTextures = new Array();
  12129. this.soundTracks = new Array();
  12130. this._audioEnabled = true;
  12131. this._headphone = false;
  12132. this._totalVertices = 0;
  12133. this._activeIndices = 0;
  12134. this._activeParticles = 0;
  12135. this._lastFrameDuration = 0;
  12136. this._evaluateActiveMeshesDuration = 0;
  12137. this._renderTargetsDuration = 0;
  12138. this._particlesDuration = 0;
  12139. this._renderDuration = 0;
  12140. this._spritesDuration = 0;
  12141. this._animationRatio = 0;
  12142. this._renderId = 0;
  12143. this._executeWhenReadyTimeoutId = -1;
  12144. this._toBeDisposed = new BABYLON.SmartArray(256);
  12145. this._onReadyCallbacks = new Array();
  12146. this._pendingData = []; //ANY
  12147. this._onBeforeRenderCallbacks = new Array();
  12148. this._onAfterRenderCallbacks = new Array();
  12149. this._activeMeshes = new BABYLON.SmartArray(256);
  12150. this._processedMaterials = new BABYLON.SmartArray(256);
  12151. this._renderTargets = new BABYLON.SmartArray(256);
  12152. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12153. this._activeSkeletons = new BABYLON.SmartArray(32);
  12154. this._activeBones = 0;
  12155. this._activeAnimatables = new Array();
  12156. this._transformMatrix = BABYLON.Matrix.Zero();
  12157. this._uniqueIdCounter = 0;
  12158. this._engine = engine;
  12159. engine.scenes.push(this);
  12160. this._renderingManager = new BABYLON.RenderingManager(this);
  12161. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12162. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12163. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12164. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12165. this.attachControl();
  12166. this._debugLayer = new BABYLON.DebugLayer(this);
  12167. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12168. //simplification queue
  12169. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12170. //collision coordinator initialization. For now legacy per default.
  12171. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12172. }
  12173. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12174. get: function () {
  12175. return Scene._FOGMODE_NONE;
  12176. },
  12177. enumerable: true,
  12178. configurable: true
  12179. });
  12180. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12181. get: function () {
  12182. return Scene._FOGMODE_EXP;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12188. get: function () {
  12189. return Scene._FOGMODE_EXP2;
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12195. get: function () {
  12196. return Scene._FOGMODE_LINEAR;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(Scene.prototype, "debugLayer", {
  12202. // Properties
  12203. get: function () {
  12204. return this._debugLayer;
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12210. get: function () {
  12211. return this._workerCollisions;
  12212. },
  12213. set: function (enabled) {
  12214. enabled = (enabled && !!Worker);
  12215. this._workerCollisions = enabled;
  12216. if (this.collisionCoordinator) {
  12217. this.collisionCoordinator.destroy();
  12218. }
  12219. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12220. this.collisionCoordinator.init(this);
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12226. /**
  12227. * The mesh that is currently under the pointer.
  12228. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12229. */
  12230. get: function () {
  12231. return this._meshUnderPointer;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. Object.defineProperty(Scene.prototype, "pointerX", {
  12237. /**
  12238. * Current on-screen X position of the pointer
  12239. * @return {number} X position of the pointer
  12240. */
  12241. get: function () {
  12242. return this._pointerX;
  12243. },
  12244. enumerable: true,
  12245. configurable: true
  12246. });
  12247. Object.defineProperty(Scene.prototype, "pointerY", {
  12248. /**
  12249. * Current on-screen Y position of the pointer
  12250. * @return {number} Y position of the pointer
  12251. */
  12252. get: function () {
  12253. return this._pointerY;
  12254. },
  12255. enumerable: true,
  12256. configurable: true
  12257. });
  12258. Scene.prototype.getCachedMaterial = function () {
  12259. return this._cachedMaterial;
  12260. };
  12261. Scene.prototype.getBoundingBoxRenderer = function () {
  12262. return this._boundingBoxRenderer;
  12263. };
  12264. Scene.prototype.getOutlineRenderer = function () {
  12265. return this._outlineRenderer;
  12266. };
  12267. Scene.prototype.getEngine = function () {
  12268. return this._engine;
  12269. };
  12270. Scene.prototype.getTotalVertices = function () {
  12271. return this._totalVertices;
  12272. };
  12273. Scene.prototype.getActiveIndices = function () {
  12274. return this._activeIndices;
  12275. };
  12276. Scene.prototype.getActiveParticles = function () {
  12277. return this._activeParticles;
  12278. };
  12279. Scene.prototype.getActiveBones = function () {
  12280. return this._activeBones;
  12281. };
  12282. // Stats
  12283. Scene.prototype.getLastFrameDuration = function () {
  12284. return this._lastFrameDuration;
  12285. };
  12286. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12287. return this._evaluateActiveMeshesDuration;
  12288. };
  12289. Scene.prototype.getActiveMeshes = function () {
  12290. return this._activeMeshes;
  12291. };
  12292. Scene.prototype.getRenderTargetsDuration = function () {
  12293. return this._renderTargetsDuration;
  12294. };
  12295. Scene.prototype.getRenderDuration = function () {
  12296. return this._renderDuration;
  12297. };
  12298. Scene.prototype.getParticlesDuration = function () {
  12299. return this._particlesDuration;
  12300. };
  12301. Scene.prototype.getSpritesDuration = function () {
  12302. return this._spritesDuration;
  12303. };
  12304. Scene.prototype.getAnimationRatio = function () {
  12305. return this._animationRatio;
  12306. };
  12307. Scene.prototype.getRenderId = function () {
  12308. return this._renderId;
  12309. };
  12310. Scene.prototype.incrementRenderId = function () {
  12311. this._renderId++;
  12312. };
  12313. Scene.prototype._updatePointerPosition = function (evt) {
  12314. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12315. this._pointerX = evt.clientX - canvasRect.left;
  12316. this._pointerY = evt.clientY - canvasRect.top;
  12317. if (this.cameraToUseForPointers) {
  12318. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12319. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12320. }
  12321. };
  12322. // Pointers handling
  12323. Scene.prototype.attachControl = function () {
  12324. var _this = this;
  12325. this._onPointerMove = function (evt) {
  12326. var canvas = _this._engine.getRenderingCanvas();
  12327. _this._updatePointerPosition(evt);
  12328. 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);
  12329. if (pickResult.hit) {
  12330. _this._meshUnderPointer = pickResult.pickedMesh;
  12331. _this.setPointerOverMesh(pickResult.pickedMesh);
  12332. canvas.style.cursor = "pointer";
  12333. }
  12334. else {
  12335. _this.setPointerOverMesh(null);
  12336. canvas.style.cursor = "";
  12337. _this._meshUnderPointer = null;
  12338. }
  12339. };
  12340. this._onPointerDown = function (evt) {
  12341. var predicate = null;
  12342. if (!_this.onPointerDown) {
  12343. predicate = function (mesh) {
  12344. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12345. };
  12346. }
  12347. _this._updatePointerPosition(evt);
  12348. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12349. if (pickResult.hit) {
  12350. if (pickResult.pickedMesh.actionManager) {
  12351. switch (evt.button) {
  12352. case 0:
  12353. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12354. break;
  12355. case 1:
  12356. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12357. break;
  12358. case 2:
  12359. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12360. break;
  12361. }
  12362. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12363. }
  12364. }
  12365. if (_this.onPointerDown) {
  12366. _this.onPointerDown(evt, pickResult);
  12367. }
  12368. };
  12369. this._onPointerUp = function (evt) {
  12370. var predicate = null;
  12371. if (!_this.onPointerUp) {
  12372. predicate = function (mesh) {
  12373. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12374. };
  12375. }
  12376. _this._updatePointerPosition(evt);
  12377. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12378. if (pickResult.hit) {
  12379. if (pickResult.pickedMesh.actionManager) {
  12380. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12381. }
  12382. }
  12383. if (_this.onPointerUp) {
  12384. _this.onPointerUp(evt, pickResult);
  12385. }
  12386. };
  12387. this._onKeyDown = function (evt) {
  12388. if (_this.actionManager) {
  12389. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12390. }
  12391. };
  12392. this._onKeyUp = function (evt) {
  12393. if (_this.actionManager) {
  12394. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12395. }
  12396. };
  12397. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12398. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12399. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12400. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12401. BABYLON.Tools.RegisterTopRootEvents([
  12402. { name: "keydown", handler: this._onKeyDown },
  12403. { name: "keyup", handler: this._onKeyUp }
  12404. ]);
  12405. };
  12406. Scene.prototype.detachControl = function () {
  12407. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12408. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12409. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12410. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12411. BABYLON.Tools.UnregisterTopRootEvents([
  12412. { name: "keydown", handler: this._onKeyDown },
  12413. { name: "keyup", handler: this._onKeyUp }
  12414. ]);
  12415. };
  12416. // Ready
  12417. Scene.prototype.isReady = function () {
  12418. if (this._pendingData.length > 0) {
  12419. return false;
  12420. }
  12421. for (var index = 0; index < this._geometries.length; index++) {
  12422. var geometry = this._geometries[index];
  12423. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12424. return false;
  12425. }
  12426. }
  12427. for (index = 0; index < this.meshes.length; index++) {
  12428. var mesh = this.meshes[index];
  12429. if (!mesh.isReady()) {
  12430. return false;
  12431. }
  12432. var mat = mesh.material;
  12433. if (mat) {
  12434. if (!mat.isReady(mesh)) {
  12435. return false;
  12436. }
  12437. }
  12438. }
  12439. return true;
  12440. };
  12441. Scene.prototype.resetCachedMaterial = function () {
  12442. this._cachedMaterial = null;
  12443. };
  12444. Scene.prototype.registerBeforeRender = function (func) {
  12445. this._onBeforeRenderCallbacks.push(func);
  12446. };
  12447. Scene.prototype.unregisterBeforeRender = function (func) {
  12448. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12449. if (index > -1) {
  12450. this._onBeforeRenderCallbacks.splice(index, 1);
  12451. }
  12452. };
  12453. Scene.prototype.registerAfterRender = function (func) {
  12454. this._onAfterRenderCallbacks.push(func);
  12455. };
  12456. Scene.prototype.unregisterAfterRender = function (func) {
  12457. var index = this._onAfterRenderCallbacks.indexOf(func);
  12458. if (index > -1) {
  12459. this._onAfterRenderCallbacks.splice(index, 1);
  12460. }
  12461. };
  12462. Scene.prototype._addPendingData = function (data) {
  12463. this._pendingData.push(data);
  12464. };
  12465. Scene.prototype._removePendingData = function (data) {
  12466. var index = this._pendingData.indexOf(data);
  12467. if (index !== -1) {
  12468. this._pendingData.splice(index, 1);
  12469. }
  12470. };
  12471. Scene.prototype.getWaitingItemsCount = function () {
  12472. return this._pendingData.length;
  12473. };
  12474. /**
  12475. * Registers a function to be executed when the scene is ready.
  12476. * @param {Function} func - the function to be executed.
  12477. */
  12478. Scene.prototype.executeWhenReady = function (func) {
  12479. var _this = this;
  12480. this._onReadyCallbacks.push(func);
  12481. if (this._executeWhenReadyTimeoutId !== -1) {
  12482. return;
  12483. }
  12484. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12485. _this._checkIsReady();
  12486. }, 150);
  12487. };
  12488. Scene.prototype._checkIsReady = function () {
  12489. var _this = this;
  12490. if (this.isReady()) {
  12491. this._onReadyCallbacks.forEach(function (func) {
  12492. func();
  12493. });
  12494. this._onReadyCallbacks = [];
  12495. this._executeWhenReadyTimeoutId = -1;
  12496. return;
  12497. }
  12498. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12499. _this._checkIsReady();
  12500. }, 150);
  12501. };
  12502. // Animations
  12503. /**
  12504. * Will start the animation sequence of a given target
  12505. * @param target - the target
  12506. * @param {number} from - from which frame should animation start
  12507. * @param {number} to - till which frame should animation run.
  12508. * @param {boolean} [loop] - should the animation loop
  12509. * @param {number} [speedRatio] - the speed in which to run the animation
  12510. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12511. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12512. * @return {BABYLON.Animatable} the animatable object created for this animation
  12513. * @see BABYLON.Animatable
  12514. * @see http://doc.babylonjs.com/page.php?p=22081
  12515. */
  12516. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12517. if (speedRatio === undefined) {
  12518. speedRatio = 1.0;
  12519. }
  12520. this.stopAnimation(target);
  12521. if (!animatable) {
  12522. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12523. }
  12524. // Local animations
  12525. if (target.animations) {
  12526. animatable.appendAnimations(target, target.animations);
  12527. }
  12528. // Children animations
  12529. if (target.getAnimatables) {
  12530. var animatables = target.getAnimatables();
  12531. for (var index = 0; index < animatables.length; index++) {
  12532. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12533. }
  12534. }
  12535. return animatable;
  12536. };
  12537. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12538. if (speedRatio === undefined) {
  12539. speedRatio = 1.0;
  12540. }
  12541. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12542. return animatable;
  12543. };
  12544. Scene.prototype.getAnimatableByTarget = function (target) {
  12545. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12546. if (this._activeAnimatables[index].target === target) {
  12547. return this._activeAnimatables[index];
  12548. }
  12549. }
  12550. return null;
  12551. };
  12552. /**
  12553. * Will stop the animation of the given target
  12554. * @param target - the target
  12555. * @see beginAnimation
  12556. */
  12557. Scene.prototype.stopAnimation = function (target) {
  12558. var animatable = this.getAnimatableByTarget(target);
  12559. if (animatable) {
  12560. animatable.stop();
  12561. }
  12562. };
  12563. Scene.prototype._animate = function () {
  12564. if (!this.animationsEnabled) {
  12565. return;
  12566. }
  12567. if (!this._animationStartDate) {
  12568. this._animationStartDate = BABYLON.Tools.Now;
  12569. }
  12570. // Getting time
  12571. var now = BABYLON.Tools.Now;
  12572. var delay = now - this._animationStartDate;
  12573. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12574. this._activeAnimatables[index]._animate(delay);
  12575. }
  12576. };
  12577. // Matrix
  12578. Scene.prototype.getViewMatrix = function () {
  12579. return this._viewMatrix;
  12580. };
  12581. Scene.prototype.getProjectionMatrix = function () {
  12582. return this._projectionMatrix;
  12583. };
  12584. Scene.prototype.getTransformMatrix = function () {
  12585. return this._transformMatrix;
  12586. };
  12587. Scene.prototype.setTransformMatrix = function (view, projection) {
  12588. this._viewMatrix = view;
  12589. this._projectionMatrix = projection;
  12590. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12591. };
  12592. // Methods
  12593. Scene.prototype.addMesh = function (newMesh) {
  12594. newMesh.uniqueId = this._uniqueIdCounter++;
  12595. var position = this.meshes.push(newMesh);
  12596. //notify the collision coordinator
  12597. this.collisionCoordinator.onMeshAdded(newMesh);
  12598. if (this.onNewMeshAdded) {
  12599. this.onNewMeshAdded(newMesh, position, this);
  12600. }
  12601. };
  12602. Scene.prototype.removeMesh = function (toRemove) {
  12603. var index = this.meshes.indexOf(toRemove);
  12604. if (index !== -1) {
  12605. // Remove from the scene if mesh found
  12606. this.meshes.splice(index, 1);
  12607. }
  12608. //notify the collision coordinator
  12609. this.collisionCoordinator.onMeshRemoved(toRemove);
  12610. if (this.onMeshRemoved) {
  12611. this.onMeshRemoved(toRemove);
  12612. }
  12613. return index;
  12614. };
  12615. Scene.prototype.removeLight = function (toRemove) {
  12616. var index = this.lights.indexOf(toRemove);
  12617. if (index !== -1) {
  12618. // Remove from the scene if mesh found
  12619. this.lights.splice(index, 1);
  12620. }
  12621. if (this.onLightRemoved) {
  12622. this.onLightRemoved(toRemove);
  12623. }
  12624. return index;
  12625. };
  12626. Scene.prototype.removeCamera = function (toRemove) {
  12627. var index = this.cameras.indexOf(toRemove);
  12628. if (index !== -1) {
  12629. // Remove from the scene if mesh found
  12630. this.cameras.splice(index, 1);
  12631. }
  12632. // Remove from activeCameras
  12633. var index2 = this.activeCameras.indexOf(toRemove);
  12634. if (index2 !== -1) {
  12635. // Remove from the scene if mesh found
  12636. this.activeCameras.splice(index2, 1);
  12637. }
  12638. // Reset the activeCamera
  12639. if (this.activeCamera === toRemove) {
  12640. if (this.cameras.length > 0) {
  12641. this.activeCamera = this.cameras[0];
  12642. }
  12643. else {
  12644. this.activeCamera = null;
  12645. }
  12646. }
  12647. if (this.onCameraRemoved) {
  12648. this.onCameraRemoved(toRemove);
  12649. }
  12650. return index;
  12651. };
  12652. Scene.prototype.addLight = function (newLight) {
  12653. newLight.uniqueId = this._uniqueIdCounter++;
  12654. var position = this.lights.push(newLight);
  12655. if (this.onNewLightAdded) {
  12656. this.onNewLightAdded(newLight, position, this);
  12657. }
  12658. };
  12659. Scene.prototype.addCamera = function (newCamera) {
  12660. newCamera.uniqueId = this._uniqueIdCounter++;
  12661. var position = this.cameras.push(newCamera);
  12662. if (this.onNewCameraAdded) {
  12663. this.onNewCameraAdded(newCamera, position, this);
  12664. }
  12665. };
  12666. /**
  12667. * sets the active camera of the scene using its ID
  12668. * @param {string} id - the camera's ID
  12669. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12670. * @see activeCamera
  12671. */
  12672. Scene.prototype.setActiveCameraByID = function (id) {
  12673. var camera = this.getCameraByID(id);
  12674. if (camera) {
  12675. this.activeCamera = camera;
  12676. return camera;
  12677. }
  12678. return null;
  12679. };
  12680. /**
  12681. * sets the active camera of the scene using its name
  12682. * @param {string} name - the camera's name
  12683. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12684. * @see activeCamera
  12685. */
  12686. Scene.prototype.setActiveCameraByName = function (name) {
  12687. var camera = this.getCameraByName(name);
  12688. if (camera) {
  12689. this.activeCamera = camera;
  12690. return camera;
  12691. }
  12692. return null;
  12693. };
  12694. /**
  12695. * get a material using its id
  12696. * @param {string} the material's ID
  12697. * @return {BABYLON.Material|null} the material or null if none found.
  12698. */
  12699. Scene.prototype.getMaterialByID = function (id) {
  12700. for (var index = 0; index < this.materials.length; index++) {
  12701. if (this.materials[index].id === id) {
  12702. return this.materials[index];
  12703. }
  12704. }
  12705. return null;
  12706. };
  12707. /**
  12708. * get a material using its name
  12709. * @param {string} the material's name
  12710. * @return {BABYLON.Material|null} the material or null if none found.
  12711. */
  12712. Scene.prototype.getMaterialByName = function (name) {
  12713. for (var index = 0; index < this.materials.length; index++) {
  12714. if (this.materials[index].name === name) {
  12715. return this.materials[index];
  12716. }
  12717. }
  12718. return null;
  12719. };
  12720. Scene.prototype.getCameraByID = function (id) {
  12721. for (var index = 0; index < this.cameras.length; index++) {
  12722. if (this.cameras[index].id === id) {
  12723. return this.cameras[index];
  12724. }
  12725. }
  12726. return null;
  12727. };
  12728. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12729. for (var index = 0; index < this.cameras.length; index++) {
  12730. if (this.cameras[index].uniqueId === uniqueId) {
  12731. return this.cameras[index];
  12732. }
  12733. }
  12734. return null;
  12735. };
  12736. /**
  12737. * get a camera using its name
  12738. * @param {string} the camera's name
  12739. * @return {BABYLON.Camera|null} the camera or null if none found.
  12740. */
  12741. Scene.prototype.getCameraByName = function (name) {
  12742. for (var index = 0; index < this.cameras.length; index++) {
  12743. if (this.cameras[index].name === name) {
  12744. return this.cameras[index];
  12745. }
  12746. }
  12747. return null;
  12748. };
  12749. /**
  12750. * get a light node using its name
  12751. * @param {string} the light's name
  12752. * @return {BABYLON.Light|null} the light or null if none found.
  12753. */
  12754. Scene.prototype.getLightByName = function (name) {
  12755. for (var index = 0; index < this.lights.length; index++) {
  12756. if (this.lights[index].name === name) {
  12757. return this.lights[index];
  12758. }
  12759. }
  12760. return null;
  12761. };
  12762. /**
  12763. * get a light node using its ID
  12764. * @param {string} the light's id
  12765. * @return {BABYLON.Light|null} the light or null if none found.
  12766. */
  12767. Scene.prototype.getLightByID = function (id) {
  12768. for (var index = 0; index < this.lights.length; index++) {
  12769. if (this.lights[index].id === id) {
  12770. return this.lights[index];
  12771. }
  12772. }
  12773. return null;
  12774. };
  12775. /**
  12776. * get a light node using its scene-generated unique ID
  12777. * @param {number} the light's unique id
  12778. * @return {BABYLON.Light|null} the light or null if none found.
  12779. */
  12780. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12781. for (var index = 0; index < this.lights.length; index++) {
  12782. if (this.lights[index].uniqueId === uniqueId) {
  12783. return this.lights[index];
  12784. }
  12785. }
  12786. return null;
  12787. };
  12788. /**
  12789. * get a geometry using its ID
  12790. * @param {string} the geometry's id
  12791. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12792. */
  12793. Scene.prototype.getGeometryByID = function (id) {
  12794. for (var index = 0; index < this._geometries.length; index++) {
  12795. if (this._geometries[index].id === id) {
  12796. return this._geometries[index];
  12797. }
  12798. }
  12799. return null;
  12800. };
  12801. /**
  12802. * add a new geometry to this scene.
  12803. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12804. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12805. * @return {boolean} was the geometry added or not
  12806. */
  12807. Scene.prototype.pushGeometry = function (geometry, force) {
  12808. if (!force && this.getGeometryByID(geometry.id)) {
  12809. return false;
  12810. }
  12811. this._geometries.push(geometry);
  12812. //notify the collision coordinator
  12813. this.collisionCoordinator.onGeometryAdded(geometry);
  12814. if (this.onGeometryAdded) {
  12815. this.onGeometryAdded(geometry);
  12816. }
  12817. return true;
  12818. };
  12819. /**
  12820. * Removes an existing geometry
  12821. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12822. * @return {boolean} was the geometry removed or not
  12823. */
  12824. Scene.prototype.removeGeometry = function (geometry) {
  12825. var index = this._geometries.indexOf(geometry);
  12826. if (index > -1) {
  12827. this._geometries.splice(index, 1);
  12828. //notify the collision coordinator
  12829. this.collisionCoordinator.onGeometryDeleted(geometry);
  12830. if (this.onGeometryRemoved) {
  12831. this.onGeometryRemoved(geometry);
  12832. }
  12833. return true;
  12834. }
  12835. return false;
  12836. };
  12837. Scene.prototype.getGeometries = function () {
  12838. return this._geometries;
  12839. };
  12840. /**
  12841. * Get the first added mesh found of a given ID
  12842. * @param {string} id - the id to search for
  12843. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12844. */
  12845. Scene.prototype.getMeshByID = function (id) {
  12846. for (var index = 0; index < this.meshes.length; index++) {
  12847. if (this.meshes[index].id === id) {
  12848. return this.meshes[index];
  12849. }
  12850. }
  12851. return null;
  12852. };
  12853. /**
  12854. * Get a mesh with its auto-generated unique id
  12855. * @param {number} uniqueId - the unique id to search for
  12856. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12857. */
  12858. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12859. for (var index = 0; index < this.meshes.length; index++) {
  12860. if (this.meshes[index].uniqueId === uniqueId) {
  12861. return this.meshes[index];
  12862. }
  12863. }
  12864. return null;
  12865. };
  12866. /**
  12867. * Get a the last added mesh found of a given ID
  12868. * @param {string} id - the id to search for
  12869. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12870. */
  12871. Scene.prototype.getLastMeshByID = function (id) {
  12872. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12873. if (this.meshes[index].id === id) {
  12874. return this.meshes[index];
  12875. }
  12876. }
  12877. return null;
  12878. };
  12879. /**
  12880. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12881. * @param {string} id - the id to search for
  12882. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12883. */
  12884. Scene.prototype.getLastEntryByID = function (id) {
  12885. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12886. if (this.meshes[index].id === id) {
  12887. return this.meshes[index];
  12888. }
  12889. }
  12890. for (index = this.cameras.length - 1; index >= 0; index--) {
  12891. if (this.cameras[index].id === id) {
  12892. return this.cameras[index];
  12893. }
  12894. }
  12895. for (index = this.lights.length - 1; index >= 0; index--) {
  12896. if (this.lights[index].id === id) {
  12897. return this.lights[index];
  12898. }
  12899. }
  12900. return null;
  12901. };
  12902. Scene.prototype.getNodeByName = function (name) {
  12903. var mesh = this.getMeshByName(name);
  12904. if (mesh) {
  12905. return mesh;
  12906. }
  12907. var light = this.getLightByName(name);
  12908. if (light) {
  12909. return light;
  12910. }
  12911. return this.getCameraByName(name);
  12912. };
  12913. Scene.prototype.getMeshByName = function (name) {
  12914. for (var index = 0; index < this.meshes.length; index++) {
  12915. if (this.meshes[index].name === name) {
  12916. return this.meshes[index];
  12917. }
  12918. }
  12919. return null;
  12920. };
  12921. Scene.prototype.getSoundByName = function (name) {
  12922. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12923. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12924. return this.mainSoundTrack.soundCollection[index];
  12925. }
  12926. }
  12927. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12928. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12929. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12930. return this.soundTracks[sdIndex].soundCollection[index];
  12931. }
  12932. }
  12933. }
  12934. return null;
  12935. };
  12936. Scene.prototype.getLastSkeletonByID = function (id) {
  12937. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12938. if (this.skeletons[index].id === id) {
  12939. return this.skeletons[index];
  12940. }
  12941. }
  12942. return null;
  12943. };
  12944. Scene.prototype.getSkeletonById = function (id) {
  12945. for (var index = 0; index < this.skeletons.length; index++) {
  12946. if (this.skeletons[index].id === id) {
  12947. return this.skeletons[index];
  12948. }
  12949. }
  12950. return null;
  12951. };
  12952. Scene.prototype.getSkeletonByName = function (name) {
  12953. for (var index = 0; index < this.skeletons.length; index++) {
  12954. if (this.skeletons[index].name === name) {
  12955. return this.skeletons[index];
  12956. }
  12957. }
  12958. return null;
  12959. };
  12960. Scene.prototype.isActiveMesh = function (mesh) {
  12961. return (this._activeMeshes.indexOf(mesh) !== -1);
  12962. };
  12963. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12964. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12965. var material = subMesh.getMaterial();
  12966. if (mesh.showSubMeshesBoundingBox) {
  12967. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12968. }
  12969. if (material) {
  12970. // Render targets
  12971. if (material.getRenderTargetTextures) {
  12972. if (this._processedMaterials.indexOf(material) === -1) {
  12973. this._processedMaterials.push(material);
  12974. this._renderTargets.concat(material.getRenderTargetTextures());
  12975. }
  12976. }
  12977. // Dispatch
  12978. this._activeIndices += subMesh.indexCount;
  12979. this._renderingManager.dispatch(subMesh);
  12980. }
  12981. }
  12982. };
  12983. Scene.prototype._evaluateActiveMeshes = function () {
  12984. this.activeCamera._activeMeshes.reset();
  12985. this._activeMeshes.reset();
  12986. this._renderingManager.reset();
  12987. this._processedMaterials.reset();
  12988. this._activeParticleSystems.reset();
  12989. this._activeSkeletons.reset();
  12990. this._boundingBoxRenderer.reset();
  12991. if (!this._frustumPlanes) {
  12992. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12993. }
  12994. else {
  12995. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12996. }
  12997. // Meshes
  12998. var meshes;
  12999. var len;
  13000. if (this._selectionOctree) {
  13001. var selection = this._selectionOctree.select(this._frustumPlanes);
  13002. meshes = selection.data;
  13003. len = selection.length;
  13004. }
  13005. else {
  13006. len = this.meshes.length;
  13007. meshes = this.meshes;
  13008. }
  13009. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13010. var mesh = meshes[meshIndex];
  13011. if (mesh.isBlocked) {
  13012. continue;
  13013. }
  13014. this._totalVertices += mesh.getTotalVertices();
  13015. if (!mesh.isReady() || !mesh.isEnabled()) {
  13016. continue;
  13017. }
  13018. mesh.computeWorldMatrix();
  13019. // Intersections
  13020. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13021. this._meshesForIntersections.pushNoDuplicate(mesh);
  13022. }
  13023. // Switch to current LOD
  13024. var meshLOD = mesh.getLOD(this.activeCamera);
  13025. if (!meshLOD) {
  13026. continue;
  13027. }
  13028. mesh._preActivate();
  13029. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13030. this._activeMeshes.push(mesh);
  13031. this.activeCamera._activeMeshes.push(mesh);
  13032. mesh._activate(this._renderId);
  13033. this._activeMesh(meshLOD);
  13034. }
  13035. }
  13036. // Particle systems
  13037. var beforeParticlesDate = BABYLON.Tools.Now;
  13038. if (this.particlesEnabled) {
  13039. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13040. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13041. var particleSystem = this.particleSystems[particleIndex];
  13042. if (!particleSystem.isStarted()) {
  13043. continue;
  13044. }
  13045. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13046. this._activeParticleSystems.push(particleSystem);
  13047. particleSystem.animate();
  13048. }
  13049. }
  13050. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13051. }
  13052. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13053. };
  13054. Scene.prototype._activeMesh = function (mesh) {
  13055. if (mesh.skeleton && this.skeletonsEnabled) {
  13056. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13057. }
  13058. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13059. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13060. }
  13061. if (mesh && mesh.subMeshes) {
  13062. // Submeshes Octrees
  13063. var len;
  13064. var subMeshes;
  13065. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13066. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13067. len = intersections.length;
  13068. subMeshes = intersections.data;
  13069. }
  13070. else {
  13071. subMeshes = mesh.subMeshes;
  13072. len = subMeshes.length;
  13073. }
  13074. for (var subIndex = 0; subIndex < len; subIndex++) {
  13075. var subMesh = subMeshes[subIndex];
  13076. this._evaluateSubMesh(subMesh, mesh);
  13077. }
  13078. }
  13079. };
  13080. Scene.prototype.updateTransformMatrix = function (force) {
  13081. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13082. };
  13083. Scene.prototype._renderForCamera = function (camera) {
  13084. var engine = this._engine;
  13085. this.activeCamera = camera;
  13086. if (!this.activeCamera)
  13087. throw new Error("Active camera not set");
  13088. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13089. // Viewport
  13090. engine.setViewport(this.activeCamera.viewport);
  13091. // Camera
  13092. this.resetCachedMaterial();
  13093. this._renderId++;
  13094. this.updateTransformMatrix();
  13095. if (this.beforeCameraRender) {
  13096. this.beforeCameraRender(this.activeCamera);
  13097. }
  13098. // Meshes
  13099. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13100. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13101. this._evaluateActiveMeshes();
  13102. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13103. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13104. // Skeletons
  13105. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13106. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13107. skeleton.prepare();
  13108. }
  13109. // Render targets
  13110. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13111. if (this.renderTargetsEnabled) {
  13112. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13113. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13114. var renderTarget = this._renderTargets.data[renderIndex];
  13115. if (renderTarget._shouldRender()) {
  13116. this._renderId++;
  13117. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13118. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13119. }
  13120. }
  13121. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13122. this._renderId++;
  13123. }
  13124. if (this._renderTargets.length > 0) {
  13125. engine.restoreDefaultFramebuffer();
  13126. }
  13127. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13128. // Prepare Frame
  13129. this.postProcessManager._prepareFrame();
  13130. var beforeRenderDate = BABYLON.Tools.Now;
  13131. // Backgrounds
  13132. if (this.layers.length) {
  13133. engine.setDepthBuffer(false);
  13134. var layerIndex;
  13135. var layer;
  13136. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13137. layer = this.layers[layerIndex];
  13138. if (layer.isBackground) {
  13139. layer.render();
  13140. }
  13141. }
  13142. engine.setDepthBuffer(true);
  13143. }
  13144. // Render
  13145. BABYLON.Tools.StartPerformanceCounter("Main render");
  13146. this._renderingManager.render(null, null, true, true);
  13147. BABYLON.Tools.EndPerformanceCounter("Main render");
  13148. // Bounding boxes
  13149. this._boundingBoxRenderer.render();
  13150. // Lens flares
  13151. if (this.lensFlaresEnabled) {
  13152. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13153. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13154. this.lensFlareSystems[lensFlareSystemIndex].render();
  13155. }
  13156. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13157. }
  13158. // Foregrounds
  13159. if (this.layers.length) {
  13160. engine.setDepthBuffer(false);
  13161. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13162. layer = this.layers[layerIndex];
  13163. if (!layer.isBackground) {
  13164. layer.render();
  13165. }
  13166. }
  13167. engine.setDepthBuffer(true);
  13168. }
  13169. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13170. // Finalize frame
  13171. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13172. // Update camera
  13173. this.activeCamera._updateFromScene();
  13174. // Reset some special arrays
  13175. this._renderTargets.reset();
  13176. if (this.afterCameraRender) {
  13177. this.afterCameraRender(this.activeCamera);
  13178. }
  13179. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13180. };
  13181. Scene.prototype._processSubCameras = function (camera) {
  13182. if (camera.subCameras.length === 0) {
  13183. this._renderForCamera(camera);
  13184. return;
  13185. }
  13186. // Sub-cameras
  13187. for (var index = 0; index < camera.subCameras.length; index++) {
  13188. this._renderForCamera(camera.subCameras[index]);
  13189. }
  13190. this.activeCamera = camera;
  13191. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13192. // Update camera
  13193. this.activeCamera._updateFromScene();
  13194. };
  13195. Scene.prototype._checkIntersections = function () {
  13196. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13197. var sourceMesh = this._meshesForIntersections.data[index];
  13198. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13199. var action = sourceMesh.actionManager.actions[actionIndex];
  13200. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13201. var parameters = action.getTriggerParameter();
  13202. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13203. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13204. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13205. if (areIntersecting && currentIntersectionInProgress === -1) {
  13206. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13207. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13208. sourceMesh._intersectionsInProgress.push(otherMesh);
  13209. }
  13210. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13211. sourceMesh._intersectionsInProgress.push(otherMesh);
  13212. }
  13213. }
  13214. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13215. //They intersected, and now they don't.
  13216. //is this trigger an exit trigger? execute an event.
  13217. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13218. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13219. }
  13220. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13221. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13222. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13223. }
  13224. }
  13225. }
  13226. }
  13227. }
  13228. };
  13229. Scene.prototype.render = function () {
  13230. var startDate = BABYLON.Tools.Now;
  13231. this._particlesDuration = 0;
  13232. this._spritesDuration = 0;
  13233. this._activeParticles = 0;
  13234. this._renderDuration = 0;
  13235. this._renderTargetsDuration = 0;
  13236. this._evaluateActiveMeshesDuration = 0;
  13237. this._totalVertices = 0;
  13238. this._activeIndices = 0;
  13239. this._activeBones = 0;
  13240. this.getEngine().resetDrawCalls();
  13241. this._meshesForIntersections.reset();
  13242. this.resetCachedMaterial();
  13243. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13244. // Actions
  13245. if (this.actionManager) {
  13246. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13247. }
  13248. //Simplification Queue
  13249. if (!this.simplificationQueue.running) {
  13250. this.simplificationQueue.executeNext();
  13251. }
  13252. // Before render
  13253. if (this.beforeRender) {
  13254. this.beforeRender();
  13255. }
  13256. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13257. this._onBeforeRenderCallbacks[callbackIndex]();
  13258. }
  13259. // Animations
  13260. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13261. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13262. this._animate();
  13263. // Physics
  13264. if (this._physicsEngine) {
  13265. BABYLON.Tools.StartPerformanceCounter("Physics");
  13266. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13267. BABYLON.Tools.EndPerformanceCounter("Physics");
  13268. }
  13269. // Customs render targets
  13270. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13271. var engine = this.getEngine();
  13272. var currentActiveCamera = this.activeCamera;
  13273. if (this.renderTargetsEnabled) {
  13274. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13275. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13276. var renderTarget = this.customRenderTargets[customIndex];
  13277. if (renderTarget._shouldRender()) {
  13278. this._renderId++;
  13279. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13280. if (!this.activeCamera)
  13281. throw new Error("Active camera not set");
  13282. // Viewport
  13283. engine.setViewport(this.activeCamera.viewport);
  13284. // Camera
  13285. this.updateTransformMatrix();
  13286. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13287. }
  13288. }
  13289. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13290. this._renderId++;
  13291. }
  13292. if (this.customRenderTargets.length > 0) {
  13293. engine.restoreDefaultFramebuffer();
  13294. }
  13295. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13296. this.activeCamera = currentActiveCamera;
  13297. // Procedural textures
  13298. if (this.proceduralTexturesEnabled) {
  13299. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13300. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13301. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13302. if (proceduralTexture._shouldRender()) {
  13303. proceduralTexture.render();
  13304. }
  13305. }
  13306. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13307. }
  13308. // Clear
  13309. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13310. // Shadows
  13311. if (this.shadowsEnabled) {
  13312. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13313. var light = this.lights[lightIndex];
  13314. var shadowGenerator = light.getShadowGenerator();
  13315. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13316. this._renderTargets.push(shadowGenerator.getShadowMap());
  13317. }
  13318. }
  13319. }
  13320. // Depth renderer
  13321. if (this._depthRenderer) {
  13322. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13323. }
  13324. // RenderPipeline
  13325. this.postProcessRenderPipelineManager.update();
  13326. // Multi-cameras?
  13327. if (this.activeCameras.length > 0) {
  13328. var currentRenderId = this._renderId;
  13329. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13330. this._renderId = currentRenderId;
  13331. this._processSubCameras(this.activeCameras[cameraIndex]);
  13332. }
  13333. }
  13334. else {
  13335. if (!this.activeCamera) {
  13336. throw new Error("No camera defined");
  13337. }
  13338. this._processSubCameras(this.activeCamera);
  13339. }
  13340. // Intersection checks
  13341. this._checkIntersections();
  13342. // Update the audio listener attached to the camera
  13343. this._updateAudioParameters();
  13344. // After render
  13345. if (this.afterRender) {
  13346. this.afterRender();
  13347. }
  13348. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13349. this._onAfterRenderCallbacks[callbackIndex]();
  13350. }
  13351. // Cleaning
  13352. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13353. this._toBeDisposed.data[index].dispose();
  13354. this._toBeDisposed[index] = null;
  13355. }
  13356. this._toBeDisposed.reset();
  13357. if (this.dumpNextRenderTargets) {
  13358. this.dumpNextRenderTargets = false;
  13359. }
  13360. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13361. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13362. };
  13363. Scene.prototype._updateAudioParameters = function () {
  13364. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13365. return;
  13366. }
  13367. var listeningCamera;
  13368. var audioEngine = BABYLON.Engine.audioEngine;
  13369. if (this.activeCameras.length > 0) {
  13370. listeningCamera = this.activeCameras[0];
  13371. }
  13372. else {
  13373. listeningCamera = this.activeCamera;
  13374. }
  13375. if (listeningCamera && audioEngine.canUseWebAudio) {
  13376. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13377. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13378. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13379. cameraDirection.normalize();
  13380. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13381. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13382. var sound = this.mainSoundTrack.soundCollection[i];
  13383. if (sound.useCustomAttenuation) {
  13384. sound.updateDistanceFromListener();
  13385. }
  13386. }
  13387. for (i = 0; i < this.soundTracks.length; i++) {
  13388. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13389. sound = this.soundTracks[i].soundCollection[j];
  13390. if (sound.useCustomAttenuation) {
  13391. sound.updateDistanceFromListener();
  13392. }
  13393. }
  13394. }
  13395. }
  13396. };
  13397. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13398. // Audio
  13399. get: function () {
  13400. return this._audioEnabled;
  13401. },
  13402. set: function (value) {
  13403. this._audioEnabled = value;
  13404. if (this._audioEnabled) {
  13405. this._enableAudio();
  13406. }
  13407. else {
  13408. this._disableAudio();
  13409. }
  13410. },
  13411. enumerable: true,
  13412. configurable: true
  13413. });
  13414. Scene.prototype._disableAudio = function () {
  13415. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13416. this.mainSoundTrack.soundCollection[i].pause();
  13417. }
  13418. for (i = 0; i < this.soundTracks.length; i++) {
  13419. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13420. this.soundTracks[i].soundCollection[j].pause();
  13421. }
  13422. }
  13423. };
  13424. Scene.prototype._enableAudio = function () {
  13425. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13426. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13427. this.mainSoundTrack.soundCollection[i].play();
  13428. }
  13429. }
  13430. for (i = 0; i < this.soundTracks.length; i++) {
  13431. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13432. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13433. this.soundTracks[i].soundCollection[j].play();
  13434. }
  13435. }
  13436. }
  13437. };
  13438. Object.defineProperty(Scene.prototype, "headphone", {
  13439. get: function () {
  13440. return this._headphone;
  13441. },
  13442. set: function (value) {
  13443. this._headphone = value;
  13444. if (this._headphone) {
  13445. this._switchAudioModeForHeadphones();
  13446. }
  13447. else {
  13448. this._switchAudioModeForNormalSpeakers();
  13449. }
  13450. },
  13451. enumerable: true,
  13452. configurable: true
  13453. });
  13454. Scene.prototype._switchAudioModeForHeadphones = function () {
  13455. this.mainSoundTrack.switchPanningModelToHRTF();
  13456. for (var i = 0; i < this.soundTracks.length; i++) {
  13457. this.soundTracks[i].switchPanningModelToHRTF();
  13458. }
  13459. };
  13460. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13461. this.mainSoundTrack.switchPanningModelToEqualPower();
  13462. for (var i = 0; i < this.soundTracks.length; i++) {
  13463. this.soundTracks[i].switchPanningModelToEqualPower();
  13464. }
  13465. };
  13466. Scene.prototype.enableDepthRenderer = function () {
  13467. if (this._depthRenderer) {
  13468. return this._depthRenderer;
  13469. }
  13470. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13471. return this._depthRenderer;
  13472. };
  13473. Scene.prototype.disableDepthRenderer = function () {
  13474. if (!this._depthRenderer) {
  13475. return;
  13476. }
  13477. this._depthRenderer.dispose();
  13478. this._depthRenderer = null;
  13479. };
  13480. Scene.prototype.dispose = function () {
  13481. this.beforeRender = null;
  13482. this.afterRender = null;
  13483. this.skeletons = [];
  13484. this._boundingBoxRenderer.dispose();
  13485. if (this._depthRenderer) {
  13486. this._depthRenderer.dispose();
  13487. }
  13488. // Debug layer
  13489. this.debugLayer.hide();
  13490. // Events
  13491. if (this.onDispose) {
  13492. this.onDispose();
  13493. }
  13494. this._onBeforeRenderCallbacks = [];
  13495. this._onAfterRenderCallbacks = [];
  13496. this.detachControl();
  13497. // Release sounds & sounds tracks
  13498. this.disposeSounds();
  13499. // Detach cameras
  13500. var canvas = this._engine.getRenderingCanvas();
  13501. var index;
  13502. for (index = 0; index < this.cameras.length; index++) {
  13503. this.cameras[index].detachControl(canvas);
  13504. }
  13505. // Release lights
  13506. while (this.lights.length) {
  13507. this.lights[0].dispose();
  13508. }
  13509. // Release meshes
  13510. while (this.meshes.length) {
  13511. this.meshes[0].dispose(true);
  13512. }
  13513. // Release cameras
  13514. while (this.cameras.length) {
  13515. this.cameras[0].dispose();
  13516. }
  13517. // Release materials
  13518. while (this.materials.length) {
  13519. this.materials[0].dispose();
  13520. }
  13521. // Release particles
  13522. while (this.particleSystems.length) {
  13523. this.particleSystems[0].dispose();
  13524. }
  13525. // Release sprites
  13526. while (this.spriteManagers.length) {
  13527. this.spriteManagers[0].dispose();
  13528. }
  13529. // Release layers
  13530. while (this.layers.length) {
  13531. this.layers[0].dispose();
  13532. }
  13533. // Release textures
  13534. while (this.textures.length) {
  13535. this.textures[0].dispose();
  13536. }
  13537. // Post-processes
  13538. this.postProcessManager.dispose();
  13539. // Physics
  13540. if (this._physicsEngine) {
  13541. this.disablePhysicsEngine();
  13542. }
  13543. // Remove from engine
  13544. index = this._engine.scenes.indexOf(this);
  13545. if (index > -1) {
  13546. this._engine.scenes.splice(index, 1);
  13547. }
  13548. this._engine.wipeCaches();
  13549. };
  13550. // Release sounds & sounds tracks
  13551. Scene.prototype.disposeSounds = function () {
  13552. this.mainSoundTrack.dispose();
  13553. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13554. this.soundTracks[scIndex].dispose();
  13555. }
  13556. };
  13557. // Octrees
  13558. Scene.prototype.getWorldExtends = function () {
  13559. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13560. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13561. for (var index = 0; index < this.meshes.length; index++) {
  13562. var mesh = this.meshes[index];
  13563. mesh.computeWorldMatrix(true);
  13564. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13565. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13566. BABYLON.Tools.CheckExtends(minBox, min, max);
  13567. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13568. }
  13569. return {
  13570. min: min,
  13571. max: max
  13572. };
  13573. };
  13574. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13575. if (maxCapacity === void 0) { maxCapacity = 64; }
  13576. if (maxDepth === void 0) { maxDepth = 2; }
  13577. if (!this._selectionOctree) {
  13578. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13579. }
  13580. var worldExtends = this.getWorldExtends();
  13581. // Update octree
  13582. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13583. return this._selectionOctree;
  13584. };
  13585. // Picking
  13586. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13587. var engine = this._engine;
  13588. if (!camera) {
  13589. if (!this.activeCamera)
  13590. throw new Error("Active camera not set");
  13591. camera = this.activeCamera;
  13592. }
  13593. var cameraViewport = camera.viewport;
  13594. var viewport = cameraViewport.toGlobal(engine);
  13595. // Moving coordinates to local viewport world
  13596. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13597. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13598. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13599. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13600. };
  13601. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13602. var pickingInfo = null;
  13603. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13604. var mesh = this.meshes[meshIndex];
  13605. if (predicate) {
  13606. if (!predicate(mesh)) {
  13607. continue;
  13608. }
  13609. }
  13610. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13611. continue;
  13612. }
  13613. var world = mesh.getWorldMatrix();
  13614. var ray = rayFunction(world);
  13615. var result = mesh.intersects(ray, fastCheck);
  13616. if (!result || !result.hit)
  13617. continue;
  13618. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13619. continue;
  13620. pickingInfo = result;
  13621. if (fastCheck) {
  13622. break;
  13623. }
  13624. }
  13625. return pickingInfo || new BABYLON.PickingInfo();
  13626. };
  13627. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13628. var _this = this;
  13629. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13630. /// <param name="x">X position on screen</param>
  13631. /// <param name="y">Y position on screen</param>
  13632. /// <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>
  13633. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13634. /// <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>
  13635. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13636. };
  13637. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13638. var _this = this;
  13639. return this._internalPick(function (world) {
  13640. if (!_this._pickWithRayInverseMatrix) {
  13641. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13642. }
  13643. world.invertToRef(_this._pickWithRayInverseMatrix);
  13644. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13645. }, predicate, fastCheck);
  13646. };
  13647. Scene.prototype.setPointerOverMesh = function (mesh) {
  13648. if (this._pointerOverMesh === mesh) {
  13649. return;
  13650. }
  13651. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13652. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13653. }
  13654. this._pointerOverMesh = mesh;
  13655. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13656. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13657. }
  13658. };
  13659. Scene.prototype.getPointerOverMesh = function () {
  13660. return this._pointerOverMesh;
  13661. };
  13662. // Physics
  13663. Scene.prototype.getPhysicsEngine = function () {
  13664. return this._physicsEngine;
  13665. };
  13666. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13667. if (this._physicsEngine) {
  13668. return true;
  13669. }
  13670. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13671. if (!this._physicsEngine.isSupported()) {
  13672. this._physicsEngine = null;
  13673. return false;
  13674. }
  13675. this._physicsEngine._initialize(gravity);
  13676. return true;
  13677. };
  13678. Scene.prototype.disablePhysicsEngine = function () {
  13679. if (!this._physicsEngine) {
  13680. return;
  13681. }
  13682. this._physicsEngine.dispose();
  13683. this._physicsEngine = undefined;
  13684. };
  13685. Scene.prototype.isPhysicsEnabled = function () {
  13686. return this._physicsEngine !== undefined;
  13687. };
  13688. Scene.prototype.setGravity = function (gravity) {
  13689. if (!this._physicsEngine) {
  13690. return;
  13691. }
  13692. this._physicsEngine._setGravity(gravity);
  13693. };
  13694. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13695. if (parts.parts) {
  13696. options = parts;
  13697. parts = parts.parts;
  13698. }
  13699. if (!this._physicsEngine) {
  13700. return null;
  13701. }
  13702. for (var index = 0; index < parts.length; index++) {
  13703. var mesh = parts[index].mesh;
  13704. mesh._physicImpostor = parts[index].impostor;
  13705. mesh._physicsMass = options.mass / parts.length;
  13706. mesh._physicsFriction = options.friction;
  13707. mesh._physicRestitution = options.restitution;
  13708. }
  13709. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13710. };
  13711. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13712. for (var index = 0; index < compound.parts.length; index++) {
  13713. var mesh = compound.parts[index].mesh;
  13714. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13715. this._physicsEngine._unregisterMesh(mesh);
  13716. }
  13717. };
  13718. // Misc.
  13719. Scene.prototype.createDefaultCameraOrLight = function () {
  13720. // Light
  13721. if (this.lights.length === 0) {
  13722. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13723. }
  13724. // Camera
  13725. if (!this.activeCamera) {
  13726. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13727. // Compute position
  13728. var worldExtends = this.getWorldExtends();
  13729. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13730. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13731. camera.setTarget(worldCenter);
  13732. this.activeCamera = camera;
  13733. }
  13734. };
  13735. // Tags
  13736. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13737. if (tagsQuery === undefined) {
  13738. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13739. return list;
  13740. }
  13741. var listByTags = [];
  13742. forEach = forEach || (function (item) { return; });
  13743. for (var i in list) {
  13744. var item = list[i];
  13745. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13746. listByTags.push(item);
  13747. forEach(item);
  13748. }
  13749. }
  13750. return listByTags;
  13751. };
  13752. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13753. return this._getByTags(this.meshes, tagsQuery, forEach);
  13754. };
  13755. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13756. return this._getByTags(this.cameras, tagsQuery, forEach);
  13757. };
  13758. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13759. return this._getByTags(this.lights, tagsQuery, forEach);
  13760. };
  13761. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13762. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13763. };
  13764. // Statics
  13765. Scene._FOGMODE_NONE = 0;
  13766. Scene._FOGMODE_EXP = 1;
  13767. Scene._FOGMODE_EXP2 = 2;
  13768. Scene._FOGMODE_LINEAR = 3;
  13769. Scene.MinDeltaTime = 1.0;
  13770. Scene.MaxDeltaTime = 1000.0;
  13771. return Scene;
  13772. })();
  13773. BABYLON.Scene = Scene;
  13774. })(BABYLON || (BABYLON = {}));
  13775. //# sourceMappingURL=babylon.scene.js.map
  13776. var BABYLON;
  13777. (function (BABYLON) {
  13778. var VertexBuffer = (function () {
  13779. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13780. if (engine instanceof BABYLON.Mesh) {
  13781. this._engine = engine.getScene().getEngine();
  13782. }
  13783. else {
  13784. this._engine = engine;
  13785. }
  13786. this._updatable = updatable;
  13787. this._data = data;
  13788. if (!postponeInternalCreation) {
  13789. this.create();
  13790. }
  13791. this._kind = kind;
  13792. if (stride) {
  13793. this._strideSize = stride;
  13794. return;
  13795. }
  13796. // Deduce stride from kind
  13797. switch (kind) {
  13798. case VertexBuffer.PositionKind:
  13799. this._strideSize = 3;
  13800. break;
  13801. case VertexBuffer.NormalKind:
  13802. this._strideSize = 3;
  13803. break;
  13804. case VertexBuffer.UVKind:
  13805. this._strideSize = 2;
  13806. break;
  13807. case VertexBuffer.UV2Kind:
  13808. this._strideSize = 2;
  13809. break;
  13810. case VertexBuffer.ColorKind:
  13811. this._strideSize = 4;
  13812. break;
  13813. case VertexBuffer.MatricesIndicesKind:
  13814. this._strideSize = 4;
  13815. break;
  13816. case VertexBuffer.MatricesWeightsKind:
  13817. this._strideSize = 4;
  13818. break;
  13819. }
  13820. }
  13821. // Properties
  13822. VertexBuffer.prototype.isUpdatable = function () {
  13823. return this._updatable;
  13824. };
  13825. VertexBuffer.prototype.getData = function () {
  13826. return this._data;
  13827. };
  13828. VertexBuffer.prototype.getBuffer = function () {
  13829. return this._buffer;
  13830. };
  13831. VertexBuffer.prototype.getStrideSize = function () {
  13832. return this._strideSize;
  13833. };
  13834. // Methods
  13835. VertexBuffer.prototype.create = function (data) {
  13836. if (!data && this._buffer) {
  13837. return; // nothing to do
  13838. }
  13839. data = data || this._data;
  13840. if (!this._buffer) {
  13841. if (this._updatable) {
  13842. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13843. }
  13844. else {
  13845. this._buffer = this._engine.createVertexBuffer(data);
  13846. }
  13847. }
  13848. if (this._updatable) {
  13849. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13850. this._data = data;
  13851. }
  13852. };
  13853. VertexBuffer.prototype.update = function (data) {
  13854. this.create(data);
  13855. };
  13856. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13857. if (!this._buffer) {
  13858. return;
  13859. }
  13860. if (this._updatable) {
  13861. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13862. this._data = null;
  13863. }
  13864. };
  13865. VertexBuffer.prototype.dispose = function () {
  13866. if (!this._buffer) {
  13867. return;
  13868. }
  13869. if (this._engine._releaseBuffer(this._buffer)) {
  13870. this._buffer = null;
  13871. }
  13872. };
  13873. Object.defineProperty(VertexBuffer, "PositionKind", {
  13874. get: function () {
  13875. return VertexBuffer._PositionKind;
  13876. },
  13877. enumerable: true,
  13878. configurable: true
  13879. });
  13880. Object.defineProperty(VertexBuffer, "NormalKind", {
  13881. get: function () {
  13882. return VertexBuffer._NormalKind;
  13883. },
  13884. enumerable: true,
  13885. configurable: true
  13886. });
  13887. Object.defineProperty(VertexBuffer, "UVKind", {
  13888. get: function () {
  13889. return VertexBuffer._UVKind;
  13890. },
  13891. enumerable: true,
  13892. configurable: true
  13893. });
  13894. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13895. get: function () {
  13896. return VertexBuffer._UV2Kind;
  13897. },
  13898. enumerable: true,
  13899. configurable: true
  13900. });
  13901. Object.defineProperty(VertexBuffer, "ColorKind", {
  13902. get: function () {
  13903. return VertexBuffer._ColorKind;
  13904. },
  13905. enumerable: true,
  13906. configurable: true
  13907. });
  13908. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13909. get: function () {
  13910. return VertexBuffer._MatricesIndicesKind;
  13911. },
  13912. enumerable: true,
  13913. configurable: true
  13914. });
  13915. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13916. get: function () {
  13917. return VertexBuffer._MatricesWeightsKind;
  13918. },
  13919. enumerable: true,
  13920. configurable: true
  13921. });
  13922. // Enums
  13923. VertexBuffer._PositionKind = "position";
  13924. VertexBuffer._NormalKind = "normal";
  13925. VertexBuffer._UVKind = "uv";
  13926. VertexBuffer._UV2Kind = "uv2";
  13927. VertexBuffer._ColorKind = "color";
  13928. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13929. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13930. return VertexBuffer;
  13931. })();
  13932. BABYLON.VertexBuffer = VertexBuffer;
  13933. })(BABYLON || (BABYLON = {}));
  13934. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13935. var __extends = this.__extends || function (d, b) {
  13936. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13937. function __() { this.constructor = d; }
  13938. __.prototype = b.prototype;
  13939. d.prototype = new __();
  13940. };
  13941. var BABYLON;
  13942. (function (BABYLON) {
  13943. /**
  13944. * Creates an instance based on a source mesh.
  13945. */
  13946. var InstancedMesh = (function (_super) {
  13947. __extends(InstancedMesh, _super);
  13948. function InstancedMesh(name, source) {
  13949. _super.call(this, name, source.getScene());
  13950. source.instances.push(this);
  13951. this._sourceMesh = source;
  13952. this.position.copyFrom(source.position);
  13953. this.rotation.copyFrom(source.rotation);
  13954. this.scaling.copyFrom(source.scaling);
  13955. if (source.rotationQuaternion) {
  13956. this.rotationQuaternion = source.rotationQuaternion.clone();
  13957. }
  13958. this.infiniteDistance = source.infiniteDistance;
  13959. this.setPivotMatrix(source.getPivotMatrix());
  13960. this.refreshBoundingInfo();
  13961. this._syncSubMeshes();
  13962. }
  13963. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13964. // Methods
  13965. get: function () {
  13966. return this._sourceMesh.receiveShadows;
  13967. },
  13968. enumerable: true,
  13969. configurable: true
  13970. });
  13971. Object.defineProperty(InstancedMesh.prototype, "material", {
  13972. get: function () {
  13973. return this._sourceMesh.material;
  13974. },
  13975. enumerable: true,
  13976. configurable: true
  13977. });
  13978. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13979. get: function () {
  13980. return this._sourceMesh.visibility;
  13981. },
  13982. enumerable: true,
  13983. configurable: true
  13984. });
  13985. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13986. get: function () {
  13987. return this._sourceMesh.skeleton;
  13988. },
  13989. enumerable: true,
  13990. configurable: true
  13991. });
  13992. InstancedMesh.prototype.getTotalVertices = function () {
  13993. return this._sourceMesh.getTotalVertices();
  13994. };
  13995. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13996. get: function () {
  13997. return this._sourceMesh;
  13998. },
  13999. enumerable: true,
  14000. configurable: true
  14001. });
  14002. InstancedMesh.prototype.getVerticesData = function (kind) {
  14003. return this._sourceMesh.getVerticesData(kind);
  14004. };
  14005. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14006. return this._sourceMesh.isVerticesDataPresent(kind);
  14007. };
  14008. InstancedMesh.prototype.getIndices = function () {
  14009. return this._sourceMesh.getIndices();
  14010. };
  14011. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14012. get: function () {
  14013. return this._sourceMesh._positions;
  14014. },
  14015. enumerable: true,
  14016. configurable: true
  14017. });
  14018. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14019. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14020. if (data) {
  14021. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14022. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14023. }
  14024. this._updateBoundingInfo();
  14025. };
  14026. InstancedMesh.prototype._preActivate = function () {
  14027. if (this._currentLOD) {
  14028. this._currentLOD._preActivate();
  14029. }
  14030. };
  14031. InstancedMesh.prototype._activate = function (renderId) {
  14032. if (this._currentLOD) {
  14033. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14034. }
  14035. };
  14036. InstancedMesh.prototype.getLOD = function (camera) {
  14037. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14038. if (this._currentLOD === this.sourceMesh) {
  14039. return this;
  14040. }
  14041. return this._currentLOD;
  14042. };
  14043. InstancedMesh.prototype._syncSubMeshes = function () {
  14044. this.releaseSubMeshes();
  14045. if (this._sourceMesh.subMeshes) {
  14046. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14047. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14048. }
  14049. }
  14050. };
  14051. InstancedMesh.prototype._generatePointsArray = function () {
  14052. return this._sourceMesh._generatePointsArray();
  14053. };
  14054. // Clone
  14055. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14056. var result = this._sourceMesh.createInstance(name);
  14057. // Deep copy
  14058. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14059. // Bounding info
  14060. this.refreshBoundingInfo();
  14061. // Parent
  14062. if (newParent) {
  14063. result.parent = newParent;
  14064. }
  14065. if (!doNotCloneChildren) {
  14066. // Children
  14067. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14068. var mesh = this.getScene().meshes[index];
  14069. if (mesh.parent === this) {
  14070. mesh.clone(mesh.name, result);
  14071. }
  14072. }
  14073. }
  14074. result.computeWorldMatrix(true);
  14075. return result;
  14076. };
  14077. // Dispoe
  14078. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14079. // Remove from mesh
  14080. var index = this._sourceMesh.instances.indexOf(this);
  14081. this._sourceMesh.instances.splice(index, 1);
  14082. _super.prototype.dispose.call(this, doNotRecurse);
  14083. };
  14084. return InstancedMesh;
  14085. })(BABYLON.AbstractMesh);
  14086. BABYLON.InstancedMesh = InstancedMesh;
  14087. })(BABYLON || (BABYLON = {}));
  14088. //# sourceMappingURL=babylon.instancedMesh.js.map
  14089. var __extends = this.__extends || function (d, b) {
  14090. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14091. function __() { this.constructor = d; }
  14092. __.prototype = b.prototype;
  14093. d.prototype = new __();
  14094. };
  14095. var BABYLON;
  14096. (function (BABYLON) {
  14097. var _InstancesBatch = (function () {
  14098. function _InstancesBatch() {
  14099. this.mustReturn = false;
  14100. this.visibleInstances = new Array();
  14101. this.renderSelf = new Array();
  14102. }
  14103. return _InstancesBatch;
  14104. })();
  14105. BABYLON._InstancesBatch = _InstancesBatch;
  14106. var Mesh = (function (_super) {
  14107. __extends(Mesh, _super);
  14108. /**
  14109. * @constructor
  14110. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14111. * @param {Scene} scene - The scene to add this mesh to.
  14112. * @param {Node} parent - The parent of this mesh, if it has one
  14113. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14114. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14115. * When false, achieved by calling a clone(), also passing False.
  14116. * This will make creation of children, recursive.
  14117. */
  14118. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14119. if (parent === void 0) { parent = null; }
  14120. _super.call(this, name, scene);
  14121. // Members
  14122. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14123. this.instances = new Array();
  14124. this._LODLevels = new Array();
  14125. this._onBeforeRenderCallbacks = new Array();
  14126. this._onAfterRenderCallbacks = new Array();
  14127. this._visibleInstances = {};
  14128. this._renderIdForInstances = new Array();
  14129. this._batchCache = new _InstancesBatch();
  14130. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14131. this._sideOrientation = Mesh._DEFAULTSIDE;
  14132. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14133. if (source) {
  14134. // Geometry
  14135. if (source._geometry) {
  14136. source._geometry.applyToMesh(this);
  14137. }
  14138. // Deep copy
  14139. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14140. // Material
  14141. this.material = source.material;
  14142. if (!doNotCloneChildren) {
  14143. // Children
  14144. for (var index = 0; index < scene.meshes.length; index++) {
  14145. var mesh = scene.meshes[index];
  14146. if (mesh.parent === source) {
  14147. // doNotCloneChildren is always going to be False
  14148. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14149. }
  14150. }
  14151. }
  14152. // Particles
  14153. for (index = 0; index < scene.particleSystems.length; index++) {
  14154. var system = scene.particleSystems[index];
  14155. if (system.emitter === source) {
  14156. system.clone(system.name, this);
  14157. }
  14158. }
  14159. this.computeWorldMatrix(true);
  14160. }
  14161. // Parent
  14162. if (parent !== null) {
  14163. this.parent = parent;
  14164. }
  14165. }
  14166. Object.defineProperty(Mesh, "FRONTSIDE", {
  14167. get: function () {
  14168. return Mesh._FRONTSIDE;
  14169. },
  14170. enumerable: true,
  14171. configurable: true
  14172. });
  14173. Object.defineProperty(Mesh, "BACKSIDE", {
  14174. get: function () {
  14175. return Mesh._BACKSIDE;
  14176. },
  14177. enumerable: true,
  14178. configurable: true
  14179. });
  14180. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14181. get: function () {
  14182. return Mesh._DOUBLESIDE;
  14183. },
  14184. enumerable: true,
  14185. configurable: true
  14186. });
  14187. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14188. get: function () {
  14189. return Mesh._DEFAULTSIDE;
  14190. },
  14191. enumerable: true,
  14192. configurable: true
  14193. });
  14194. Object.defineProperty(Mesh, "NO_CAP", {
  14195. get: function () {
  14196. return Mesh._NO_CAP;
  14197. },
  14198. enumerable: true,
  14199. configurable: true
  14200. });
  14201. Object.defineProperty(Mesh, "CAP_START", {
  14202. get: function () {
  14203. return Mesh._CAP_START;
  14204. },
  14205. enumerable: true,
  14206. configurable: true
  14207. });
  14208. Object.defineProperty(Mesh, "CAP_END", {
  14209. get: function () {
  14210. return Mesh._CAP_END;
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. Object.defineProperty(Mesh, "CAP_ALL", {
  14216. get: function () {
  14217. return Mesh._CAP_ALL;
  14218. },
  14219. enumerable: true,
  14220. configurable: true
  14221. });
  14222. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14223. // Methods
  14224. get: function () {
  14225. return this._LODLevels.length > 0;
  14226. },
  14227. enumerable: true,
  14228. configurable: true
  14229. });
  14230. Mesh.prototype._sortLODLevels = function () {
  14231. this._LODLevels.sort(function (a, b) {
  14232. if (a.distance < b.distance) {
  14233. return 1;
  14234. }
  14235. if (a.distance > b.distance) {
  14236. return -1;
  14237. }
  14238. return 0;
  14239. });
  14240. };
  14241. /**
  14242. * Add a mesh as LOD level triggered at the given distance.
  14243. * @param {number} distance - the distance from the center of the object to show this level
  14244. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14245. * @return {BABYLON.Mesh} this mesh (for chaining)
  14246. */
  14247. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14248. if (mesh && mesh._masterMesh) {
  14249. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14250. return this;
  14251. }
  14252. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14253. this._LODLevels.push(level);
  14254. if (mesh) {
  14255. mesh._masterMesh = this;
  14256. }
  14257. this._sortLODLevels();
  14258. return this;
  14259. };
  14260. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14261. for (var index = 0; index < this._LODLevels.length; index++) {
  14262. var level = this._LODLevels[index];
  14263. if (level.distance === distance) {
  14264. return level.mesh;
  14265. }
  14266. }
  14267. return null;
  14268. };
  14269. /**
  14270. * Remove a mesh from the LOD array
  14271. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14272. * @return {BABYLON.Mesh} this mesh (for chaining)
  14273. */
  14274. Mesh.prototype.removeLODLevel = function (mesh) {
  14275. for (var index = 0; index < this._LODLevels.length; index++) {
  14276. if (this._LODLevels[index].mesh === mesh) {
  14277. this._LODLevels.splice(index, 1);
  14278. if (mesh) {
  14279. mesh._masterMesh = null;
  14280. }
  14281. }
  14282. }
  14283. this._sortLODLevels();
  14284. return this;
  14285. };
  14286. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14287. if (!this._LODLevels || this._LODLevels.length === 0) {
  14288. return this;
  14289. }
  14290. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14291. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14292. if (this.onLODLevelSelection) {
  14293. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14294. }
  14295. return this;
  14296. }
  14297. for (var index = 0; index < this._LODLevels.length; index++) {
  14298. var level = this._LODLevels[index];
  14299. if (level.distance < distanceToCamera) {
  14300. if (level.mesh) {
  14301. level.mesh._preActivate();
  14302. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14303. }
  14304. if (this.onLODLevelSelection) {
  14305. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14306. }
  14307. return level.mesh;
  14308. }
  14309. }
  14310. if (this.onLODLevelSelection) {
  14311. this.onLODLevelSelection(distanceToCamera, this, this);
  14312. }
  14313. return this;
  14314. };
  14315. Object.defineProperty(Mesh.prototype, "geometry", {
  14316. get: function () {
  14317. return this._geometry;
  14318. },
  14319. enumerable: true,
  14320. configurable: true
  14321. });
  14322. Mesh.prototype.getTotalVertices = function () {
  14323. if (!this._geometry) {
  14324. return 0;
  14325. }
  14326. return this._geometry.getTotalVertices();
  14327. };
  14328. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14329. if (!this._geometry) {
  14330. return null;
  14331. }
  14332. return this._geometry.getVerticesData(kind, copyWhenShared);
  14333. };
  14334. Mesh.prototype.getVertexBuffer = function (kind) {
  14335. if (!this._geometry) {
  14336. return undefined;
  14337. }
  14338. return this._geometry.getVertexBuffer(kind);
  14339. };
  14340. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14341. if (!this._geometry) {
  14342. if (this._delayInfo) {
  14343. return this._delayInfo.indexOf(kind) !== -1;
  14344. }
  14345. return false;
  14346. }
  14347. return this._geometry.isVerticesDataPresent(kind);
  14348. };
  14349. Mesh.prototype.getVerticesDataKinds = function () {
  14350. if (!this._geometry) {
  14351. var result = [];
  14352. if (this._delayInfo) {
  14353. for (var kind in this._delayInfo) {
  14354. result.push(kind);
  14355. }
  14356. }
  14357. return result;
  14358. }
  14359. return this._geometry.getVerticesDataKinds();
  14360. };
  14361. Mesh.prototype.getTotalIndices = function () {
  14362. if (!this._geometry) {
  14363. return 0;
  14364. }
  14365. return this._geometry.getTotalIndices();
  14366. };
  14367. Mesh.prototype.getIndices = function (copyWhenShared) {
  14368. if (!this._geometry) {
  14369. return [];
  14370. }
  14371. return this._geometry.getIndices(copyWhenShared);
  14372. };
  14373. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14374. get: function () {
  14375. return this._masterMesh !== null && this._masterMesh !== undefined;
  14376. },
  14377. enumerable: true,
  14378. configurable: true
  14379. });
  14380. Mesh.prototype.isReady = function () {
  14381. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14382. return false;
  14383. }
  14384. return _super.prototype.isReady.call(this);
  14385. };
  14386. Mesh.prototype.isDisposed = function () {
  14387. return this._isDisposed;
  14388. };
  14389. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14390. get: function () {
  14391. return this._sideOrientation;
  14392. },
  14393. set: function (sideO) {
  14394. this._sideOrientation = sideO;
  14395. },
  14396. enumerable: true,
  14397. configurable: true
  14398. });
  14399. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14400. get: function () {
  14401. return this._areNormalsFrozen;
  14402. },
  14403. enumerable: true,
  14404. configurable: true
  14405. });
  14406. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14407. Mesh.prototype.freezeNormals = function () {
  14408. this._areNormalsFrozen = true;
  14409. };
  14410. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14411. Mesh.prototype.unfreezeNormals = function () {
  14412. this._areNormalsFrozen = false;
  14413. };
  14414. // Methods
  14415. Mesh.prototype._preActivate = function () {
  14416. var sceneRenderId = this.getScene().getRenderId();
  14417. if (this._preActivateId === sceneRenderId) {
  14418. return;
  14419. }
  14420. this._preActivateId = sceneRenderId;
  14421. this._visibleInstances = null;
  14422. };
  14423. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14424. if (!this._visibleInstances) {
  14425. this._visibleInstances = {};
  14426. this._visibleInstances.defaultRenderId = renderId;
  14427. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14428. }
  14429. if (!this._visibleInstances[renderId]) {
  14430. this._visibleInstances[renderId] = new Array();
  14431. }
  14432. this._visibleInstances[renderId].push(instance);
  14433. };
  14434. Mesh.prototype.refreshBoundingInfo = function () {
  14435. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14436. if (data) {
  14437. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14438. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14439. }
  14440. if (this.subMeshes) {
  14441. for (var index = 0; index < this.subMeshes.length; index++) {
  14442. this.subMeshes[index].refreshBoundingInfo();
  14443. }
  14444. }
  14445. this._updateBoundingInfo();
  14446. };
  14447. Mesh.prototype._createGlobalSubMesh = function () {
  14448. var totalVertices = this.getTotalVertices();
  14449. if (!totalVertices || !this.getIndices()) {
  14450. return null;
  14451. }
  14452. this.releaseSubMeshes();
  14453. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14454. };
  14455. Mesh.prototype.subdivide = function (count) {
  14456. if (count < 1) {
  14457. return;
  14458. }
  14459. var totalIndices = this.getTotalIndices();
  14460. var subdivisionSize = (totalIndices / count) | 0;
  14461. var offset = 0;
  14462. // Ensure that subdivisionSize is a multiple of 3
  14463. while (subdivisionSize % 3 !== 0) {
  14464. subdivisionSize++;
  14465. }
  14466. this.releaseSubMeshes();
  14467. for (var index = 0; index < count; index++) {
  14468. if (offset >= totalIndices) {
  14469. break;
  14470. }
  14471. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14472. offset += subdivisionSize;
  14473. }
  14474. this.synchronizeInstances();
  14475. };
  14476. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14477. if (kind instanceof Array) {
  14478. var temp = data;
  14479. data = kind;
  14480. kind = temp;
  14481. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14482. }
  14483. if (!this._geometry) {
  14484. var vertexData = new BABYLON.VertexData();
  14485. vertexData.set(data, kind);
  14486. var scene = this.getScene();
  14487. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14488. }
  14489. else {
  14490. this._geometry.setVerticesData(kind, data, updatable, stride);
  14491. }
  14492. };
  14493. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14494. if (!this._geometry) {
  14495. return;
  14496. }
  14497. if (!makeItUnique) {
  14498. this._geometry.updateVerticesData(kind, data, updateExtends);
  14499. }
  14500. else {
  14501. this.makeGeometryUnique();
  14502. this.updateVerticesData(kind, data, updateExtends, false);
  14503. }
  14504. };
  14505. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14506. if (!this._geometry) {
  14507. return;
  14508. }
  14509. if (!makeItUnique) {
  14510. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14511. }
  14512. else {
  14513. this.makeGeometryUnique();
  14514. this.updateVerticesDataDirectly(kind, data, offset, false);
  14515. }
  14516. };
  14517. // Mesh positions update function :
  14518. // updates the mesh positions according to the positionFunction returned values.
  14519. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14520. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14521. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14522. if (computeNormals === void 0) { computeNormals = true; }
  14523. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14524. positionFunction(positions);
  14525. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14526. if (computeNormals) {
  14527. var indices = this.getIndices();
  14528. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14529. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14530. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14531. }
  14532. };
  14533. Mesh.prototype.makeGeometryUnique = function () {
  14534. if (!this._geometry) {
  14535. return;
  14536. }
  14537. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14538. geometry.applyToMesh(this);
  14539. };
  14540. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14541. if (!this._geometry) {
  14542. var vertexData = new BABYLON.VertexData();
  14543. vertexData.indices = indices;
  14544. var scene = this.getScene();
  14545. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14546. }
  14547. else {
  14548. this._geometry.setIndices(indices, totalVertices);
  14549. }
  14550. };
  14551. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14552. var engine = this.getScene().getEngine();
  14553. // Wireframe
  14554. var indexToBind;
  14555. switch (fillMode) {
  14556. case BABYLON.Material.PointFillMode:
  14557. indexToBind = null;
  14558. break;
  14559. case BABYLON.Material.WireFrameFillMode:
  14560. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14561. break;
  14562. default:
  14563. case BABYLON.Material.TriangleFillMode:
  14564. indexToBind = this._geometry.getIndexBuffer();
  14565. break;
  14566. }
  14567. // VBOs
  14568. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14569. };
  14570. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14571. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14572. return;
  14573. }
  14574. var engine = this.getScene().getEngine();
  14575. // Draw order
  14576. switch (fillMode) {
  14577. case BABYLON.Material.PointFillMode:
  14578. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14579. break;
  14580. case BABYLON.Material.WireFrameFillMode:
  14581. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14582. break;
  14583. default:
  14584. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14585. }
  14586. };
  14587. Mesh.prototype.registerBeforeRender = function (func) {
  14588. this._onBeforeRenderCallbacks.push(func);
  14589. };
  14590. Mesh.prototype.unregisterBeforeRender = function (func) {
  14591. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14592. if (index > -1) {
  14593. this._onBeforeRenderCallbacks.splice(index, 1);
  14594. }
  14595. };
  14596. Mesh.prototype.registerAfterRender = function (func) {
  14597. this._onAfterRenderCallbacks.push(func);
  14598. };
  14599. Mesh.prototype.unregisterAfterRender = function (func) {
  14600. var index = this._onAfterRenderCallbacks.indexOf(func);
  14601. if (index > -1) {
  14602. this._onAfterRenderCallbacks.splice(index, 1);
  14603. }
  14604. };
  14605. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14606. var scene = this.getScene();
  14607. this._batchCache.mustReturn = false;
  14608. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14609. this._batchCache.visibleInstances[subMeshId] = null;
  14610. if (this._visibleInstances) {
  14611. var currentRenderId = scene.getRenderId();
  14612. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14613. var selfRenderId = this._renderId;
  14614. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14615. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14616. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14617. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14618. }
  14619. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14620. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14621. this._batchCache.mustReturn = true;
  14622. return this._batchCache;
  14623. }
  14624. if (currentRenderId !== selfRenderId) {
  14625. this._batchCache.renderSelf[subMeshId] = false;
  14626. }
  14627. }
  14628. this._renderIdForInstances[subMeshId] = currentRenderId;
  14629. }
  14630. return this._batchCache;
  14631. };
  14632. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14633. var visibleInstances = batch.visibleInstances[subMesh._id];
  14634. var matricesCount = visibleInstances.length + 1;
  14635. var bufferSize = matricesCount * 16 * 4;
  14636. while (this._instancesBufferSize < bufferSize) {
  14637. this._instancesBufferSize *= 2;
  14638. }
  14639. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14640. if (this._worldMatricesInstancesBuffer) {
  14641. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14642. }
  14643. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14644. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14645. }
  14646. var offset = 0;
  14647. var instancesCount = 0;
  14648. var world = this.getWorldMatrix();
  14649. if (batch.renderSelf[subMesh._id]) {
  14650. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14651. offset += 16;
  14652. instancesCount++;
  14653. }
  14654. if (visibleInstances) {
  14655. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14656. var instance = visibleInstances[instanceIndex];
  14657. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14658. offset += 16;
  14659. instancesCount++;
  14660. }
  14661. }
  14662. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14663. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14664. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14665. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14666. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14667. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14668. this._draw(subMesh, fillMode, instancesCount);
  14669. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14670. };
  14671. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14672. var scene = this.getScene();
  14673. var engine = scene.getEngine();
  14674. if (hardwareInstancedRendering) {
  14675. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14676. }
  14677. else {
  14678. if (batch.renderSelf[subMesh._id]) {
  14679. // Draw
  14680. if (onBeforeDraw) {
  14681. onBeforeDraw(false, this.getWorldMatrix());
  14682. }
  14683. this._draw(subMesh, fillMode);
  14684. }
  14685. if (batch.visibleInstances[subMesh._id]) {
  14686. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14687. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14688. // World
  14689. var world = instance.getWorldMatrix();
  14690. if (onBeforeDraw) {
  14691. onBeforeDraw(true, world);
  14692. }
  14693. // Draw
  14694. this._draw(subMesh, fillMode);
  14695. }
  14696. }
  14697. }
  14698. };
  14699. Mesh.prototype.render = function (subMesh) {
  14700. var scene = this.getScene();
  14701. // Managing instances
  14702. var batch = this._getInstancesRenderList(subMesh._id);
  14703. if (batch.mustReturn) {
  14704. return;
  14705. }
  14706. // Checking geometry state
  14707. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14708. return;
  14709. }
  14710. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14711. this._onBeforeRenderCallbacks[callbackIndex](this);
  14712. }
  14713. var engine = scene.getEngine();
  14714. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14715. // Material
  14716. var effectiveMaterial = subMesh.getMaterial();
  14717. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14718. return;
  14719. }
  14720. // Outline - step 1
  14721. var savedDepthWrite = engine.getDepthWrite();
  14722. if (this.renderOutline) {
  14723. engine.setDepthWrite(false);
  14724. scene.getOutlineRenderer().render(subMesh, batch);
  14725. engine.setDepthWrite(savedDepthWrite);
  14726. }
  14727. effectiveMaterial._preBind();
  14728. var effect = effectiveMaterial.getEffect();
  14729. // Bind
  14730. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14731. this._bind(subMesh, effect, fillMode);
  14732. var world = this.getWorldMatrix();
  14733. effectiveMaterial.bind(world, this);
  14734. // Draw
  14735. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14736. if (isInstance) {
  14737. effectiveMaterial.bindOnlyWorldMatrix(world);
  14738. }
  14739. });
  14740. // Unbind
  14741. effectiveMaterial.unbind();
  14742. // Outline - step 2
  14743. if (this.renderOutline && savedDepthWrite) {
  14744. engine.setDepthWrite(true);
  14745. engine.setColorWrite(false);
  14746. scene.getOutlineRenderer().render(subMesh, batch);
  14747. engine.setColorWrite(true);
  14748. }
  14749. // Overlay
  14750. if (this.renderOverlay) {
  14751. var currentMode = engine.getAlphaMode();
  14752. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14753. scene.getOutlineRenderer().render(subMesh, batch, true);
  14754. engine.setAlphaMode(currentMode);
  14755. }
  14756. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14757. this._onAfterRenderCallbacks[callbackIndex](this);
  14758. }
  14759. };
  14760. Mesh.prototype.getEmittedParticleSystems = function () {
  14761. var results = new Array();
  14762. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14763. var particleSystem = this.getScene().particleSystems[index];
  14764. if (particleSystem.emitter === this) {
  14765. results.push(particleSystem);
  14766. }
  14767. }
  14768. return results;
  14769. };
  14770. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14771. var results = new Array();
  14772. var descendants = this.getDescendants();
  14773. descendants.push(this);
  14774. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14775. var particleSystem = this.getScene().particleSystems[index];
  14776. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14777. results.push(particleSystem);
  14778. }
  14779. }
  14780. return results;
  14781. };
  14782. Mesh.prototype.getChildren = function () {
  14783. var results = [];
  14784. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14785. var mesh = this.getScene().meshes[index];
  14786. if (mesh.parent === this) {
  14787. results.push(mesh);
  14788. }
  14789. }
  14790. return results;
  14791. };
  14792. Mesh.prototype._checkDelayState = function () {
  14793. var _this = this;
  14794. var that = this;
  14795. var scene = this.getScene();
  14796. if (this._geometry) {
  14797. this._geometry.load(scene);
  14798. }
  14799. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14800. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14801. scene._addPendingData(that);
  14802. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14803. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14804. if (data instanceof ArrayBuffer) {
  14805. _this._delayLoadingFunction(data, _this);
  14806. }
  14807. else {
  14808. _this._delayLoadingFunction(JSON.parse(data), _this);
  14809. }
  14810. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14811. scene._removePendingData(_this);
  14812. }, function () { }, scene.database, getBinaryData);
  14813. }
  14814. };
  14815. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14816. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14817. return false;
  14818. }
  14819. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14820. return false;
  14821. }
  14822. this._checkDelayState();
  14823. return true;
  14824. };
  14825. Mesh.prototype.setMaterialByID = function (id) {
  14826. var materials = this.getScene().materials;
  14827. for (var index = 0; index < materials.length; index++) {
  14828. if (materials[index].id === id) {
  14829. this.material = materials[index];
  14830. return;
  14831. }
  14832. }
  14833. // Multi
  14834. var multiMaterials = this.getScene().multiMaterials;
  14835. for (index = 0; index < multiMaterials.length; index++) {
  14836. if (multiMaterials[index].id === id) {
  14837. this.material = multiMaterials[index];
  14838. return;
  14839. }
  14840. }
  14841. };
  14842. Mesh.prototype.getAnimatables = function () {
  14843. var results = [];
  14844. if (this.material) {
  14845. results.push(this.material);
  14846. }
  14847. if (this.skeleton) {
  14848. results.push(this.skeleton);
  14849. }
  14850. return results;
  14851. };
  14852. // Geometry
  14853. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14854. // Position
  14855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14856. return;
  14857. }
  14858. this._resetPointsArrayCache();
  14859. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14860. var temp = [];
  14861. for (var index = 0; index < data.length; index += 3) {
  14862. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14863. }
  14864. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14865. // Normals
  14866. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14867. return;
  14868. }
  14869. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14870. temp = [];
  14871. for (index = 0; index < data.length; index += 3) {
  14872. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14873. }
  14874. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14875. };
  14876. // Cache
  14877. Mesh.prototype._resetPointsArrayCache = function () {
  14878. this._positions = null;
  14879. };
  14880. Mesh.prototype._generatePointsArray = function () {
  14881. if (this._positions)
  14882. return true;
  14883. this._positions = [];
  14884. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14885. if (!data) {
  14886. return false;
  14887. }
  14888. for (var index = 0; index < data.length; index += 3) {
  14889. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14890. }
  14891. return true;
  14892. };
  14893. // Clone
  14894. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14895. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14896. };
  14897. // Dispose
  14898. Mesh.prototype.dispose = function (doNotRecurse) {
  14899. if (this._geometry) {
  14900. this._geometry.releaseForMesh(this, true);
  14901. }
  14902. // Instances
  14903. if (this._worldMatricesInstancesBuffer) {
  14904. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14905. this._worldMatricesInstancesBuffer = null;
  14906. }
  14907. while (this.instances.length) {
  14908. this.instances[0].dispose();
  14909. }
  14910. _super.prototype.dispose.call(this, doNotRecurse);
  14911. };
  14912. // Geometric tools
  14913. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14914. var _this = this;
  14915. var scene = this.getScene();
  14916. var onload = function (img) {
  14917. // Getting height map data
  14918. var canvas = document.createElement("canvas");
  14919. var context = canvas.getContext("2d");
  14920. var heightMapWidth = img.width;
  14921. var heightMapHeight = img.height;
  14922. canvas.width = heightMapWidth;
  14923. canvas.height = heightMapHeight;
  14924. context.drawImage(img, 0, 0);
  14925. // Create VertexData from map data
  14926. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14927. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14928. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14929. //execute success callback, if set
  14930. if (onSuccess) {
  14931. onSuccess(_this);
  14932. }
  14933. };
  14934. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14935. };
  14936. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14937. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14938. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14939. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14940. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14941. return;
  14942. }
  14943. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14944. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14945. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14946. var position = BABYLON.Vector3.Zero();
  14947. var normal = BABYLON.Vector3.Zero();
  14948. var uv = BABYLON.Vector2.Zero();
  14949. for (var index = 0; index < positions.length; index += 3) {
  14950. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14951. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14952. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14953. // Compute height
  14954. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14955. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14956. var pos = (u + v * heightMapWidth) * 4;
  14957. var r = buffer[pos] / 255.0;
  14958. var g = buffer[pos + 1] / 255.0;
  14959. var b = buffer[pos + 2] / 255.0;
  14960. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14961. normal.normalize();
  14962. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14963. position = position.add(normal);
  14964. position.toArray(positions, index);
  14965. }
  14966. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14967. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14968. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14969. };
  14970. Mesh.prototype.convertToFlatShadedMesh = function () {
  14971. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14972. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14973. var kinds = this.getVerticesDataKinds();
  14974. var vbs = [];
  14975. var data = [];
  14976. var newdata = [];
  14977. var updatableNormals = false;
  14978. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14979. var kind = kinds[kindIndex];
  14980. var vertexBuffer = this.getVertexBuffer(kind);
  14981. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14982. updatableNormals = vertexBuffer.isUpdatable();
  14983. kinds.splice(kindIndex, 1);
  14984. kindIndex--;
  14985. continue;
  14986. }
  14987. vbs[kind] = vertexBuffer;
  14988. data[kind] = vbs[kind].getData();
  14989. newdata[kind] = [];
  14990. }
  14991. // Save previous submeshes
  14992. var previousSubmeshes = this.subMeshes.slice(0);
  14993. var indices = this.getIndices();
  14994. var totalIndices = this.getTotalIndices();
  14995. // Generating unique vertices per face
  14996. for (var index = 0; index < totalIndices; index++) {
  14997. var vertexIndex = indices[index];
  14998. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14999. kind = kinds[kindIndex];
  15000. var stride = vbs[kind].getStrideSize();
  15001. for (var offset = 0; offset < stride; offset++) {
  15002. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15003. }
  15004. }
  15005. }
  15006. // Updating faces & normal
  15007. var normals = [];
  15008. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15009. for (index = 0; index < totalIndices; index += 3) {
  15010. indices[index] = index;
  15011. indices[index + 1] = index + 1;
  15012. indices[index + 2] = index + 2;
  15013. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15014. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15015. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15016. var p1p2 = p1.subtract(p2);
  15017. var p3p2 = p3.subtract(p2);
  15018. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15019. // Store same normals for every vertex
  15020. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15021. normals.push(normal.x);
  15022. normals.push(normal.y);
  15023. normals.push(normal.z);
  15024. }
  15025. }
  15026. this.setIndices(indices);
  15027. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15028. // Updating vertex buffers
  15029. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15030. kind = kinds[kindIndex];
  15031. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15032. }
  15033. // Updating submeshes
  15034. this.releaseSubMeshes();
  15035. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15036. var previousOne = previousSubmeshes[submeshIndex];
  15037. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15038. }
  15039. this.synchronizeInstances();
  15040. };
  15041. // Instances
  15042. Mesh.prototype.createInstance = function (name) {
  15043. return new BABYLON.InstancedMesh(name, this);
  15044. };
  15045. Mesh.prototype.synchronizeInstances = function () {
  15046. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15047. var instance = this.instances[instanceIndex];
  15048. instance._syncSubMeshes();
  15049. }
  15050. };
  15051. /**
  15052. * Simplify the mesh according to the given array of settings.
  15053. * Function will return immediately and will simplify async.
  15054. * @param settings a collection of simplification settings.
  15055. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15056. * @param type the type of simplification to run.
  15057. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15058. */
  15059. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15060. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15061. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15062. this.getScene().simplificationQueue.addTask({
  15063. settings: settings,
  15064. parallelProcessing: parallelProcessing,
  15065. mesh: this,
  15066. simplificationType: simplificationType,
  15067. successCallback: successCallback
  15068. });
  15069. };
  15070. /**
  15071. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15072. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15073. * This should be used together with the simplification to avoid disappearing triangles.
  15074. * @param successCallback an optional success callback to be called after the optimization finished.
  15075. */
  15076. Mesh.prototype.optimizeIndices = function (successCallback) {
  15077. var _this = this;
  15078. var indices = this.getIndices();
  15079. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15080. var vectorPositions = [];
  15081. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15082. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15083. }
  15084. var dupes = [];
  15085. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15086. var realPos = vectorPositions.length - 1 - iteration;
  15087. var testedPosition = vectorPositions[realPos];
  15088. for (var j = 0; j < realPos; ++j) {
  15089. var againstPosition = vectorPositions[j];
  15090. if (testedPosition.equals(againstPosition)) {
  15091. dupes[realPos] = j;
  15092. break;
  15093. }
  15094. }
  15095. }, function () {
  15096. for (var i = 0; i < indices.length; ++i) {
  15097. indices[i] = dupes[indices[i]] || indices[i];
  15098. }
  15099. //indices are now reordered
  15100. var originalSubMeshes = _this.subMeshes.slice(0);
  15101. _this.setIndices(indices);
  15102. _this.subMeshes = originalSubMeshes;
  15103. if (successCallback) {
  15104. successCallback(_this);
  15105. }
  15106. });
  15107. };
  15108. // Statics
  15109. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15110. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15111. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15112. if (ribbonInstance) {
  15113. // positionFunction : ribbon case
  15114. // only pathArray and sideOrientation parameters are taken into account for positions update
  15115. var positionFunction = function (positions) {
  15116. var minlg = pathArray[0].length;
  15117. var i = 0;
  15118. var ns = (ribbonInstance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15119. for (var si = 1; si <= ns; si++) {
  15120. for (var p = 0; p < pathArray.length; p++) {
  15121. var path = pathArray[p];
  15122. var l = path.length;
  15123. minlg = (minlg < l) ? minlg : l;
  15124. var j = 0;
  15125. while (j < minlg) {
  15126. positions[i] = path[j].x;
  15127. positions[i + 1] = path[j].y;
  15128. positions[i + 2] = path[j].z;
  15129. j++;
  15130. i += 3;
  15131. }
  15132. }
  15133. }
  15134. };
  15135. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15136. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15137. return ribbonInstance;
  15138. }
  15139. else {
  15140. var ribbon = new Mesh(name, scene);
  15141. ribbon.sideOrientation = sideOrientation;
  15142. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15143. vertexData.applyToMesh(ribbon, updatable);
  15144. return ribbon;
  15145. }
  15146. };
  15147. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15148. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15149. var disc = new Mesh(name, scene);
  15150. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15151. vertexData.applyToMesh(disc, updatable);
  15152. return disc;
  15153. };
  15154. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15155. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15156. var box = new Mesh(name, scene);
  15157. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15158. vertexData.applyToMesh(box, updatable);
  15159. return box;
  15160. };
  15161. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15162. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15163. var sphere = new Mesh(name, scene);
  15164. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15165. vertexData.applyToMesh(sphere, updatable);
  15166. return sphere;
  15167. };
  15168. // Cylinder and cone (Code inspired by SharpDX.org)
  15169. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15170. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15171. // subdivisions is a new parameter, we need to support old signature
  15172. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15173. if (scene !== undefined) {
  15174. updatable = scene;
  15175. }
  15176. scene = subdivisions;
  15177. subdivisions = 1;
  15178. }
  15179. var cylinder = new Mesh(name, scene);
  15180. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15181. vertexData.applyToMesh(cylinder, updatable);
  15182. return cylinder;
  15183. };
  15184. // Torus (Code from SharpDX.org)
  15185. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15186. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15187. var torus = new Mesh(name, scene);
  15188. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15189. vertexData.applyToMesh(torus, updatable);
  15190. return torus;
  15191. };
  15192. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15193. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15194. var torusKnot = new Mesh(name, scene);
  15195. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15196. vertexData.applyToMesh(torusKnot, updatable);
  15197. return torusKnot;
  15198. };
  15199. // Lines
  15200. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15201. if (linesInstance === void 0) { linesInstance = null; }
  15202. if (linesInstance) {
  15203. var positionFunction = function (positions) {
  15204. var i = 0;
  15205. for (var p = 0; p < points.length; p++) {
  15206. positions[i] = points[p].x;
  15207. positions[i + 1] = points[p].y;
  15208. positions[i + 2] = points[p].z;
  15209. i += 3;
  15210. }
  15211. };
  15212. linesInstance.updateMeshPositions(positionFunction, false);
  15213. return linesInstance;
  15214. }
  15215. // lines creation
  15216. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15217. var vertexData = BABYLON.VertexData.CreateLines(points);
  15218. vertexData.applyToMesh(lines, updatable);
  15219. return lines;
  15220. };
  15221. // Dashed Lines
  15222. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15223. if (linesInstance === void 0) { linesInstance = null; }
  15224. if (linesInstance) {
  15225. var positionFunction = function (positions) {
  15226. var curvect = BABYLON.Vector3.Zero();
  15227. var nbSeg = positions.length / 6;
  15228. var lg = 0;
  15229. var nb = 0;
  15230. var shft = 0;
  15231. var dashshft = 0;
  15232. var curshft = 0;
  15233. var p = 0;
  15234. var i = 0;
  15235. var j = 0;
  15236. for (i = 0; i < points.length - 1; i++) {
  15237. points[i + 1].subtractToRef(points[i], curvect);
  15238. lg += curvect.length();
  15239. }
  15240. shft = lg / nbSeg;
  15241. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15242. for (i = 0; i < points.length - 1; i++) {
  15243. points[i + 1].subtractToRef(points[i], curvect);
  15244. nb = Math.floor(curvect.length() / shft);
  15245. curvect.normalize();
  15246. j = 0;
  15247. while (j < nb && p < positions.length) {
  15248. curshft = shft * j;
  15249. positions[p] = points[i].x + curshft * curvect.x;
  15250. positions[p + 1] = points[i].y + curshft * curvect.y;
  15251. positions[p + 2] = points[i].z + curshft * curvect.z;
  15252. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15253. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15254. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15255. p += 6;
  15256. j++;
  15257. }
  15258. }
  15259. while (p < positions.length) {
  15260. positions[p] = points[i].x;
  15261. positions[p + 1] = points[i].y;
  15262. positions[p + 2] = points[i].z;
  15263. p += 3;
  15264. }
  15265. };
  15266. linesInstance.updateMeshPositions(positionFunction, false);
  15267. return linesInstance;
  15268. }
  15269. // dashed lines creation
  15270. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15271. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15272. vertexData.applyToMesh(dashedLines, updatable);
  15273. dashedLines.dashSize = dashSize;
  15274. dashedLines.gapSize = gapSize;
  15275. return dashedLines;
  15276. };
  15277. // Extrusion
  15278. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15279. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15280. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15281. scale = scale || 1;
  15282. rotation = rotation || 0;
  15283. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15284. return extruded;
  15285. };
  15286. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15287. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15288. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15289. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15290. return extrudedCustom;
  15291. };
  15292. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15293. // extrusion geometry
  15294. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15295. var tangents = path3D.getTangents();
  15296. var normals = path3D.getNormals();
  15297. var binormals = path3D.getBinormals();
  15298. var distances = path3D.getDistances();
  15299. var angle = 0;
  15300. var returnScale = function (i, distance) { return scale; };
  15301. var returnRotation = function (i, distance) { return rotation; };
  15302. var rotate = custom ? rotateFunction : returnRotation;
  15303. var scl = custom ? scaleFunction : returnScale;
  15304. var index = 0;
  15305. for (var i = 0; i < curve.length; i++) {
  15306. var shapePath = new Array();
  15307. var angleStep = rotate(i, distances[i]);
  15308. var scaleRatio = scl(i, distances[i]);
  15309. for (var p = 0; p < shape.length; p++) {
  15310. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15311. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15312. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15313. shapePath.push(rotated);
  15314. }
  15315. shapePaths[index] = shapePath;
  15316. angle += angleStep;
  15317. index++;
  15318. }
  15319. // cap
  15320. var capPath = function (shapePath) {
  15321. var pointCap = Array();
  15322. var barycenter = BABYLON.Vector3.Zero();
  15323. var i;
  15324. for (i = 0; i < shapePath.length; i++) {
  15325. barycenter.addInPlace(shapePath[i]);
  15326. }
  15327. barycenter.scaleInPlace(1 / shapePath.length);
  15328. for (i = 0; i < shapePath.length; i++) {
  15329. pointCap.push(barycenter);
  15330. }
  15331. return pointCap;
  15332. };
  15333. switch (cap) {
  15334. case BABYLON.Mesh.NO_CAP:
  15335. break;
  15336. case BABYLON.Mesh.CAP_START:
  15337. shapePaths.unshift(capPath(shapePaths[0]));
  15338. break;
  15339. case BABYLON.Mesh.CAP_END:
  15340. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15341. break;
  15342. case BABYLON.Mesh.CAP_ALL:
  15343. shapePaths.unshift(capPath(shapePaths[0]));
  15344. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15345. break;
  15346. default:
  15347. break;
  15348. }
  15349. return shapePaths;
  15350. };
  15351. if (instance) {
  15352. var path3D = (instance.path3D).update(curve);
  15353. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15354. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15355. return instance;
  15356. }
  15357. // extruded shape creation
  15358. var path3D = new BABYLON.Path3D(curve);
  15359. var newShapePaths = new Array();
  15360. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15361. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15362. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15363. extrudedGeneric.pathArray = pathArray;
  15364. extrudedGeneric.path3D = path3D;
  15365. extrudedGeneric.cap = cap;
  15366. return extrudedGeneric;
  15367. };
  15368. // Lathe
  15369. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15370. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15371. radius = radius || 1;
  15372. tessellation = tessellation || radius * 60;
  15373. var pi2 = Math.PI * 2;
  15374. var Y = BABYLON.Axis.Y;
  15375. var shapeLathe = new Array();
  15376. // first rotatable point
  15377. var i = 0;
  15378. while (shape[i].x === 0) {
  15379. i++;
  15380. }
  15381. var pt = shape[i];
  15382. for (i = 0; i < shape.length; i++) {
  15383. shapeLathe.push(shape[i].subtract(pt));
  15384. }
  15385. // circle path
  15386. var step = pi2 / tessellation;
  15387. var rotated;
  15388. var path = new Array();
  15389. ;
  15390. for (i = 0; i < tessellation; i++) {
  15391. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15392. path.push(rotated);
  15393. }
  15394. path.push(path[0]);
  15395. // extrusion
  15396. var scaleFunction = function () { return 1; };
  15397. var rotateFunction = function () { return 0; };
  15398. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15399. return lathe;
  15400. };
  15401. // Plane & ground
  15402. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15403. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15404. var plane = new Mesh(name, scene);
  15405. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15406. vertexData.applyToMesh(plane, updatable);
  15407. return plane;
  15408. };
  15409. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15410. var ground = new BABYLON.GroundMesh(name, scene);
  15411. ground._setReady(false);
  15412. ground._subdivisions = subdivisions;
  15413. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15414. vertexData.applyToMesh(ground, updatable);
  15415. ground._setReady(true);
  15416. return ground;
  15417. };
  15418. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15419. var tiledGround = new Mesh(name, scene);
  15420. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15421. vertexData.applyToMesh(tiledGround, updatable);
  15422. return tiledGround;
  15423. };
  15424. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15425. var ground = new BABYLON.GroundMesh(name, scene);
  15426. ground._subdivisions = subdivisions;
  15427. ground._setReady(false);
  15428. var onload = function (img) {
  15429. // Getting height map data
  15430. var canvas = document.createElement("canvas");
  15431. var context = canvas.getContext("2d");
  15432. var heightMapWidth = img.width;
  15433. var heightMapHeight = img.height;
  15434. canvas.width = heightMapWidth;
  15435. canvas.height = heightMapHeight;
  15436. context.drawImage(img, 0, 0);
  15437. // Create VertexData from map data
  15438. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15439. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15440. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15441. vertexData.applyToMesh(ground, updatable);
  15442. ground._setReady(true);
  15443. //execute ready callback, if set
  15444. if (onReady) {
  15445. onReady(ground);
  15446. }
  15447. };
  15448. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15449. return ground;
  15450. };
  15451. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15452. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15453. if (tubeInstance === void 0) { tubeInstance = null; }
  15454. // tube geometry
  15455. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15456. var tangents = path3D.getTangents();
  15457. var normals = path3D.getNormals();
  15458. var distances = path3D.getDistances();
  15459. var pi2 = Math.PI * 2;
  15460. var step = pi2 / tessellation;
  15461. var returnRadius = function (i, distance) { return radius; };
  15462. var radiusFunctionFinal = radiusFunction || returnRadius;
  15463. var circlePath;
  15464. var rad;
  15465. var normal;
  15466. var rotated;
  15467. var rotationMatrix;
  15468. var index = 0;
  15469. for (var i = 0; i < path.length; i++) {
  15470. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15471. circlePath = Array(); // current circle array
  15472. normal = normals[i]; // current normal
  15473. for (var t = 0; t < tessellation; t++) {
  15474. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15475. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15476. circlePath.push(rotated);
  15477. }
  15478. circlePath.push(circlePath[0]);
  15479. circlePaths[index] = circlePath;
  15480. index++;
  15481. }
  15482. // cap
  15483. var capPath = function (nbPoints, pathIndex) {
  15484. var pointCap = Array();
  15485. for (var i = 0; i < nbPoints; i++) {
  15486. pointCap.push(path[pathIndex]);
  15487. }
  15488. return pointCap;
  15489. };
  15490. switch (cap) {
  15491. case BABYLON.Mesh.NO_CAP:
  15492. break;
  15493. case BABYLON.Mesh.CAP_START:
  15494. circlePaths.unshift(capPath(tessellation + 1, 0));
  15495. break;
  15496. case BABYLON.Mesh.CAP_END:
  15497. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15498. break;
  15499. case BABYLON.Mesh.CAP_ALL:
  15500. circlePaths.unshift(capPath(tessellation + 1, 0));
  15501. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15502. break;
  15503. default:
  15504. break;
  15505. }
  15506. return circlePaths;
  15507. };
  15508. if (tubeInstance) {
  15509. var path3D = (tubeInstance.path3D).update(path);
  15510. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15511. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15512. return tubeInstance;
  15513. }
  15514. // tube creation
  15515. var path3D = new BABYLON.Path3D(path);
  15516. var newPathArray = new Array();
  15517. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15518. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15519. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15520. tube.pathArray = pathArray;
  15521. tube.path3D = path3D;
  15522. tube.tessellation = tessellation;
  15523. tube.cap = cap;
  15524. return tube;
  15525. };
  15526. // Decals
  15527. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15528. if (angle === void 0) { angle = 0; }
  15529. var indices = sourceMesh.getIndices();
  15530. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15531. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15532. // Getting correct rotation
  15533. if (!normal) {
  15534. var target = new BABYLON.Vector3(0, 0, 1);
  15535. var camera = sourceMesh.getScene().activeCamera;
  15536. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15537. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15538. }
  15539. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15540. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15541. var pitch = Math.atan2(normal.y, len);
  15542. // Matrix
  15543. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15544. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15545. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15546. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15547. var vertexData = new BABYLON.VertexData();
  15548. vertexData.indices = [];
  15549. vertexData.positions = [];
  15550. vertexData.normals = [];
  15551. vertexData.uvs = [];
  15552. var currentVertexDataIndex = 0;
  15553. var extractDecalVector3 = function (indexId) {
  15554. var vertexId = indices[indexId];
  15555. var result = new BABYLON.PositionNormalVertex();
  15556. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15557. // Send vector to decal local world
  15558. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15559. // Get normal
  15560. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15561. return result;
  15562. };
  15563. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15564. var clip = function (vertices, axis) {
  15565. if (vertices.length === 0) {
  15566. return vertices;
  15567. }
  15568. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15569. var clipVertices = function (v0, v1) {
  15570. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15571. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15572. };
  15573. var result = new Array();
  15574. for (var index = 0; index < vertices.length; index += 3) {
  15575. var v1Out;
  15576. var v2Out;
  15577. var v3Out;
  15578. var total = 0;
  15579. var nV1, nV2, nV3, nV4;
  15580. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15581. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15582. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15583. v1Out = d1 > 0;
  15584. v2Out = d2 > 0;
  15585. v3Out = d3 > 0;
  15586. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15587. switch (total) {
  15588. case 0:
  15589. result.push(vertices[index]);
  15590. result.push(vertices[index + 1]);
  15591. result.push(vertices[index + 2]);
  15592. break;
  15593. case 1:
  15594. if (v1Out) {
  15595. nV1 = vertices[index + 1];
  15596. nV2 = vertices[index + 2];
  15597. nV3 = clipVertices(vertices[index], nV1);
  15598. nV4 = clipVertices(vertices[index], nV2);
  15599. }
  15600. if (v2Out) {
  15601. nV1 = vertices[index];
  15602. nV2 = vertices[index + 2];
  15603. nV3 = clipVertices(vertices[index + 1], nV1);
  15604. nV4 = clipVertices(vertices[index + 1], nV2);
  15605. result.push(nV3);
  15606. result.push(nV2.clone());
  15607. result.push(nV1.clone());
  15608. result.push(nV2.clone());
  15609. result.push(nV3.clone());
  15610. result.push(nV4);
  15611. break;
  15612. }
  15613. if (v3Out) {
  15614. nV1 = vertices[index];
  15615. nV2 = vertices[index + 1];
  15616. nV3 = clipVertices(vertices[index + 2], nV1);
  15617. nV4 = clipVertices(vertices[index + 2], nV2);
  15618. }
  15619. result.push(nV1.clone());
  15620. result.push(nV2.clone());
  15621. result.push(nV3);
  15622. result.push(nV4);
  15623. result.push(nV3.clone());
  15624. result.push(nV2.clone());
  15625. break;
  15626. case 2:
  15627. if (!v1Out) {
  15628. nV1 = vertices[index].clone();
  15629. nV2 = clipVertices(nV1, vertices[index + 1]);
  15630. nV3 = clipVertices(nV1, vertices[index + 2]);
  15631. result.push(nV1);
  15632. result.push(nV2);
  15633. result.push(nV3);
  15634. }
  15635. if (!v2Out) {
  15636. nV1 = vertices[index + 1].clone();
  15637. nV2 = clipVertices(nV1, vertices[index + 2]);
  15638. nV3 = clipVertices(nV1, vertices[index]);
  15639. result.push(nV1);
  15640. result.push(nV2);
  15641. result.push(nV3);
  15642. }
  15643. if (!v3Out) {
  15644. nV1 = vertices[index + 2].clone();
  15645. nV2 = clipVertices(nV1, vertices[index]);
  15646. nV3 = clipVertices(nV1, vertices[index + 1]);
  15647. result.push(nV1);
  15648. result.push(nV2);
  15649. result.push(nV3);
  15650. }
  15651. break;
  15652. case 3:
  15653. break;
  15654. }
  15655. }
  15656. return result;
  15657. };
  15658. for (var index = 0; index < indices.length; index += 3) {
  15659. var faceVertices = new Array();
  15660. faceVertices.push(extractDecalVector3(index));
  15661. faceVertices.push(extractDecalVector3(index + 1));
  15662. faceVertices.push(extractDecalVector3(index + 2));
  15663. // Clip
  15664. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15665. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15666. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15667. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15668. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15669. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15670. if (faceVertices.length === 0) {
  15671. continue;
  15672. }
  15673. // Add UVs and get back to world
  15674. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15675. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15676. var vertex = faceVertices[vIndex];
  15677. vertexData.indices.push(currentVertexDataIndex);
  15678. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15679. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15680. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15681. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15682. currentVertexDataIndex++;
  15683. }
  15684. }
  15685. // Return mesh
  15686. var decal = new Mesh(name, sourceMesh.getScene());
  15687. vertexData.applyToMesh(decal);
  15688. decal.position = position.clone();
  15689. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15690. return decal;
  15691. };
  15692. // Tools
  15693. Mesh.MinMax = function (meshes) {
  15694. var minVector = null;
  15695. var maxVector = null;
  15696. for (var i in meshes) {
  15697. var mesh = meshes[i];
  15698. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15699. if (!minVector) {
  15700. minVector = boundingBox.minimumWorld;
  15701. maxVector = boundingBox.maximumWorld;
  15702. continue;
  15703. }
  15704. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15705. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15706. }
  15707. return {
  15708. min: minVector,
  15709. max: maxVector
  15710. };
  15711. };
  15712. Mesh.Center = function (meshesOrMinMaxVector) {
  15713. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15714. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15715. };
  15716. /**
  15717. * Merge the array of meshes into a single mesh for performance reasons.
  15718. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15719. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15720. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15721. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15722. */
  15723. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15724. if (disposeSource === void 0) { disposeSource = true; }
  15725. if (!allow32BitsIndices) {
  15726. var totalVertices = 0;
  15727. // Counting vertices
  15728. for (var index = 0; index < meshes.length; index++) {
  15729. if (meshes[index]) {
  15730. totalVertices += meshes[index].getTotalVertices();
  15731. if (totalVertices > 65536) {
  15732. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15733. return null;
  15734. }
  15735. }
  15736. }
  15737. }
  15738. // Merge
  15739. var vertexData;
  15740. var otherVertexData;
  15741. var source;
  15742. for (index = 0; index < meshes.length; index++) {
  15743. if (meshes[index]) {
  15744. meshes[index].computeWorldMatrix(true);
  15745. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15746. otherVertexData.transform(meshes[index].getWorldMatrix());
  15747. if (vertexData) {
  15748. vertexData.merge(otherVertexData);
  15749. }
  15750. else {
  15751. vertexData = otherVertexData;
  15752. source = meshes[index];
  15753. }
  15754. }
  15755. }
  15756. if (!meshSubclass) {
  15757. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15758. }
  15759. vertexData.applyToMesh(meshSubclass);
  15760. // Setting properties
  15761. meshSubclass.material = source.material;
  15762. meshSubclass.checkCollisions = source.checkCollisions;
  15763. // Cleaning
  15764. if (disposeSource) {
  15765. for (index = 0; index < meshes.length; index++) {
  15766. if (meshes[index]) {
  15767. meshes[index].dispose();
  15768. }
  15769. }
  15770. }
  15771. return meshSubclass;
  15772. };
  15773. // Consts
  15774. Mesh._FRONTSIDE = 0;
  15775. Mesh._BACKSIDE = 1;
  15776. Mesh._DOUBLESIDE = 2;
  15777. Mesh._DEFAULTSIDE = 0;
  15778. Mesh._NO_CAP = 0;
  15779. Mesh._CAP_START = 1;
  15780. Mesh._CAP_END = 2;
  15781. Mesh._CAP_ALL = 3;
  15782. return Mesh;
  15783. })(BABYLON.AbstractMesh);
  15784. BABYLON.Mesh = Mesh;
  15785. })(BABYLON || (BABYLON = {}));
  15786. //# sourceMappingURL=babylon.mesh.js.map
  15787. var BABYLON;
  15788. (function (BABYLON) {
  15789. var SubMesh = (function () {
  15790. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15791. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15792. this.materialIndex = materialIndex;
  15793. this.verticesStart = verticesStart;
  15794. this.verticesCount = verticesCount;
  15795. this.indexStart = indexStart;
  15796. this.indexCount = indexCount;
  15797. this._renderId = 0;
  15798. this._mesh = mesh;
  15799. this._renderingMesh = renderingMesh || mesh;
  15800. mesh.subMeshes.push(this);
  15801. this._trianglePlanes = [];
  15802. this._id = mesh.subMeshes.length - 1;
  15803. if (createBoundingBox) {
  15804. this.refreshBoundingInfo();
  15805. mesh.computeWorldMatrix(true);
  15806. }
  15807. }
  15808. SubMesh.prototype.getBoundingInfo = function () {
  15809. return this._boundingInfo;
  15810. };
  15811. SubMesh.prototype.getMesh = function () {
  15812. return this._mesh;
  15813. };
  15814. SubMesh.prototype.getRenderingMesh = function () {
  15815. return this._renderingMesh;
  15816. };
  15817. SubMesh.prototype.getMaterial = function () {
  15818. var rootMaterial = this._renderingMesh.material;
  15819. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15820. var multiMaterial = rootMaterial;
  15821. return multiMaterial.getSubMaterial(this.materialIndex);
  15822. }
  15823. if (!rootMaterial) {
  15824. return this._mesh.getScene().defaultMaterial;
  15825. }
  15826. return rootMaterial;
  15827. };
  15828. // Methods
  15829. SubMesh.prototype.refreshBoundingInfo = function () {
  15830. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15831. if (!data) {
  15832. this._boundingInfo = this._mesh._boundingInfo;
  15833. return;
  15834. }
  15835. var indices = this._renderingMesh.getIndices();
  15836. var extend;
  15837. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15838. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15839. }
  15840. else {
  15841. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15842. }
  15843. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15844. };
  15845. SubMesh.prototype._checkCollision = function (collider) {
  15846. return this._boundingInfo._checkCollision(collider);
  15847. };
  15848. SubMesh.prototype.updateBoundingInfo = function (world) {
  15849. if (!this._boundingInfo) {
  15850. this.refreshBoundingInfo();
  15851. }
  15852. this._boundingInfo._update(world);
  15853. };
  15854. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15855. return this._boundingInfo.isInFrustum(frustumPlanes);
  15856. };
  15857. SubMesh.prototype.render = function () {
  15858. this._renderingMesh.render(this);
  15859. };
  15860. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15861. if (!this._linesIndexBuffer) {
  15862. var linesIndices = [];
  15863. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15864. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15865. }
  15866. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15867. this.linesIndexCount = linesIndices.length;
  15868. }
  15869. return this._linesIndexBuffer;
  15870. };
  15871. SubMesh.prototype.canIntersects = function (ray) {
  15872. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15873. };
  15874. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15875. var intersectInfo = null;
  15876. // Triangles test
  15877. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15878. var p0 = positions[indices[index]];
  15879. var p1 = positions[indices[index + 1]];
  15880. var p2 = positions[indices[index + 2]];
  15881. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15882. if (currentIntersectInfo) {
  15883. if (currentIntersectInfo.distance < 0) {
  15884. continue;
  15885. }
  15886. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15887. intersectInfo = currentIntersectInfo;
  15888. intersectInfo.faceId = index / 3;
  15889. if (fastCheck) {
  15890. break;
  15891. }
  15892. }
  15893. }
  15894. }
  15895. return intersectInfo;
  15896. };
  15897. // Clone
  15898. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15899. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15900. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15901. return result;
  15902. };
  15903. // Dispose
  15904. SubMesh.prototype.dispose = function () {
  15905. if (this._linesIndexBuffer) {
  15906. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15907. this._linesIndexBuffer = null;
  15908. }
  15909. // Remove from mesh
  15910. var index = this._mesh.subMeshes.indexOf(this);
  15911. this._mesh.subMeshes.splice(index, 1);
  15912. };
  15913. // Statics
  15914. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15915. var minVertexIndex = Number.MAX_VALUE;
  15916. var maxVertexIndex = -Number.MAX_VALUE;
  15917. renderingMesh = renderingMesh || mesh;
  15918. var indices = renderingMesh.getIndices();
  15919. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15920. var vertexIndex = indices[index];
  15921. if (vertexIndex < minVertexIndex)
  15922. minVertexIndex = vertexIndex;
  15923. if (vertexIndex > maxVertexIndex)
  15924. maxVertexIndex = vertexIndex;
  15925. }
  15926. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15927. };
  15928. return SubMesh;
  15929. })();
  15930. BABYLON.SubMesh = SubMesh;
  15931. })(BABYLON || (BABYLON = {}));
  15932. //# sourceMappingURL=babylon.subMesh.js.map
  15933. var BABYLON;
  15934. (function (BABYLON) {
  15935. var BaseTexture = (function () {
  15936. function BaseTexture(scene) {
  15937. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15938. this.hasAlpha = false;
  15939. this.getAlphaFromRGB = false;
  15940. this.level = 1;
  15941. this.isCube = false;
  15942. this.isRenderTarget = false;
  15943. this.animations = new Array();
  15944. this.coordinatesIndex = 0;
  15945. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15946. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15947. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15948. this.anisotropicFilteringLevel = 4;
  15949. this._scene = scene;
  15950. this._scene.textures.push(this);
  15951. }
  15952. BaseTexture.prototype.getScene = function () {
  15953. return this._scene;
  15954. };
  15955. BaseTexture.prototype.getTextureMatrix = function () {
  15956. return null;
  15957. };
  15958. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15959. return null;
  15960. };
  15961. BaseTexture.prototype.getInternalTexture = function () {
  15962. return this._texture;
  15963. };
  15964. BaseTexture.prototype.isReady = function () {
  15965. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15966. return true;
  15967. }
  15968. if (this._texture) {
  15969. return this._texture.isReady;
  15970. }
  15971. return false;
  15972. };
  15973. BaseTexture.prototype.getSize = function () {
  15974. if (this._texture._width) {
  15975. return { width: this._texture._width, height: this._texture._height };
  15976. }
  15977. if (this._texture._size) {
  15978. return { width: this._texture._size, height: this._texture._size };
  15979. }
  15980. return { width: 0, height: 0 };
  15981. };
  15982. BaseTexture.prototype.getBaseSize = function () {
  15983. if (!this.isReady())
  15984. return { width: 0, height: 0 };
  15985. if (this._texture._size) {
  15986. return { width: this._texture._size, height: this._texture._size };
  15987. }
  15988. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15989. };
  15990. BaseTexture.prototype.scale = function (ratio) {
  15991. };
  15992. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15993. get: function () {
  15994. return false;
  15995. },
  15996. enumerable: true,
  15997. configurable: true
  15998. });
  15999. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16000. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16001. for (var index = 0; index < texturesCache.length; index++) {
  16002. var texturesCacheEntry = texturesCache[index];
  16003. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16004. texturesCache.splice(index, 1);
  16005. return;
  16006. }
  16007. }
  16008. };
  16009. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16010. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16011. for (var index = 0; index < texturesCache.length; index++) {
  16012. var texturesCacheEntry = texturesCache[index];
  16013. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16014. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16015. texturesCacheEntry.references++;
  16016. return texturesCacheEntry;
  16017. }
  16018. }
  16019. }
  16020. return null;
  16021. };
  16022. BaseTexture.prototype.delayLoad = function () {
  16023. };
  16024. BaseTexture.prototype.releaseInternalTexture = function () {
  16025. if (!this._texture) {
  16026. return;
  16027. }
  16028. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16029. this._texture.references--;
  16030. // Final reference ?
  16031. if (this._texture.references === 0) {
  16032. var index = texturesCache.indexOf(this._texture);
  16033. texturesCache.splice(index, 1);
  16034. this._scene.getEngine()._releaseTexture(this._texture);
  16035. delete this._texture;
  16036. }
  16037. };
  16038. BaseTexture.prototype.clone = function () {
  16039. return null;
  16040. };
  16041. BaseTexture.prototype.dispose = function () {
  16042. // Remove from scene
  16043. var index = this._scene.textures.indexOf(this);
  16044. if (index >= 0) {
  16045. this._scene.textures.splice(index, 1);
  16046. }
  16047. if (this._texture === undefined) {
  16048. return;
  16049. }
  16050. this.releaseInternalTexture();
  16051. // Callback
  16052. if (this.onDispose) {
  16053. this.onDispose();
  16054. }
  16055. };
  16056. return BaseTexture;
  16057. })();
  16058. BABYLON.BaseTexture = BaseTexture;
  16059. })(BABYLON || (BABYLON = {}));
  16060. //# sourceMappingURL=babylon.baseTexture.js.map
  16061. var __extends = this.__extends || function (d, b) {
  16062. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16063. function __() { this.constructor = d; }
  16064. __.prototype = b.prototype;
  16065. d.prototype = new __();
  16066. };
  16067. var BABYLON;
  16068. (function (BABYLON) {
  16069. var Texture = (function (_super) {
  16070. __extends(Texture, _super);
  16071. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16072. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16073. if (onLoad === void 0) { onLoad = null; }
  16074. if (onError === void 0) { onError = null; }
  16075. if (buffer === void 0) { buffer = null; }
  16076. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16077. _super.call(this, scene);
  16078. this.uOffset = 0;
  16079. this.vOffset = 0;
  16080. this.uScale = 1.0;
  16081. this.vScale = 1.0;
  16082. this.uAng = 0;
  16083. this.vAng = 0;
  16084. this.wAng = 0;
  16085. this.name = url;
  16086. this.url = url;
  16087. this._noMipmap = noMipmap;
  16088. this._invertY = invertY;
  16089. this._samplingMode = samplingMode;
  16090. this._buffer = buffer;
  16091. this._deleteBuffer = deleteBuffer;
  16092. if (!url) {
  16093. return;
  16094. }
  16095. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16096. if (!this._texture) {
  16097. if (!scene.useDelayedTextureLoading) {
  16098. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16099. if (deleteBuffer) {
  16100. delete this._buffer;
  16101. }
  16102. }
  16103. else {
  16104. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16105. }
  16106. }
  16107. else {
  16108. BABYLON.Tools.SetImmediate(function () {
  16109. if (onLoad) {
  16110. onLoad();
  16111. }
  16112. });
  16113. }
  16114. }
  16115. Texture.prototype.delayLoad = function () {
  16116. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16117. return;
  16118. }
  16119. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16120. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16121. if (!this._texture) {
  16122. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16123. if (this._deleteBuffer) {
  16124. delete this._buffer;
  16125. }
  16126. }
  16127. };
  16128. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16129. if (!this._texture) {
  16130. return;
  16131. }
  16132. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16133. };
  16134. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16135. x -= this.uOffset + 0.5;
  16136. y -= this.vOffset + 0.5;
  16137. z -= 0.5;
  16138. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16139. t.x *= this.uScale;
  16140. t.y *= this.vScale;
  16141. t.x += 0.5;
  16142. t.y += 0.5;
  16143. t.z += 0.5;
  16144. };
  16145. Texture.prototype.getTextureMatrix = function () {
  16146. if (this.uOffset === this._cachedUOffset &&
  16147. this.vOffset === this._cachedVOffset &&
  16148. this.uScale === this._cachedUScale &&
  16149. this.vScale === this._cachedVScale &&
  16150. this.uAng === this._cachedUAng &&
  16151. this.vAng === this._cachedVAng &&
  16152. this.wAng === this._cachedWAng) {
  16153. return this._cachedTextureMatrix;
  16154. }
  16155. this._cachedUOffset = this.uOffset;
  16156. this._cachedVOffset = this.vOffset;
  16157. this._cachedUScale = this.uScale;
  16158. this._cachedVScale = this.vScale;
  16159. this._cachedUAng = this.uAng;
  16160. this._cachedVAng = this.vAng;
  16161. this._cachedWAng = this.wAng;
  16162. if (!this._cachedTextureMatrix) {
  16163. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16164. this._rowGenerationMatrix = new BABYLON.Matrix();
  16165. this._t0 = BABYLON.Vector3.Zero();
  16166. this._t1 = BABYLON.Vector3.Zero();
  16167. this._t2 = BABYLON.Vector3.Zero();
  16168. }
  16169. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16170. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16171. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16172. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16173. this._t1.subtractInPlace(this._t0);
  16174. this._t2.subtractInPlace(this._t0);
  16175. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16176. this._cachedTextureMatrix.m[0] = this._t1.x;
  16177. this._cachedTextureMatrix.m[1] = this._t1.y;
  16178. this._cachedTextureMatrix.m[2] = this._t1.z;
  16179. this._cachedTextureMatrix.m[4] = this._t2.x;
  16180. this._cachedTextureMatrix.m[5] = this._t2.y;
  16181. this._cachedTextureMatrix.m[6] = this._t2.z;
  16182. this._cachedTextureMatrix.m[8] = this._t0.x;
  16183. this._cachedTextureMatrix.m[9] = this._t0.y;
  16184. this._cachedTextureMatrix.m[10] = this._t0.z;
  16185. return this._cachedTextureMatrix;
  16186. };
  16187. Texture.prototype.getReflectionTextureMatrix = function () {
  16188. if (this.uOffset === this._cachedUOffset &&
  16189. this.vOffset === this._cachedVOffset &&
  16190. this.uScale === this._cachedUScale &&
  16191. this.vScale === this._cachedVScale &&
  16192. this.coordinatesMode === this._cachedCoordinatesMode) {
  16193. return this._cachedTextureMatrix;
  16194. }
  16195. if (!this._cachedTextureMatrix) {
  16196. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16197. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16198. }
  16199. this._cachedCoordinatesMode = this.coordinatesMode;
  16200. switch (this.coordinatesMode) {
  16201. case Texture.SPHERICAL_MODE:
  16202. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16203. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16204. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16205. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16206. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16207. break;
  16208. case Texture.PLANAR_MODE:
  16209. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16210. this._cachedTextureMatrix[0] = this.uScale;
  16211. this._cachedTextureMatrix[5] = this.vScale;
  16212. this._cachedTextureMatrix[12] = this.uOffset;
  16213. this._cachedTextureMatrix[13] = this.vOffset;
  16214. break;
  16215. case Texture.PROJECTION_MODE:
  16216. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16217. this._projectionModeMatrix.m[0] = 0.5;
  16218. this._projectionModeMatrix.m[5] = -0.5;
  16219. this._projectionModeMatrix.m[10] = 0.0;
  16220. this._projectionModeMatrix.m[12] = 0.5;
  16221. this._projectionModeMatrix.m[13] = 0.5;
  16222. this._projectionModeMatrix.m[14] = 1.0;
  16223. this._projectionModeMatrix.m[15] = 1.0;
  16224. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16225. break;
  16226. default:
  16227. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16228. break;
  16229. }
  16230. return this._cachedTextureMatrix;
  16231. };
  16232. Texture.prototype.clone = function () {
  16233. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16234. // Base texture
  16235. newTexture.hasAlpha = this.hasAlpha;
  16236. newTexture.level = this.level;
  16237. newTexture.wrapU = this.wrapU;
  16238. newTexture.wrapV = this.wrapV;
  16239. newTexture.coordinatesIndex = this.coordinatesIndex;
  16240. newTexture.coordinatesMode = this.coordinatesMode;
  16241. // Texture
  16242. newTexture.uOffset = this.uOffset;
  16243. newTexture.vOffset = this.vOffset;
  16244. newTexture.uScale = this.uScale;
  16245. newTexture.vScale = this.vScale;
  16246. newTexture.uAng = this.uAng;
  16247. newTexture.vAng = this.vAng;
  16248. newTexture.wAng = this.wAng;
  16249. return newTexture;
  16250. };
  16251. // Statics
  16252. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16253. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16254. if (onLoad === void 0) { onLoad = null; }
  16255. if (onError === void 0) { onError = null; }
  16256. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16257. };
  16258. // Constants
  16259. Texture.NEAREST_SAMPLINGMODE = 1;
  16260. Texture.BILINEAR_SAMPLINGMODE = 2;
  16261. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16262. Texture.EXPLICIT_MODE = 0;
  16263. Texture.SPHERICAL_MODE = 1;
  16264. Texture.PLANAR_MODE = 2;
  16265. Texture.CUBIC_MODE = 3;
  16266. Texture.PROJECTION_MODE = 4;
  16267. Texture.SKYBOX_MODE = 5;
  16268. Texture.CLAMP_ADDRESSMODE = 0;
  16269. Texture.WRAP_ADDRESSMODE = 1;
  16270. Texture.MIRROR_ADDRESSMODE = 2;
  16271. return Texture;
  16272. })(BABYLON.BaseTexture);
  16273. BABYLON.Texture = Texture;
  16274. })(BABYLON || (BABYLON = {}));
  16275. //# sourceMappingURL=babylon.texture.js.map
  16276. var __extends = this.__extends || function (d, b) {
  16277. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16278. function __() { this.constructor = d; }
  16279. __.prototype = b.prototype;
  16280. d.prototype = new __();
  16281. };
  16282. var BABYLON;
  16283. (function (BABYLON) {
  16284. var CubeTexture = (function (_super) {
  16285. __extends(CubeTexture, _super);
  16286. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16287. _super.call(this, scene);
  16288. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16289. this.name = rootUrl;
  16290. this.url = rootUrl;
  16291. this._noMipmap = noMipmap;
  16292. this.hasAlpha = false;
  16293. this._texture = this._getFromCache(rootUrl, noMipmap);
  16294. if (!extensions) {
  16295. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16296. }
  16297. this._extensions = extensions;
  16298. if (!this._texture) {
  16299. if (!scene.useDelayedTextureLoading) {
  16300. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16301. }
  16302. else {
  16303. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16304. }
  16305. }
  16306. this.isCube = true;
  16307. this._textureMatrix = BABYLON.Matrix.Identity();
  16308. }
  16309. CubeTexture.prototype.clone = function () {
  16310. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16311. // Base texture
  16312. newTexture.level = this.level;
  16313. newTexture.wrapU = this.wrapU;
  16314. newTexture.wrapV = this.wrapV;
  16315. newTexture.coordinatesIndex = this.coordinatesIndex;
  16316. newTexture.coordinatesMode = this.coordinatesMode;
  16317. return newTexture;
  16318. };
  16319. // Methods
  16320. CubeTexture.prototype.delayLoad = function () {
  16321. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16322. return;
  16323. }
  16324. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16325. this._texture = this._getFromCache(this.url, this._noMipmap);
  16326. if (!this._texture) {
  16327. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16328. }
  16329. };
  16330. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16331. return this._textureMatrix;
  16332. };
  16333. return CubeTexture;
  16334. })(BABYLON.BaseTexture);
  16335. BABYLON.CubeTexture = CubeTexture;
  16336. })(BABYLON || (BABYLON = {}));
  16337. //# sourceMappingURL=babylon.cubeTexture.js.map
  16338. var __extends = this.__extends || function (d, b) {
  16339. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16340. function __() { this.constructor = d; }
  16341. __.prototype = b.prototype;
  16342. d.prototype = new __();
  16343. };
  16344. var BABYLON;
  16345. (function (BABYLON) {
  16346. var RenderTargetTexture = (function (_super) {
  16347. __extends(RenderTargetTexture, _super);
  16348. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16349. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16350. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16351. _super.call(this, null, scene, !generateMipMaps);
  16352. this.renderList = new Array();
  16353. this.renderParticles = true;
  16354. this.renderSprites = false;
  16355. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16356. this._currentRefreshId = -1;
  16357. this._refreshRate = 1;
  16358. this.name = name;
  16359. this.isRenderTarget = true;
  16360. this._size = size;
  16361. this._generateMipMaps = generateMipMaps;
  16362. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16363. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16364. // Rendering groups
  16365. this._renderingManager = new BABYLON.RenderingManager(scene);
  16366. }
  16367. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16368. this._currentRefreshId = -1;
  16369. };
  16370. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16371. get: function () {
  16372. return this._refreshRate;
  16373. },
  16374. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16375. set: function (value) {
  16376. this._refreshRate = value;
  16377. this.resetRefreshCounter();
  16378. },
  16379. enumerable: true,
  16380. configurable: true
  16381. });
  16382. RenderTargetTexture.prototype._shouldRender = function () {
  16383. if (this._currentRefreshId === -1) {
  16384. this._currentRefreshId = 1;
  16385. return true;
  16386. }
  16387. if (this.refreshRate === this._currentRefreshId) {
  16388. this._currentRefreshId = 1;
  16389. return true;
  16390. }
  16391. this._currentRefreshId++;
  16392. return false;
  16393. };
  16394. RenderTargetTexture.prototype.isReady = function () {
  16395. if (!this.getScene().renderTargetsEnabled) {
  16396. return false;
  16397. }
  16398. return _super.prototype.isReady.call(this);
  16399. };
  16400. RenderTargetTexture.prototype.getRenderSize = function () {
  16401. return this._size;
  16402. };
  16403. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16404. get: function () {
  16405. return true;
  16406. },
  16407. enumerable: true,
  16408. configurable: true
  16409. });
  16410. RenderTargetTexture.prototype.scale = function (ratio) {
  16411. var newSize = this._size * ratio;
  16412. this.resize(newSize, this._generateMipMaps);
  16413. };
  16414. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16415. this.releaseInternalTexture();
  16416. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16417. };
  16418. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16419. var scene = this.getScene();
  16420. var engine = scene.getEngine();
  16421. if (this._waitingRenderList) {
  16422. this.renderList = [];
  16423. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16424. var id = this._waitingRenderList[index];
  16425. this.renderList.push(scene.getMeshByID(id));
  16426. }
  16427. delete this._waitingRenderList;
  16428. }
  16429. if (this.renderList && this.renderList.length === 0) {
  16430. return;
  16431. }
  16432. // Bind
  16433. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16434. engine.bindFramebuffer(this._texture);
  16435. }
  16436. this._renderingManager.reset();
  16437. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16438. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16439. var mesh = currentRenderList[meshIndex];
  16440. if (mesh) {
  16441. if (!mesh.isReady()) {
  16442. // Reset _currentRefreshId
  16443. this.resetRefreshCounter();
  16444. continue;
  16445. }
  16446. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16447. mesh._activate(scene.getRenderId());
  16448. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16449. var subMesh = mesh.subMeshes[subIndex];
  16450. scene._activeIndices += subMesh.indexCount;
  16451. this._renderingManager.dispatch(subMesh);
  16452. }
  16453. }
  16454. }
  16455. }
  16456. if (this.onBeforeRender) {
  16457. this.onBeforeRender();
  16458. }
  16459. // Clear
  16460. if (this.onClear) {
  16461. this.onClear(engine);
  16462. }
  16463. else {
  16464. engine.clear(scene.clearColor, true, true);
  16465. }
  16466. if (!this._doNotChangeAspectRatio) {
  16467. scene.updateTransformMatrix(true);
  16468. }
  16469. // Render
  16470. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16471. if (useCameraPostProcess) {
  16472. scene.postProcessManager._finalizeFrame(false, this._texture);
  16473. }
  16474. if (!this._doNotChangeAspectRatio) {
  16475. scene.updateTransformMatrix(true);
  16476. }
  16477. if (this.onAfterRender) {
  16478. this.onAfterRender();
  16479. }
  16480. // Dump ?
  16481. if (dumpForDebug) {
  16482. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16483. }
  16484. // Unbind
  16485. engine.unBindFramebuffer(this._texture);
  16486. if (this.onAfterUnbind) {
  16487. this.onAfterUnbind();
  16488. }
  16489. };
  16490. RenderTargetTexture.prototype.clone = function () {
  16491. var textureSize = this.getSize();
  16492. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16493. // Base texture
  16494. newTexture.hasAlpha = this.hasAlpha;
  16495. newTexture.level = this.level;
  16496. // RenderTarget Texture
  16497. newTexture.coordinatesMode = this.coordinatesMode;
  16498. newTexture.renderList = this.renderList.slice(0);
  16499. return newTexture;
  16500. };
  16501. return RenderTargetTexture;
  16502. })(BABYLON.Texture);
  16503. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16504. })(BABYLON || (BABYLON = {}));
  16505. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16506. var __extends = this.__extends || function (d, b) {
  16507. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16508. function __() { this.constructor = d; }
  16509. __.prototype = b.prototype;
  16510. d.prototype = new __();
  16511. };
  16512. var BABYLON;
  16513. (function (BABYLON) {
  16514. var ProceduralTexture = (function (_super) {
  16515. __extends(ProceduralTexture, _super);
  16516. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16517. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16518. _super.call(this, null, scene, !generateMipMaps);
  16519. this._currentRefreshId = -1;
  16520. this._refreshRate = 1;
  16521. this._vertexDeclaration = [2];
  16522. this._vertexStrideSize = 2 * 4;
  16523. this._uniforms = new Array();
  16524. this._samplers = new Array();
  16525. this._textures = new Array();
  16526. this._floats = new Array();
  16527. this._floatsArrays = {};
  16528. this._colors3 = new Array();
  16529. this._colors4 = new Array();
  16530. this._vectors2 = new Array();
  16531. this._vectors3 = new Array();
  16532. this._matrices = new Array();
  16533. this._fallbackTextureUsed = false;
  16534. scene._proceduralTextures.push(this);
  16535. this.name = name;
  16536. this.isRenderTarget = true;
  16537. this._size = size;
  16538. this._generateMipMaps = generateMipMaps;
  16539. this.setFragment(fragment);
  16540. this._fallbackTexture = fallbackTexture;
  16541. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16542. // VBO
  16543. var vertices = [];
  16544. vertices.push(1, 1);
  16545. vertices.push(-1, 1);
  16546. vertices.push(-1, -1);
  16547. vertices.push(1, -1);
  16548. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16549. // Indices
  16550. var indices = [];
  16551. indices.push(0);
  16552. indices.push(1);
  16553. indices.push(2);
  16554. indices.push(0);
  16555. indices.push(2);
  16556. indices.push(3);
  16557. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16558. }
  16559. ProceduralTexture.prototype.reset = function () {
  16560. if (this._effect === undefined) {
  16561. return;
  16562. }
  16563. var engine = this.getScene().getEngine();
  16564. engine._releaseEffect(this._effect);
  16565. };
  16566. ProceduralTexture.prototype.isReady = function () {
  16567. var _this = this;
  16568. var engine = this.getScene().getEngine();
  16569. var shaders;
  16570. if (!this._fragment) {
  16571. return false;
  16572. }
  16573. if (this._fallbackTextureUsed) {
  16574. return true;
  16575. }
  16576. if (this._fragment.fragmentElement !== undefined) {
  16577. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16578. }
  16579. else {
  16580. shaders = { vertex: "procedural", fragment: this._fragment };
  16581. }
  16582. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16583. _this.releaseInternalTexture();
  16584. if (_this._fallbackTexture) {
  16585. _this._texture = _this._fallbackTexture._texture;
  16586. _this._texture.references++;
  16587. }
  16588. _this._fallbackTextureUsed = true;
  16589. });
  16590. return this._effect.isReady();
  16591. };
  16592. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16593. this._currentRefreshId = -1;
  16594. };
  16595. ProceduralTexture.prototype.setFragment = function (fragment) {
  16596. this._fragment = fragment;
  16597. };
  16598. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16599. get: function () {
  16600. return this._refreshRate;
  16601. },
  16602. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16603. set: function (value) {
  16604. this._refreshRate = value;
  16605. this.resetRefreshCounter();
  16606. },
  16607. enumerable: true,
  16608. configurable: true
  16609. });
  16610. ProceduralTexture.prototype._shouldRender = function () {
  16611. if (!this.isReady() || !this._texture) {
  16612. return false;
  16613. }
  16614. if (this._fallbackTextureUsed) {
  16615. return false;
  16616. }
  16617. if (this._currentRefreshId === -1) {
  16618. this._currentRefreshId = 1;
  16619. return true;
  16620. }
  16621. if (this.refreshRate === this._currentRefreshId) {
  16622. this._currentRefreshId = 1;
  16623. return true;
  16624. }
  16625. this._currentRefreshId++;
  16626. return false;
  16627. };
  16628. ProceduralTexture.prototype.getRenderSize = function () {
  16629. return this._size;
  16630. };
  16631. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16632. if (this._fallbackTextureUsed) {
  16633. return;
  16634. }
  16635. this.releaseInternalTexture();
  16636. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16637. };
  16638. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16639. if (this._uniforms.indexOf(uniformName) === -1) {
  16640. this._uniforms.push(uniformName);
  16641. }
  16642. };
  16643. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16644. if (this._samplers.indexOf(name) === -1) {
  16645. this._samplers.push(name);
  16646. }
  16647. this._textures[name] = texture;
  16648. return this;
  16649. };
  16650. ProceduralTexture.prototype.setFloat = function (name, value) {
  16651. this._checkUniform(name);
  16652. this._floats[name] = value;
  16653. return this;
  16654. };
  16655. ProceduralTexture.prototype.setFloats = function (name, value) {
  16656. this._checkUniform(name);
  16657. this._floatsArrays[name] = value;
  16658. return this;
  16659. };
  16660. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16661. this._checkUniform(name);
  16662. this._colors3[name] = value;
  16663. return this;
  16664. };
  16665. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16666. this._checkUniform(name);
  16667. this._colors4[name] = value;
  16668. return this;
  16669. };
  16670. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16671. this._checkUniform(name);
  16672. this._vectors2[name] = value;
  16673. return this;
  16674. };
  16675. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16676. this._checkUniform(name);
  16677. this._vectors3[name] = value;
  16678. return this;
  16679. };
  16680. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16681. this._checkUniform(name);
  16682. this._matrices[name] = value;
  16683. return this;
  16684. };
  16685. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16686. var scene = this.getScene();
  16687. var engine = scene.getEngine();
  16688. engine.bindFramebuffer(this._texture);
  16689. // Clear
  16690. engine.clear(scene.clearColor, true, true);
  16691. // Render
  16692. engine.enableEffect(this._effect);
  16693. engine.setState(false);
  16694. // Texture
  16695. for (var name in this._textures) {
  16696. this._effect.setTexture(name, this._textures[name]);
  16697. }
  16698. // Float
  16699. for (name in this._floats) {
  16700. this._effect.setFloat(name, this._floats[name]);
  16701. }
  16702. // Floats
  16703. for (name in this._floatsArrays) {
  16704. this._effect.setArray(name, this._floatsArrays[name]);
  16705. }
  16706. // Color3
  16707. for (name in this._colors3) {
  16708. this._effect.setColor3(name, this._colors3[name]);
  16709. }
  16710. // Color4
  16711. for (name in this._colors4) {
  16712. var color = this._colors4[name];
  16713. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16714. }
  16715. // Vector2
  16716. for (name in this._vectors2) {
  16717. this._effect.setVector2(name, this._vectors2[name]);
  16718. }
  16719. // Vector3
  16720. for (name in this._vectors3) {
  16721. this._effect.setVector3(name, this._vectors3[name]);
  16722. }
  16723. // Matrix
  16724. for (name in this._matrices) {
  16725. this._effect.setMatrix(name, this._matrices[name]);
  16726. }
  16727. // VBOs
  16728. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16729. // Draw order
  16730. engine.draw(true, 0, 6);
  16731. // Unbind
  16732. engine.unBindFramebuffer(this._texture);
  16733. };
  16734. ProceduralTexture.prototype.clone = function () {
  16735. var textureSize = this.getSize();
  16736. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16737. // Base texture
  16738. newTexture.hasAlpha = this.hasAlpha;
  16739. newTexture.level = this.level;
  16740. // RenderTarget Texture
  16741. newTexture.coordinatesMode = this.coordinatesMode;
  16742. return newTexture;
  16743. };
  16744. ProceduralTexture.prototype.dispose = function () {
  16745. var index = this.getScene()._proceduralTextures.indexOf(this);
  16746. if (index >= 0) {
  16747. this.getScene()._proceduralTextures.splice(index, 1);
  16748. }
  16749. _super.prototype.dispose.call(this);
  16750. };
  16751. return ProceduralTexture;
  16752. })(BABYLON.Texture);
  16753. BABYLON.ProceduralTexture = ProceduralTexture;
  16754. })(BABYLON || (BABYLON = {}));
  16755. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16756. var __extends = this.__extends || function (d, b) {
  16757. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16758. function __() { this.constructor = d; }
  16759. __.prototype = b.prototype;
  16760. d.prototype = new __();
  16761. };
  16762. var BABYLON;
  16763. (function (BABYLON) {
  16764. var MirrorTexture = (function (_super) {
  16765. __extends(MirrorTexture, _super);
  16766. function MirrorTexture(name, size, scene, generateMipMaps) {
  16767. var _this = this;
  16768. _super.call(this, name, size, scene, generateMipMaps, true);
  16769. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16770. this._transformMatrix = BABYLON.Matrix.Zero();
  16771. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16772. this.onBeforeRender = function () {
  16773. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16774. _this._savedViewMatrix = scene.getViewMatrix();
  16775. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16776. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16777. scene.clipPlane = _this.mirrorPlane;
  16778. scene.getEngine().cullBackFaces = false;
  16779. };
  16780. this.onAfterRender = function () {
  16781. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16782. scene.getEngine().cullBackFaces = true;
  16783. delete scene.clipPlane;
  16784. };
  16785. }
  16786. MirrorTexture.prototype.clone = function () {
  16787. var textureSize = this.getSize();
  16788. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16789. // Base texture
  16790. newTexture.hasAlpha = this.hasAlpha;
  16791. newTexture.level = this.level;
  16792. // Mirror Texture
  16793. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16794. newTexture.renderList = this.renderList.slice(0);
  16795. return newTexture;
  16796. };
  16797. return MirrorTexture;
  16798. })(BABYLON.RenderTargetTexture);
  16799. BABYLON.MirrorTexture = MirrorTexture;
  16800. })(BABYLON || (BABYLON = {}));
  16801. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16802. var __extends = this.__extends || function (d, b) {
  16803. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16804. function __() { this.constructor = d; }
  16805. __.prototype = b.prototype;
  16806. d.prototype = new __();
  16807. };
  16808. var BABYLON;
  16809. (function (BABYLON) {
  16810. var DynamicTexture = (function (_super) {
  16811. __extends(DynamicTexture, _super);
  16812. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16813. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16814. _super.call(this, null, scene, !generateMipMaps);
  16815. this.name = name;
  16816. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16817. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16818. this._generateMipMaps = generateMipMaps;
  16819. if (options.getContext) {
  16820. this._canvas = options;
  16821. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16822. }
  16823. else {
  16824. this._canvas = document.createElement("canvas");
  16825. if (options.width) {
  16826. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16827. }
  16828. else {
  16829. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16830. }
  16831. }
  16832. var textureSize = this.getSize();
  16833. this._canvas.width = textureSize.width;
  16834. this._canvas.height = textureSize.height;
  16835. this._context = this._canvas.getContext("2d");
  16836. }
  16837. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16838. get: function () {
  16839. return true;
  16840. },
  16841. enumerable: true,
  16842. configurable: true
  16843. });
  16844. DynamicTexture.prototype.scale = function (ratio) {
  16845. var textureSize = this.getSize();
  16846. textureSize.width *= ratio;
  16847. textureSize.height *= ratio;
  16848. this._canvas.width = textureSize.width;
  16849. this._canvas.height = textureSize.height;
  16850. this.releaseInternalTexture();
  16851. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16852. };
  16853. DynamicTexture.prototype.getContext = function () {
  16854. return this._context;
  16855. };
  16856. DynamicTexture.prototype.clear = function () {
  16857. var size = this.getSize();
  16858. this._context.fillRect(0, 0, size.width, size.height);
  16859. };
  16860. DynamicTexture.prototype.update = function (invertY) {
  16861. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16862. };
  16863. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16864. if (update === void 0) { update = true; }
  16865. var size = this.getSize();
  16866. if (clearColor) {
  16867. this._context.fillStyle = clearColor;
  16868. this._context.fillRect(0, 0, size.width, size.height);
  16869. }
  16870. this._context.font = font;
  16871. if (x === null) {
  16872. var textSize = this._context.measureText(text);
  16873. x = (size.width - textSize.width) / 2;
  16874. }
  16875. this._context.fillStyle = color;
  16876. this._context.fillText(text, x, y);
  16877. if (update) {
  16878. this.update(invertY);
  16879. }
  16880. };
  16881. DynamicTexture.prototype.clone = function () {
  16882. var textureSize = this.getSize();
  16883. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16884. // Base texture
  16885. newTexture.hasAlpha = this.hasAlpha;
  16886. newTexture.level = this.level;
  16887. // Dynamic Texture
  16888. newTexture.wrapU = this.wrapU;
  16889. newTexture.wrapV = this.wrapV;
  16890. return newTexture;
  16891. };
  16892. return DynamicTexture;
  16893. })(BABYLON.Texture);
  16894. BABYLON.DynamicTexture = DynamicTexture;
  16895. })(BABYLON || (BABYLON = {}));
  16896. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16897. var __extends = this.__extends || function (d, b) {
  16898. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16899. function __() { this.constructor = d; }
  16900. __.prototype = b.prototype;
  16901. d.prototype = new __();
  16902. };
  16903. var BABYLON;
  16904. (function (BABYLON) {
  16905. var VideoTexture = (function (_super) {
  16906. __extends(VideoTexture, _super);
  16907. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16908. var _this = this;
  16909. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16910. if (invertY === void 0) { invertY = false; }
  16911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16912. _super.call(this, null, scene, !generateMipMaps, invertY);
  16913. this._autoLaunch = true;
  16914. this.name = name;
  16915. this.video = document.createElement("video");
  16916. this.video.autoplay = false;
  16917. this.video.loop = true;
  16918. this.video.addEventListener("canplaythrough", function () {
  16919. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16920. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16921. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16922. }
  16923. else {
  16924. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16925. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16926. generateMipMaps = false;
  16927. }
  16928. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16929. _this._texture.isReady = true;
  16930. });
  16931. urls.forEach(function (url) {
  16932. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16933. var source = document.createElement("source");
  16934. source.src = url;
  16935. _this.video.appendChild(source);
  16936. });
  16937. this._lastUpdate = BABYLON.Tools.Now;
  16938. }
  16939. VideoTexture.prototype.update = function () {
  16940. if (this._autoLaunch) {
  16941. this._autoLaunch = false;
  16942. this.video.play();
  16943. }
  16944. var now = BABYLON.Tools.Now;
  16945. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16946. return false;
  16947. }
  16948. this._lastUpdate = now;
  16949. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16950. return true;
  16951. };
  16952. return VideoTexture;
  16953. })(BABYLON.Texture);
  16954. BABYLON.VideoTexture = VideoTexture;
  16955. })(BABYLON || (BABYLON = {}));
  16956. //# sourceMappingURL=babylon.videoTexture.js.map
  16957. var __extends = this.__extends || function (d, b) {
  16958. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16959. function __() { this.constructor = d; }
  16960. __.prototype = b.prototype;
  16961. d.prototype = new __();
  16962. };
  16963. var BABYLON;
  16964. (function (BABYLON) {
  16965. var CustomProceduralTexture = (function (_super) {
  16966. __extends(CustomProceduralTexture, _super);
  16967. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16968. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16969. this._animate = true;
  16970. this._time = 0;
  16971. this._texturePath = texturePath;
  16972. //Try to load json
  16973. this.loadJson(texturePath);
  16974. this.refreshRate = 1;
  16975. }
  16976. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16977. var _this = this;
  16978. var that = this;
  16979. function noConfigFile() {
  16980. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16981. try {
  16982. that.setFragment(that._texturePath);
  16983. }
  16984. catch (ex) {
  16985. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16986. }
  16987. }
  16988. var configFileUrl = jsonUrl + "/config.json";
  16989. var xhr = new XMLHttpRequest();
  16990. xhr.open("GET", configFileUrl, true);
  16991. xhr.addEventListener("load", function () {
  16992. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16993. try {
  16994. _this._config = JSON.parse(xhr.response);
  16995. _this.updateShaderUniforms();
  16996. _this.updateTextures();
  16997. _this.setFragment(_this._texturePath + "/custom");
  16998. _this._animate = _this._config.animate;
  16999. _this.refreshRate = _this._config.refreshrate;
  17000. }
  17001. catch (ex) {
  17002. noConfigFile();
  17003. }
  17004. }
  17005. else {
  17006. noConfigFile();
  17007. }
  17008. }, false);
  17009. xhr.addEventListener("error", function () {
  17010. noConfigFile();
  17011. }, false);
  17012. try {
  17013. xhr.send();
  17014. }
  17015. catch (ex) {
  17016. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17017. }
  17018. };
  17019. CustomProceduralTexture.prototype.isReady = function () {
  17020. if (!_super.prototype.isReady.call(this)) {
  17021. return false;
  17022. }
  17023. for (var name in this._textures) {
  17024. var texture = this._textures[name];
  17025. if (!texture.isReady()) {
  17026. return false;
  17027. }
  17028. }
  17029. return true;
  17030. };
  17031. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17032. if (this._animate) {
  17033. this._time += this.getScene().getAnimationRatio() * 0.03;
  17034. this.updateShaderUniforms();
  17035. }
  17036. _super.prototype.render.call(this, useCameraPostProcess);
  17037. };
  17038. CustomProceduralTexture.prototype.updateTextures = function () {
  17039. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17040. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17041. }
  17042. };
  17043. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17044. if (this._config) {
  17045. for (var j = 0; j < this._config.uniforms.length; j++) {
  17046. var uniform = this._config.uniforms[j];
  17047. switch (uniform.type) {
  17048. case "float":
  17049. this.setFloat(uniform.name, uniform.value);
  17050. break;
  17051. case "color3":
  17052. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17053. break;
  17054. case "color4":
  17055. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17056. break;
  17057. case "vector2":
  17058. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17059. break;
  17060. case "vector3":
  17061. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17062. break;
  17063. }
  17064. }
  17065. }
  17066. this.setFloat("time", this._time);
  17067. };
  17068. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17069. get: function () {
  17070. return this._animate;
  17071. },
  17072. set: function (value) {
  17073. this._animate = value;
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. return CustomProceduralTexture;
  17079. })(BABYLON.ProceduralTexture);
  17080. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17081. })(BABYLON || (BABYLON = {}));
  17082. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  17083. var __extends = this.__extends || function (d, b) {
  17084. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17085. function __() { this.constructor = d; }
  17086. __.prototype = b.prototype;
  17087. d.prototype = new __();
  17088. };
  17089. var BABYLON;
  17090. (function (BABYLON) {
  17091. var WoodProceduralTexture = (function (_super) {
  17092. __extends(WoodProceduralTexture, _super);
  17093. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17094. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17095. this._ampScale = 100.0;
  17096. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17097. this.updateShaderUniforms();
  17098. this.refreshRate = 0;
  17099. }
  17100. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17101. this.setFloat("ampScale", this._ampScale);
  17102. this.setColor3("woodColor", this._woodColor);
  17103. };
  17104. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17105. get: function () {
  17106. return this._ampScale;
  17107. },
  17108. set: function (value) {
  17109. this._ampScale = value;
  17110. this.updateShaderUniforms();
  17111. },
  17112. enumerable: true,
  17113. configurable: true
  17114. });
  17115. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17116. get: function () {
  17117. return this._woodColor;
  17118. },
  17119. set: function (value) {
  17120. this._woodColor = value;
  17121. this.updateShaderUniforms();
  17122. },
  17123. enumerable: true,
  17124. configurable: true
  17125. });
  17126. return WoodProceduralTexture;
  17127. })(BABYLON.ProceduralTexture);
  17128. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17129. var FireProceduralTexture = (function (_super) {
  17130. __extends(FireProceduralTexture, _super);
  17131. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17132. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17133. this._time = 0.0;
  17134. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17135. this._autoGenerateTime = true;
  17136. this._alphaThreshold = 0.5;
  17137. this._fireColors = FireProceduralTexture.RedFireColors;
  17138. this.updateShaderUniforms();
  17139. this.refreshRate = 1;
  17140. }
  17141. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17142. this.setFloat("time", this._time);
  17143. this.setVector2("speed", this._speed);
  17144. this.setColor3("c1", this._fireColors[0]);
  17145. this.setColor3("c2", this._fireColors[1]);
  17146. this.setColor3("c3", this._fireColors[2]);
  17147. this.setColor3("c4", this._fireColors[3]);
  17148. this.setColor3("c5", this._fireColors[4]);
  17149. this.setColor3("c6", this._fireColors[5]);
  17150. this.setFloat("alphaThreshold", this._alphaThreshold);
  17151. };
  17152. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17153. if (this._autoGenerateTime) {
  17154. this._time += this.getScene().getAnimationRatio() * 0.03;
  17155. this.updateShaderUniforms();
  17156. }
  17157. _super.prototype.render.call(this, useCameraPostProcess);
  17158. };
  17159. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17160. get: function () {
  17161. return [
  17162. new BABYLON.Color3(0.5, 0.0, 1.0),
  17163. new BABYLON.Color3(0.9, 0.0, 1.0),
  17164. new BABYLON.Color3(0.2, 0.0, 1.0),
  17165. new BABYLON.Color3(1.0, 0.9, 1.0),
  17166. new BABYLON.Color3(0.1, 0.1, 1.0),
  17167. new BABYLON.Color3(0.9, 0.9, 1.0)
  17168. ];
  17169. },
  17170. enumerable: true,
  17171. configurable: true
  17172. });
  17173. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17174. get: function () {
  17175. return [
  17176. new BABYLON.Color3(0.5, 1.0, 0.0),
  17177. new BABYLON.Color3(0.5, 1.0, 0.0),
  17178. new BABYLON.Color3(0.3, 0.4, 0.0),
  17179. new BABYLON.Color3(0.5, 1.0, 0.0),
  17180. new BABYLON.Color3(0.2, 0.0, 0.0),
  17181. new BABYLON.Color3(0.5, 1.0, 0.0)
  17182. ];
  17183. },
  17184. enumerable: true,
  17185. configurable: true
  17186. });
  17187. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17188. get: function () {
  17189. return [
  17190. new BABYLON.Color3(0.5, 0.0, 0.1),
  17191. new BABYLON.Color3(0.9, 0.0, 0.0),
  17192. new BABYLON.Color3(0.2, 0.0, 0.0),
  17193. new BABYLON.Color3(1.0, 0.9, 0.0),
  17194. new BABYLON.Color3(0.1, 0.1, 0.1),
  17195. new BABYLON.Color3(0.9, 0.9, 0.9)
  17196. ];
  17197. },
  17198. enumerable: true,
  17199. configurable: true
  17200. });
  17201. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17202. get: function () {
  17203. return [
  17204. new BABYLON.Color3(0.1, 0.0, 0.5),
  17205. new BABYLON.Color3(0.0, 0.0, 0.5),
  17206. new BABYLON.Color3(0.1, 0.0, 0.2),
  17207. new BABYLON.Color3(0.0, 0.0, 1.0),
  17208. new BABYLON.Color3(0.1, 0.2, 0.3),
  17209. new BABYLON.Color3(0.0, 0.2, 0.9)
  17210. ];
  17211. },
  17212. enumerable: true,
  17213. configurable: true
  17214. });
  17215. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17216. get: function () {
  17217. return this._fireColors;
  17218. },
  17219. set: function (value) {
  17220. this._fireColors = value;
  17221. this.updateShaderUniforms();
  17222. },
  17223. enumerable: true,
  17224. configurable: true
  17225. });
  17226. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17227. get: function () {
  17228. return this._time;
  17229. },
  17230. set: function (value) {
  17231. this._time = value;
  17232. this.updateShaderUniforms();
  17233. },
  17234. enumerable: true,
  17235. configurable: true
  17236. });
  17237. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17238. get: function () {
  17239. return this._speed;
  17240. },
  17241. set: function (value) {
  17242. this._speed = value;
  17243. this.updateShaderUniforms();
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17249. get: function () {
  17250. return this._alphaThreshold;
  17251. },
  17252. set: function (value) {
  17253. this._alphaThreshold = value;
  17254. this.updateShaderUniforms();
  17255. },
  17256. enumerable: true,
  17257. configurable: true
  17258. });
  17259. return FireProceduralTexture;
  17260. })(BABYLON.ProceduralTexture);
  17261. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17262. var CloudProceduralTexture = (function (_super) {
  17263. __extends(CloudProceduralTexture, _super);
  17264. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17265. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17266. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17267. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17268. this.updateShaderUniforms();
  17269. this.refreshRate = 0;
  17270. }
  17271. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17272. this.setColor3("skyColor", this._skyColor);
  17273. this.setColor3("cloudColor", this._cloudColor);
  17274. };
  17275. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17276. get: function () {
  17277. return this._skyColor;
  17278. },
  17279. set: function (value) {
  17280. this._skyColor = value;
  17281. this.updateShaderUniforms();
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17287. get: function () {
  17288. return this._cloudColor;
  17289. },
  17290. set: function (value) {
  17291. this._cloudColor = value;
  17292. this.updateShaderUniforms();
  17293. },
  17294. enumerable: true,
  17295. configurable: true
  17296. });
  17297. return CloudProceduralTexture;
  17298. })(BABYLON.ProceduralTexture);
  17299. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17300. var GrassProceduralTexture = (function (_super) {
  17301. __extends(GrassProceduralTexture, _super);
  17302. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17303. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17304. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17305. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17306. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17307. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17308. this._grassColors = [
  17309. new BABYLON.Color3(0.29, 0.38, 0.02),
  17310. new BABYLON.Color3(0.36, 0.49, 0.09),
  17311. new BABYLON.Color3(0.51, 0.6, 0.28)
  17312. ];
  17313. this.updateShaderUniforms();
  17314. this.refreshRate = 0;
  17315. }
  17316. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17317. this.setColor3("herb1Color", this._grassColors[0]);
  17318. this.setColor3("herb2Color", this._grassColors[1]);
  17319. this.setColor3("herb3Color", this._grassColors[2]);
  17320. this.setColor3("groundColor", this._groundColor);
  17321. };
  17322. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17323. get: function () {
  17324. return this._grassColors;
  17325. },
  17326. set: function (value) {
  17327. this._grassColors = value;
  17328. this.updateShaderUniforms();
  17329. },
  17330. enumerable: true,
  17331. configurable: true
  17332. });
  17333. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17334. get: function () {
  17335. return this._groundColor;
  17336. },
  17337. set: function (value) {
  17338. this.groundColor = value;
  17339. this.updateShaderUniforms();
  17340. },
  17341. enumerable: true,
  17342. configurable: true
  17343. });
  17344. return GrassProceduralTexture;
  17345. })(BABYLON.ProceduralTexture);
  17346. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17347. var RoadProceduralTexture = (function (_super) {
  17348. __extends(RoadProceduralTexture, _super);
  17349. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17350. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17351. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17352. this.updateShaderUniforms();
  17353. this.refreshRate = 0;
  17354. }
  17355. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17356. this.setColor3("roadColor", this._roadColor);
  17357. };
  17358. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17359. get: function () {
  17360. return this._roadColor;
  17361. },
  17362. set: function (value) {
  17363. this._roadColor = value;
  17364. this.updateShaderUniforms();
  17365. },
  17366. enumerable: true,
  17367. configurable: true
  17368. });
  17369. return RoadProceduralTexture;
  17370. })(BABYLON.ProceduralTexture);
  17371. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17372. var BrickProceduralTexture = (function (_super) {
  17373. __extends(BrickProceduralTexture, _super);
  17374. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17375. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17376. this._numberOfBricksHeight = 15;
  17377. this._numberOfBricksWidth = 5;
  17378. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17379. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17380. this.updateShaderUniforms();
  17381. this.refreshRate = 0;
  17382. }
  17383. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17384. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17385. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17386. this.setColor3("brickColor", this._brickColor);
  17387. this.setColor3("jointColor", this._jointColor);
  17388. };
  17389. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17390. get: function () {
  17391. return this._numberOfBricksHeight;
  17392. },
  17393. set: function (value) {
  17394. this._numberOfBricksHeight = value;
  17395. this.updateShaderUniforms();
  17396. },
  17397. enumerable: true,
  17398. configurable: true
  17399. });
  17400. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17401. get: function () {
  17402. return this._numberOfBricksWidth;
  17403. },
  17404. set: function (value) {
  17405. this._numberOfBricksHeight = value;
  17406. this.updateShaderUniforms();
  17407. },
  17408. enumerable: true,
  17409. configurable: true
  17410. });
  17411. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17412. get: function () {
  17413. return this._jointColor;
  17414. },
  17415. set: function (value) {
  17416. this._jointColor = value;
  17417. this.updateShaderUniforms();
  17418. },
  17419. enumerable: true,
  17420. configurable: true
  17421. });
  17422. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17423. get: function () {
  17424. return this._brickColor;
  17425. },
  17426. set: function (value) {
  17427. this._brickColor = value;
  17428. this.updateShaderUniforms();
  17429. },
  17430. enumerable: true,
  17431. configurable: true
  17432. });
  17433. return BrickProceduralTexture;
  17434. })(BABYLON.ProceduralTexture);
  17435. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17436. var MarbleProceduralTexture = (function (_super) {
  17437. __extends(MarbleProceduralTexture, _super);
  17438. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17439. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17440. this._numberOfTilesHeight = 3;
  17441. this._numberOfTilesWidth = 3;
  17442. this._amplitude = 9.0;
  17443. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17444. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17445. this.updateShaderUniforms();
  17446. this.refreshRate = 0;
  17447. }
  17448. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17449. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17450. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17451. this.setFloat("amplitude", this._amplitude);
  17452. this.setColor3("marbleColor", this._marbleColor);
  17453. this.setColor3("jointColor", this._jointColor);
  17454. };
  17455. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17456. get: function () {
  17457. return this._numberOfTilesHeight;
  17458. },
  17459. set: function (value) {
  17460. this._numberOfTilesHeight = value;
  17461. this.updateShaderUniforms();
  17462. },
  17463. enumerable: true,
  17464. configurable: true
  17465. });
  17466. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17467. get: function () {
  17468. return this._numberOfTilesWidth;
  17469. },
  17470. set: function (value) {
  17471. this._numberOfTilesWidth = value;
  17472. this.updateShaderUniforms();
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17478. get: function () {
  17479. return this._jointColor;
  17480. },
  17481. set: function (value) {
  17482. this._jointColor = value;
  17483. this.updateShaderUniforms();
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17489. get: function () {
  17490. return this._marbleColor;
  17491. },
  17492. set: function (value) {
  17493. this._marbleColor = value;
  17494. this.updateShaderUniforms();
  17495. },
  17496. enumerable: true,
  17497. configurable: true
  17498. });
  17499. return MarbleProceduralTexture;
  17500. })(BABYLON.ProceduralTexture);
  17501. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17502. })(BABYLON || (BABYLON = {}));
  17503. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17504. var BABYLON;
  17505. (function (BABYLON) {
  17506. var EffectFallbacks = (function () {
  17507. function EffectFallbacks() {
  17508. this._defines = {};
  17509. this._currentRank = 32;
  17510. this._maxRank = -1;
  17511. }
  17512. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17513. if (!this._defines[rank]) {
  17514. if (rank < this._currentRank) {
  17515. this._currentRank = rank;
  17516. }
  17517. if (rank > this._maxRank) {
  17518. this._maxRank = rank;
  17519. }
  17520. this._defines[rank] = new Array();
  17521. }
  17522. this._defines[rank].push(define);
  17523. };
  17524. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17525. get: function () {
  17526. return this._currentRank <= this._maxRank;
  17527. },
  17528. enumerable: true,
  17529. configurable: true
  17530. });
  17531. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17532. var currentFallbacks = this._defines[this._currentRank];
  17533. for (var index = 0; index < currentFallbacks.length; index++) {
  17534. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17535. }
  17536. this._currentRank++;
  17537. return currentDefines;
  17538. };
  17539. return EffectFallbacks;
  17540. })();
  17541. BABYLON.EffectFallbacks = EffectFallbacks;
  17542. var Effect = (function () {
  17543. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17544. var _this = this;
  17545. this._isReady = false;
  17546. this._compilationError = "";
  17547. this._valueCache = [];
  17548. this._engine = engine;
  17549. this.name = baseName;
  17550. this.defines = defines;
  17551. this._uniformsNames = uniformsNames.concat(samplers);
  17552. this._samplers = samplers;
  17553. this._attributesNames = attributesNames;
  17554. this.onError = onError;
  17555. this.onCompiled = onCompiled;
  17556. var vertexSource;
  17557. var fragmentSource;
  17558. if (baseName.vertexElement) {
  17559. vertexSource = document.getElementById(baseName.vertexElement);
  17560. if (!vertexSource) {
  17561. vertexSource = baseName.vertexElement;
  17562. }
  17563. }
  17564. else {
  17565. vertexSource = baseName.vertex || baseName;
  17566. }
  17567. if (baseName.fragmentElement) {
  17568. fragmentSource = document.getElementById(baseName.fragmentElement);
  17569. if (!fragmentSource) {
  17570. fragmentSource = baseName.fragmentElement;
  17571. }
  17572. }
  17573. else {
  17574. fragmentSource = baseName.fragment || baseName;
  17575. }
  17576. this._loadVertexShader(vertexSource, function (vertexCode) {
  17577. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17578. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17579. });
  17580. });
  17581. }
  17582. // Properties
  17583. Effect.prototype.isReady = function () {
  17584. return this._isReady;
  17585. };
  17586. Effect.prototype.getProgram = function () {
  17587. return this._program;
  17588. };
  17589. Effect.prototype.getAttributesNames = function () {
  17590. return this._attributesNames;
  17591. };
  17592. Effect.prototype.getAttributeLocation = function (index) {
  17593. return this._attributes[index];
  17594. };
  17595. Effect.prototype.getAttributeLocationByName = function (name) {
  17596. var index = this._attributesNames.indexOf(name);
  17597. return this._attributes[index];
  17598. };
  17599. Effect.prototype.getAttributesCount = function () {
  17600. return this._attributes.length;
  17601. };
  17602. Effect.prototype.getUniformIndex = function (uniformName) {
  17603. return this._uniformsNames.indexOf(uniformName);
  17604. };
  17605. Effect.prototype.getUniform = function (uniformName) {
  17606. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17607. };
  17608. Effect.prototype.getSamplers = function () {
  17609. return this._samplers;
  17610. };
  17611. Effect.prototype.getCompilationError = function () {
  17612. return this._compilationError;
  17613. };
  17614. // Methods
  17615. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17616. // DOM element ?
  17617. if (vertex instanceof HTMLElement) {
  17618. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17619. callback(vertexCode);
  17620. return;
  17621. }
  17622. // Is in local store ?
  17623. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17624. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17625. return;
  17626. }
  17627. var vertexShaderUrl;
  17628. if (vertex[0] === ".") {
  17629. vertexShaderUrl = vertex;
  17630. }
  17631. else {
  17632. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17633. }
  17634. // Vertex shader
  17635. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17636. };
  17637. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17638. // DOM element ?
  17639. if (fragment instanceof HTMLElement) {
  17640. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17641. callback(fragmentCode);
  17642. return;
  17643. }
  17644. // Is in local store ?
  17645. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17646. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17647. return;
  17648. }
  17649. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17650. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17651. return;
  17652. }
  17653. var fragmentShaderUrl;
  17654. if (fragment[0] === ".") {
  17655. fragmentShaderUrl = fragment;
  17656. }
  17657. else {
  17658. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17659. }
  17660. // Fragment shader
  17661. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17662. };
  17663. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17664. try {
  17665. var engine = this._engine;
  17666. if (!engine.getCaps().highPrecisionShaderSupported) {
  17667. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17668. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17669. }
  17670. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17671. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17672. this._attributes = engine.getAttributes(this._program, attributesNames);
  17673. for (var index = 0; index < this._samplers.length; index++) {
  17674. var sampler = this.getUniform(this._samplers[index]);
  17675. if (sampler == null) {
  17676. this._samplers.splice(index, 1);
  17677. index--;
  17678. }
  17679. }
  17680. engine.bindSamplers(this);
  17681. this._isReady = true;
  17682. if (this.onCompiled) {
  17683. this.onCompiled(this);
  17684. }
  17685. }
  17686. catch (e) {
  17687. // Is it a problem with precision?
  17688. if (e.message.indexOf("highp") !== -1) {
  17689. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17690. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17691. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17692. return;
  17693. }
  17694. // Let's go through fallbacks then
  17695. if (fallbacks && fallbacks.isMoreFallbacks) {
  17696. defines = fallbacks.reduce(defines);
  17697. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17698. }
  17699. else {
  17700. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  17701. BABYLON.Tools.Error("Defines: " + defines);
  17702. BABYLON.Tools.Error("Error: " + e.message);
  17703. this._compilationError = e.message;
  17704. if (this.onError) {
  17705. this.onError(this, this._compilationError);
  17706. }
  17707. }
  17708. }
  17709. };
  17710. Effect.prototype._bindTexture = function (channel, texture) {
  17711. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17712. };
  17713. Effect.prototype.setTexture = function (channel, texture) {
  17714. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17715. };
  17716. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17717. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17718. };
  17719. //public _cacheMatrix(uniformName, matrix) {
  17720. // if (!this._valueCache[uniformName]) {
  17721. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17722. // }
  17723. // for (var index = 0; index < 16; index++) {
  17724. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17725. // }
  17726. //};
  17727. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17728. if (!this._valueCache[uniformName]) {
  17729. this._valueCache[uniformName] = [x, y];
  17730. return;
  17731. }
  17732. this._valueCache[uniformName][0] = x;
  17733. this._valueCache[uniformName][1] = y;
  17734. };
  17735. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17736. if (!this._valueCache[uniformName]) {
  17737. this._valueCache[uniformName] = [x, y, z];
  17738. return;
  17739. }
  17740. this._valueCache[uniformName][0] = x;
  17741. this._valueCache[uniformName][1] = y;
  17742. this._valueCache[uniformName][2] = z;
  17743. };
  17744. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17745. if (!this._valueCache[uniformName]) {
  17746. this._valueCache[uniformName] = [x, y, z, w];
  17747. return;
  17748. }
  17749. this._valueCache[uniformName][0] = x;
  17750. this._valueCache[uniformName][1] = y;
  17751. this._valueCache[uniformName][2] = z;
  17752. this._valueCache[uniformName][3] = w;
  17753. };
  17754. Effect.prototype.setArray = function (uniformName, array) {
  17755. this._engine.setArray(this.getUniform(uniformName), array);
  17756. return this;
  17757. };
  17758. Effect.prototype.setArray2 = function (uniformName, array) {
  17759. this._engine.setArray2(this.getUniform(uniformName), array);
  17760. return this;
  17761. };
  17762. Effect.prototype.setArray3 = function (uniformName, array) {
  17763. this._engine.setArray3(this.getUniform(uniformName), array);
  17764. return this;
  17765. };
  17766. Effect.prototype.setArray4 = function (uniformName, array) {
  17767. this._engine.setArray4(this.getUniform(uniformName), array);
  17768. return this;
  17769. };
  17770. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17771. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17772. return this;
  17773. };
  17774. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17775. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17776. // return;
  17777. //this._cacheMatrix(uniformName, matrix);
  17778. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17779. return this;
  17780. };
  17781. Effect.prototype.setFloat = function (uniformName, value) {
  17782. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17783. return this;
  17784. this._valueCache[uniformName] = value;
  17785. this._engine.setFloat(this.getUniform(uniformName), value);
  17786. return this;
  17787. };
  17788. Effect.prototype.setBool = function (uniformName, bool) {
  17789. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17790. return this;
  17791. this._valueCache[uniformName] = bool;
  17792. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17793. return this;
  17794. };
  17795. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17796. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17797. return this;
  17798. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17799. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17800. return this;
  17801. };
  17802. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17803. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17804. return this;
  17805. this._cacheFloat2(uniformName, x, y);
  17806. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17807. return this;
  17808. };
  17809. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17810. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17811. return this;
  17812. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17813. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17814. return this;
  17815. };
  17816. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17817. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17818. return this;
  17819. this._cacheFloat3(uniformName, x, y, z);
  17820. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17821. return this;
  17822. };
  17823. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17824. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17825. return this;
  17826. this._cacheFloat4(uniformName, x, y, z, w);
  17827. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17828. return this;
  17829. };
  17830. Effect.prototype.setColor3 = function (uniformName, color3) {
  17831. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17832. return this;
  17833. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17834. this._engine.setColor3(this.getUniform(uniformName), color3);
  17835. return this;
  17836. };
  17837. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17838. 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)
  17839. return this;
  17840. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17841. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17842. return this;
  17843. };
  17844. // Statics
  17845. Effect.ShadersStore = {};
  17846. return Effect;
  17847. })();
  17848. BABYLON.Effect = Effect;
  17849. })(BABYLON || (BABYLON = {}));
  17850. //# sourceMappingURL=babylon.effect.js.map
  17851. var BABYLON;
  17852. (function (BABYLON) {
  17853. var Material = (function () {
  17854. function Material(name, scene, doNotAdd) {
  17855. this.name = name;
  17856. this.checkReadyOnEveryCall = true;
  17857. this.checkReadyOnlyOnce = false;
  17858. this.state = "";
  17859. this.alpha = 1.0;
  17860. this.backFaceCulling = true;
  17861. this._wasPreviouslyReady = false;
  17862. this._fillMode = Material.TriangleFillMode;
  17863. this.pointSize = 1.0;
  17864. this.zOffset = 0;
  17865. this.id = name;
  17866. this._scene = scene;
  17867. if (!doNotAdd) {
  17868. scene.materials.push(this);
  17869. }
  17870. }
  17871. Object.defineProperty(Material, "TriangleFillMode", {
  17872. get: function () {
  17873. return Material._TriangleFillMode;
  17874. },
  17875. enumerable: true,
  17876. configurable: true
  17877. });
  17878. Object.defineProperty(Material, "WireFrameFillMode", {
  17879. get: function () {
  17880. return Material._WireFrameFillMode;
  17881. },
  17882. enumerable: true,
  17883. configurable: true
  17884. });
  17885. Object.defineProperty(Material, "PointFillMode", {
  17886. get: function () {
  17887. return Material._PointFillMode;
  17888. },
  17889. enumerable: true,
  17890. configurable: true
  17891. });
  17892. Object.defineProperty(Material.prototype, "wireframe", {
  17893. get: function () {
  17894. return this._fillMode === Material.WireFrameFillMode;
  17895. },
  17896. set: function (value) {
  17897. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(Material.prototype, "pointsCloud", {
  17903. get: function () {
  17904. return this._fillMode === Material.PointFillMode;
  17905. },
  17906. set: function (value) {
  17907. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. Object.defineProperty(Material.prototype, "fillMode", {
  17913. get: function () {
  17914. return this._fillMode;
  17915. },
  17916. set: function (value) {
  17917. this._fillMode = value;
  17918. },
  17919. enumerable: true,
  17920. configurable: true
  17921. });
  17922. Material.prototype.isReady = function (mesh, useInstances) {
  17923. return true;
  17924. };
  17925. Material.prototype.getEffect = function () {
  17926. return this._effect;
  17927. };
  17928. Material.prototype.getScene = function () {
  17929. return this._scene;
  17930. };
  17931. Material.prototype.needAlphaBlending = function () {
  17932. return (this.alpha < 1.0);
  17933. };
  17934. Material.prototype.needAlphaTesting = function () {
  17935. return false;
  17936. };
  17937. Material.prototype.getAlphaTestTexture = function () {
  17938. return null;
  17939. };
  17940. Material.prototype.trackCreation = function (onCompiled, onError) {
  17941. };
  17942. Material.prototype._preBind = function () {
  17943. var engine = this._scene.getEngine();
  17944. engine.enableEffect(this._effect);
  17945. engine.setState(this.backFaceCulling, this.zOffset);
  17946. };
  17947. Material.prototype.bind = function (world, mesh) {
  17948. this._scene._cachedMaterial = this;
  17949. if (this.onBind) {
  17950. this.onBind(this, mesh);
  17951. }
  17952. };
  17953. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17954. };
  17955. Material.prototype.unbind = function () {
  17956. };
  17957. Material.prototype.dispose = function (forceDisposeEffect) {
  17958. // Remove from scene
  17959. var index = this._scene.materials.indexOf(this);
  17960. this._scene.materials.splice(index, 1);
  17961. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17962. if (forceDisposeEffect && this._effect) {
  17963. this._scene.getEngine()._releaseEffect(this._effect);
  17964. this._effect = null;
  17965. }
  17966. // Callback
  17967. if (this.onDispose) {
  17968. this.onDispose();
  17969. }
  17970. };
  17971. Material._TriangleFillMode = 0;
  17972. Material._WireFrameFillMode = 1;
  17973. Material._PointFillMode = 2;
  17974. return Material;
  17975. })();
  17976. BABYLON.Material = Material;
  17977. })(BABYLON || (BABYLON = {}));
  17978. //# sourceMappingURL=babylon.material.js.map
  17979. var __extends = this.__extends || function (d, b) {
  17980. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17981. function __() { this.constructor = d; }
  17982. __.prototype = b.prototype;
  17983. d.prototype = new __();
  17984. };
  17985. var BABYLON;
  17986. (function (BABYLON) {
  17987. var maxSimultaneousLights = 4;
  17988. var FresnelParameters = (function () {
  17989. function FresnelParameters() {
  17990. this.isEnabled = true;
  17991. this.leftColor = BABYLON.Color3.White();
  17992. this.rightColor = BABYLON.Color3.Black();
  17993. this.bias = 0;
  17994. this.power = 1;
  17995. }
  17996. return FresnelParameters;
  17997. })();
  17998. BABYLON.FresnelParameters = FresnelParameters;
  17999. var StandardMaterial = (function (_super) {
  18000. __extends(StandardMaterial, _super);
  18001. function StandardMaterial(name, scene) {
  18002. var _this = this;
  18003. _super.call(this, name, scene);
  18004. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18005. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18006. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18007. this.specularPower = 64;
  18008. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18009. this.useAlphaFromDiffuseTexture = false;
  18010. this.useSpecularOverAlpha = true;
  18011. this.fogEnabled = true;
  18012. this._cachedDefines = null;
  18013. this._renderTargets = new BABYLON.SmartArray(16);
  18014. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18015. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18016. this._scaledDiffuse = new BABYLON.Color3();
  18017. this._scaledSpecular = new BABYLON.Color3();
  18018. this.getRenderTargetTextures = function () {
  18019. _this._renderTargets.reset();
  18020. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18021. _this._renderTargets.push(_this.reflectionTexture);
  18022. }
  18023. return _this._renderTargets;
  18024. };
  18025. }
  18026. StandardMaterial.prototype.needAlphaBlending = function () {
  18027. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18028. };
  18029. StandardMaterial.prototype.needAlphaTesting = function () {
  18030. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18031. };
  18032. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18033. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18034. };
  18035. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18036. return this.diffuseTexture;
  18037. };
  18038. // Methods
  18039. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18040. if (this.checkReadyOnlyOnce) {
  18041. if (this._wasPreviouslyReady) {
  18042. return true;
  18043. }
  18044. }
  18045. var scene = this.getScene();
  18046. if (!this.checkReadyOnEveryCall) {
  18047. if (this._renderId === scene.getRenderId()) {
  18048. return true;
  18049. }
  18050. }
  18051. var engine = scene.getEngine();
  18052. var defines = [];
  18053. var fallbacks = new BABYLON.EffectFallbacks();
  18054. var needNormals = false;
  18055. var needUVs = false;
  18056. // Textures
  18057. if (scene.texturesEnabled) {
  18058. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18059. if (!this.diffuseTexture.isReady()) {
  18060. return false;
  18061. }
  18062. else {
  18063. needUVs = true;
  18064. defines.push("#define DIFFUSE");
  18065. }
  18066. }
  18067. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18068. if (!this.ambientTexture.isReady()) {
  18069. return false;
  18070. }
  18071. else {
  18072. needUVs = true;
  18073. defines.push("#define AMBIENT");
  18074. }
  18075. }
  18076. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18077. if (!this.opacityTexture.isReady()) {
  18078. return false;
  18079. }
  18080. else {
  18081. needUVs = true;
  18082. defines.push("#define OPACITY");
  18083. if (this.opacityTexture.getAlphaFromRGB) {
  18084. defines.push("#define OPACITYRGB");
  18085. }
  18086. }
  18087. }
  18088. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18089. if (!this.reflectionTexture.isReady()) {
  18090. return false;
  18091. }
  18092. else {
  18093. needNormals = true;
  18094. needUVs = true;
  18095. defines.push("#define REFLECTION");
  18096. fallbacks.addFallback(0, "REFLECTION");
  18097. }
  18098. }
  18099. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18100. if (!this.emissiveTexture.isReady()) {
  18101. return false;
  18102. }
  18103. else {
  18104. needUVs = true;
  18105. defines.push("#define EMISSIVE");
  18106. }
  18107. }
  18108. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18109. if (!this.specularTexture.isReady()) {
  18110. return false;
  18111. }
  18112. else {
  18113. needUVs = true;
  18114. defines.push("#define SPECULAR");
  18115. fallbacks.addFallback(0, "SPECULAR");
  18116. }
  18117. }
  18118. }
  18119. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18120. if (!this.bumpTexture.isReady()) {
  18121. return false;
  18122. }
  18123. else {
  18124. needUVs = true;
  18125. defines.push("#define BUMP");
  18126. fallbacks.addFallback(0, "BUMP");
  18127. }
  18128. }
  18129. // Effect
  18130. if (this.useSpecularOverAlpha) {
  18131. defines.push("#define SPECULAROVERALPHA");
  18132. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18133. }
  18134. if (scene.clipPlane) {
  18135. defines.push("#define CLIPPLANE");
  18136. }
  18137. if (engine.getAlphaTesting()) {
  18138. defines.push("#define ALPHATEST");
  18139. }
  18140. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18141. defines.push("#define ALPHAFROMDIFFUSE");
  18142. }
  18143. // Point size
  18144. if (this.pointsCloud || scene.forcePointsCloud) {
  18145. defines.push("#define POINTSIZE");
  18146. }
  18147. // Fog
  18148. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18149. defines.push("#define FOG");
  18150. fallbacks.addFallback(1, "FOG");
  18151. }
  18152. var shadowsActivated = false;
  18153. var lightIndex = 0;
  18154. if (scene.lightsEnabled) {
  18155. for (var index = 0; index < scene.lights.length; index++) {
  18156. var light = scene.lights[index];
  18157. if (!light.isEnabled()) {
  18158. continue;
  18159. }
  18160. // Excluded check
  18161. if (light._excludedMeshesIds.length > 0) {
  18162. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18163. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18164. if (excludedMesh) {
  18165. light.excludedMeshes.push(excludedMesh);
  18166. }
  18167. }
  18168. light._excludedMeshesIds = [];
  18169. }
  18170. // Included check
  18171. if (light._includedOnlyMeshesIds.length > 0) {
  18172. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18173. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18174. if (includedOnlyMesh) {
  18175. light.includedOnlyMeshes.push(includedOnlyMesh);
  18176. }
  18177. }
  18178. light._includedOnlyMeshesIds = [];
  18179. }
  18180. if (!light.canAffectMesh(mesh)) {
  18181. continue;
  18182. }
  18183. needNormals = true;
  18184. defines.push("#define LIGHT" + lightIndex);
  18185. if (lightIndex > 0) {
  18186. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18187. }
  18188. var type;
  18189. if (light instanceof BABYLON.SpotLight) {
  18190. type = "#define SPOTLIGHT" + lightIndex;
  18191. }
  18192. else if (light instanceof BABYLON.HemisphericLight) {
  18193. type = "#define HEMILIGHT" + lightIndex;
  18194. }
  18195. else {
  18196. type = "#define POINTDIRLIGHT" + lightIndex;
  18197. }
  18198. defines.push(type);
  18199. if (lightIndex > 0) {
  18200. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18201. }
  18202. // Shadows
  18203. if (scene.shadowsEnabled) {
  18204. var shadowGenerator = light.getShadowGenerator();
  18205. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18206. defines.push("#define SHADOW" + lightIndex);
  18207. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18208. if (!shadowsActivated) {
  18209. defines.push("#define SHADOWS");
  18210. shadowsActivated = true;
  18211. }
  18212. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18213. defines.push("#define SHADOWVSM" + lightIndex);
  18214. if (lightIndex > 0) {
  18215. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18216. }
  18217. }
  18218. if (shadowGenerator.usePoissonSampling) {
  18219. defines.push("#define SHADOWPCF" + lightIndex);
  18220. if (lightIndex > 0) {
  18221. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18222. }
  18223. }
  18224. }
  18225. }
  18226. lightIndex++;
  18227. if (lightIndex === maxSimultaneousLights)
  18228. break;
  18229. }
  18230. }
  18231. if (StandardMaterial.FresnelEnabled) {
  18232. // Fresnel
  18233. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18234. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18235. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18236. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18237. var fresnelRank = 1;
  18238. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18239. defines.push("#define DIFFUSEFRESNEL");
  18240. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18241. fresnelRank++;
  18242. }
  18243. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18244. defines.push("#define OPACITYFRESNEL");
  18245. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18246. fresnelRank++;
  18247. }
  18248. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18249. defines.push("#define REFLECTIONFRESNEL");
  18250. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18251. fresnelRank++;
  18252. }
  18253. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18254. defines.push("#define EMISSIVEFRESNEL");
  18255. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18256. fresnelRank++;
  18257. }
  18258. needNormals = true;
  18259. defines.push("#define FRESNEL");
  18260. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18261. }
  18262. }
  18263. // Attribs
  18264. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18265. if (mesh) {
  18266. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18267. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18268. defines.push("#define NORMAL");
  18269. }
  18270. if (needUVs) {
  18271. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18272. attribs.push(BABYLON.VertexBuffer.UVKind);
  18273. defines.push("#define UV1");
  18274. }
  18275. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18276. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18277. defines.push("#define UV2");
  18278. }
  18279. }
  18280. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18281. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18282. defines.push("#define VERTEXCOLOR");
  18283. if (mesh.hasVertexAlpha) {
  18284. defines.push("#define VERTEXALPHA");
  18285. }
  18286. }
  18287. if (mesh.useBones) {
  18288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18290. defines.push("#define BONES");
  18291. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18292. defines.push("#define BONES4");
  18293. fallbacks.addFallback(0, "BONES4");
  18294. }
  18295. // Instances
  18296. if (useInstances) {
  18297. defines.push("#define INSTANCES");
  18298. attribs.push("world0");
  18299. attribs.push("world1");
  18300. attribs.push("world2");
  18301. attribs.push("world3");
  18302. }
  18303. }
  18304. // Get correct effect
  18305. var join = defines.join("\n");
  18306. if (this._cachedDefines !== join) {
  18307. this._cachedDefines = join;
  18308. scene.resetCachedMaterial();
  18309. // Legacy browser patch
  18310. var shaderName = "default";
  18311. if (!scene.getEngine().getCaps().standardDerivatives) {
  18312. shaderName = "legacydefault";
  18313. }
  18314. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18315. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18316. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18317. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18318. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18319. "vFogInfos", "vFogColor", "pointSize",
  18320. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18321. "mBones",
  18322. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18323. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18324. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18325. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18326. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18327. ], join, fallbacks, this.onCompiled, this.onError);
  18328. }
  18329. if (!this._effect.isReady()) {
  18330. return false;
  18331. }
  18332. this._renderId = scene.getRenderId();
  18333. this._wasPreviouslyReady = true;
  18334. return true;
  18335. };
  18336. StandardMaterial.prototype.unbind = function () {
  18337. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18338. this._effect.setTexture("reflection2DSampler", null);
  18339. }
  18340. };
  18341. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18342. this._effect.setMatrix("world", world);
  18343. };
  18344. StandardMaterial.prototype.bind = function (world, mesh) {
  18345. var scene = this.getScene();
  18346. // Matrices
  18347. this.bindOnlyWorldMatrix(world);
  18348. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18349. // Bones
  18350. if (mesh && mesh.useBones) {
  18351. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18352. }
  18353. if (scene.getCachedMaterial() !== this) {
  18354. if (StandardMaterial.FresnelEnabled) {
  18355. // Fresnel
  18356. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18357. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18358. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18359. }
  18360. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18361. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18362. }
  18363. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18364. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18365. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18366. }
  18367. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18368. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18369. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18370. }
  18371. }
  18372. // Textures
  18373. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18374. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18375. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18376. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18377. }
  18378. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18379. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18380. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18381. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18382. }
  18383. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18384. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18385. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18386. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18387. }
  18388. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18389. if (this.reflectionTexture.isCube) {
  18390. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18391. }
  18392. else {
  18393. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18394. }
  18395. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18396. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18397. }
  18398. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18399. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18400. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18401. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18402. }
  18403. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18404. this._effect.setTexture("specularSampler", this.specularTexture);
  18405. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18406. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18407. }
  18408. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18409. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18410. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18411. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18412. }
  18413. // Clip plane
  18414. if (scene.clipPlane) {
  18415. var clipPlane = scene.clipPlane;
  18416. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18417. }
  18418. // Point size
  18419. if (this.pointsCloud) {
  18420. this._effect.setFloat("pointSize", this.pointSize);
  18421. }
  18422. // Colors
  18423. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18424. // Scaling down color according to emissive
  18425. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18426. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18427. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18428. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18429. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18430. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18431. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18432. }
  18433. // Scaling down color according to emissive
  18434. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18435. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18436. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18437. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18438. if (scene.lightsEnabled) {
  18439. var lightIndex = 0;
  18440. for (var index = 0; index < scene.lights.length; index++) {
  18441. var light = scene.lights[index];
  18442. if (!light.isEnabled()) {
  18443. continue;
  18444. }
  18445. if (!light.canAffectMesh(mesh)) {
  18446. continue;
  18447. }
  18448. if (light instanceof BABYLON.PointLight) {
  18449. // Point Light
  18450. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18451. }
  18452. else if (light instanceof BABYLON.DirectionalLight) {
  18453. // Directional Light
  18454. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18455. }
  18456. else if (light instanceof BABYLON.SpotLight) {
  18457. // Spot Light
  18458. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18459. }
  18460. else if (light instanceof BABYLON.HemisphericLight) {
  18461. // Hemispheric Light
  18462. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18463. }
  18464. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18465. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18466. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18467. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18468. // Shadows
  18469. if (scene.shadowsEnabled) {
  18470. var shadowGenerator = light.getShadowGenerator();
  18471. if (mesh.receiveShadows && shadowGenerator) {
  18472. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18473. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18474. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18475. }
  18476. }
  18477. lightIndex++;
  18478. if (lightIndex === maxSimultaneousLights)
  18479. break;
  18480. }
  18481. }
  18482. // View
  18483. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18484. this._effect.setMatrix("view", scene.getViewMatrix());
  18485. }
  18486. // Fog
  18487. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18488. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18489. this._effect.setColor3("vFogColor", scene.fogColor);
  18490. }
  18491. _super.prototype.bind.call(this, world, mesh);
  18492. };
  18493. StandardMaterial.prototype.getAnimatables = function () {
  18494. var results = [];
  18495. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18496. results.push(this.diffuseTexture);
  18497. }
  18498. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18499. results.push(this.ambientTexture);
  18500. }
  18501. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18502. results.push(this.opacityTexture);
  18503. }
  18504. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18505. results.push(this.reflectionTexture);
  18506. }
  18507. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18508. results.push(this.emissiveTexture);
  18509. }
  18510. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18511. results.push(this.specularTexture);
  18512. }
  18513. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18514. results.push(this.bumpTexture);
  18515. }
  18516. return results;
  18517. };
  18518. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18519. if (this.diffuseTexture) {
  18520. this.diffuseTexture.dispose();
  18521. }
  18522. if (this.ambientTexture) {
  18523. this.ambientTexture.dispose();
  18524. }
  18525. if (this.opacityTexture) {
  18526. this.opacityTexture.dispose();
  18527. }
  18528. if (this.reflectionTexture) {
  18529. this.reflectionTexture.dispose();
  18530. }
  18531. if (this.emissiveTexture) {
  18532. this.emissiveTexture.dispose();
  18533. }
  18534. if (this.specularTexture) {
  18535. this.specularTexture.dispose();
  18536. }
  18537. if (this.bumpTexture) {
  18538. this.bumpTexture.dispose();
  18539. }
  18540. _super.prototype.dispose.call(this, forceDisposeEffect);
  18541. };
  18542. StandardMaterial.prototype.clone = function (name) {
  18543. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18544. // Base material
  18545. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18546. newStandardMaterial.alpha = this.alpha;
  18547. newStandardMaterial.fillMode = this.fillMode;
  18548. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18549. // Standard material
  18550. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18551. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18552. }
  18553. if (this.ambientTexture && this.ambientTexture.clone) {
  18554. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18555. }
  18556. if (this.opacityTexture && this.opacityTexture.clone) {
  18557. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18558. }
  18559. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18560. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18561. }
  18562. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18563. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18564. }
  18565. if (this.specularTexture && this.specularTexture.clone) {
  18566. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18567. }
  18568. if (this.bumpTexture && this.bumpTexture.clone) {
  18569. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18570. }
  18571. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18572. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18573. newStandardMaterial.specularColor = this.specularColor.clone();
  18574. newStandardMaterial.specularPower = this.specularPower;
  18575. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18576. return newStandardMaterial;
  18577. };
  18578. // Statics
  18579. // Flags used to enable or disable a type of texture for all Standard Materials
  18580. StandardMaterial.DiffuseTextureEnabled = true;
  18581. StandardMaterial.AmbientTextureEnabled = true;
  18582. StandardMaterial.OpacityTextureEnabled = true;
  18583. StandardMaterial.ReflectionTextureEnabled = true;
  18584. StandardMaterial.EmissiveTextureEnabled = true;
  18585. StandardMaterial.SpecularTextureEnabled = true;
  18586. StandardMaterial.BumpTextureEnabled = true;
  18587. StandardMaterial.FresnelEnabled = true;
  18588. return StandardMaterial;
  18589. })(BABYLON.Material);
  18590. BABYLON.StandardMaterial = StandardMaterial;
  18591. })(BABYLON || (BABYLON = {}));
  18592. //# sourceMappingURL=babylon.standardMaterial.js.map
  18593. var __extends = this.__extends || function (d, b) {
  18594. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18595. function __() { this.constructor = d; }
  18596. __.prototype = b.prototype;
  18597. d.prototype = new __();
  18598. };
  18599. var BABYLON;
  18600. (function (BABYLON) {
  18601. var MultiMaterial = (function (_super) {
  18602. __extends(MultiMaterial, _super);
  18603. function MultiMaterial(name, scene) {
  18604. _super.call(this, name, scene, true);
  18605. this.subMaterials = new Array();
  18606. scene.multiMaterials.push(this);
  18607. }
  18608. // Properties
  18609. MultiMaterial.prototype.getSubMaterial = function (index) {
  18610. if (index < 0 || index >= this.subMaterials.length) {
  18611. return this.getScene().defaultMaterial;
  18612. }
  18613. return this.subMaterials[index];
  18614. };
  18615. // Methods
  18616. MultiMaterial.prototype.isReady = function (mesh) {
  18617. for (var index = 0; index < this.subMaterials.length; index++) {
  18618. var subMaterial = this.subMaterials[index];
  18619. if (subMaterial) {
  18620. if (!this.subMaterials[index].isReady(mesh)) {
  18621. return false;
  18622. }
  18623. }
  18624. }
  18625. return true;
  18626. };
  18627. MultiMaterial.prototype.clone = function (name) {
  18628. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18629. for (var index = 0; index < this.subMaterials.length; index++) {
  18630. var subMaterial = this.subMaterials[index];
  18631. newMultiMaterial.subMaterials.push(subMaterial);
  18632. }
  18633. return newMultiMaterial;
  18634. };
  18635. return MultiMaterial;
  18636. })(BABYLON.Material);
  18637. BABYLON.MultiMaterial = MultiMaterial;
  18638. })(BABYLON || (BABYLON = {}));
  18639. //# sourceMappingURL=babylon.multiMaterial.js.map
  18640. var BABYLON;
  18641. (function (BABYLON) {
  18642. var SceneLoader = (function () {
  18643. function SceneLoader() {
  18644. }
  18645. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18646. get: function () {
  18647. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18648. },
  18649. set: function (value) {
  18650. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18651. },
  18652. enumerable: true,
  18653. configurable: true
  18654. });
  18655. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18656. get: function () {
  18657. return SceneLoader._ShowLoadingScreen;
  18658. },
  18659. set: function (value) {
  18660. SceneLoader._ShowLoadingScreen = value;
  18661. },
  18662. enumerable: true,
  18663. configurable: true
  18664. });
  18665. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18666. var dotPosition = sceneFilename.lastIndexOf(".");
  18667. var queryStringPosition = sceneFilename.indexOf("?");
  18668. if (queryStringPosition === -1) {
  18669. queryStringPosition = sceneFilename.length;
  18670. }
  18671. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18672. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18673. var plugin = this._registeredPlugins[index];
  18674. if (plugin.extensions.indexOf(extension) !== -1) {
  18675. return plugin;
  18676. }
  18677. }
  18678. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18679. };
  18680. // Public functions
  18681. SceneLoader.RegisterPlugin = function (plugin) {
  18682. plugin.extensions = plugin.extensions.toLowerCase();
  18683. SceneLoader._registeredPlugins.push(plugin);
  18684. };
  18685. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18686. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18687. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18688. return;
  18689. }
  18690. var manifestChecked = function (success) {
  18691. scene.database = database;
  18692. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18693. var importMeshFromData = function (data) {
  18694. var meshes = [];
  18695. var particleSystems = [];
  18696. var skeletons = [];
  18697. try {
  18698. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18699. if (onerror) {
  18700. onerror(scene, 'unable to load the scene');
  18701. }
  18702. return;
  18703. }
  18704. }
  18705. catch (e) {
  18706. if (onerror) {
  18707. onerror(scene, e);
  18708. }
  18709. return;
  18710. }
  18711. if (onsuccess) {
  18712. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18713. onsuccess(meshes, particleSystems, skeletons);
  18714. }
  18715. };
  18716. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18717. // Direct load
  18718. importMeshFromData(sceneFilename.substr(5));
  18719. return;
  18720. }
  18721. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18722. importMeshFromData(data);
  18723. }, progressCallBack, database);
  18724. };
  18725. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18726. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18727. };
  18728. /**
  18729. * Load a scene
  18730. * @param rootUrl a string that defines the root url for scene and resources
  18731. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18732. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18733. */
  18734. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18735. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18736. };
  18737. /**
  18738. * Append a scene
  18739. * @param rootUrl a string that defines the root url for scene and resources
  18740. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18741. * @param scene is the instance of BABYLON.Scene to append to
  18742. */
  18743. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18744. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18745. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18746. return;
  18747. }
  18748. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18749. var database;
  18750. if (SceneLoader.ShowLoadingScreen) {
  18751. scene.getEngine().displayLoadingUI();
  18752. }
  18753. var loadSceneFromData = function (data) {
  18754. scene.database = database;
  18755. if (!plugin.load(scene, data, rootUrl)) {
  18756. if (onerror) {
  18757. onerror(scene);
  18758. }
  18759. scene.getEngine().hideLoadingUI();
  18760. return;
  18761. }
  18762. if (onsuccess) {
  18763. onsuccess(scene);
  18764. }
  18765. if (SceneLoader.ShowLoadingScreen) {
  18766. scene.executeWhenReady(function () {
  18767. scene.getEngine().hideLoadingUI();
  18768. });
  18769. }
  18770. };
  18771. var manifestChecked = function (success) {
  18772. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18773. };
  18774. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18775. // Direct load
  18776. loadSceneFromData(sceneFilename.substr(5));
  18777. return;
  18778. }
  18779. if (rootUrl.indexOf("file:") === -1) {
  18780. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18781. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18782. }
  18783. else {
  18784. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18785. }
  18786. };
  18787. // Flags
  18788. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18789. SceneLoader._ShowLoadingScreen = true;
  18790. // Members
  18791. SceneLoader._registeredPlugins = new Array();
  18792. return SceneLoader;
  18793. })();
  18794. BABYLON.SceneLoader = SceneLoader;
  18795. ;
  18796. })(BABYLON || (BABYLON = {}));
  18797. //# sourceMappingURL=babylon.sceneLoader.js.map
  18798. var BABYLON;
  18799. (function (BABYLON) {
  18800. var Internals;
  18801. (function (Internals) {
  18802. var checkColors4 = function (colors, count) {
  18803. // Check if color3 was used
  18804. if (colors.length === count * 3) {
  18805. var colors4 = [];
  18806. for (var index = 0; index < colors.length; index += 3) {
  18807. var newIndex = (index / 3) * 4;
  18808. colors4[newIndex] = colors[index];
  18809. colors4[newIndex + 1] = colors[index + 1];
  18810. colors4[newIndex + 2] = colors[index + 2];
  18811. colors4[newIndex + 3] = 1.0;
  18812. }
  18813. return colors4;
  18814. }
  18815. return colors;
  18816. };
  18817. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18818. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18819. texture.name = parsedTexture.name;
  18820. texture.hasAlpha = parsedTexture.hasAlpha;
  18821. texture.level = parsedTexture.level;
  18822. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18823. return texture;
  18824. };
  18825. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18826. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18827. return null;
  18828. }
  18829. if (parsedTexture.isCube) {
  18830. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18831. }
  18832. var texture;
  18833. if (parsedTexture.mirrorPlane) {
  18834. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18835. texture._waitingRenderList = parsedTexture.renderList;
  18836. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18837. }
  18838. else if (parsedTexture.isRenderTarget) {
  18839. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18840. texture._waitingRenderList = parsedTexture.renderList;
  18841. }
  18842. else {
  18843. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18844. }
  18845. texture.name = parsedTexture.name;
  18846. texture.hasAlpha = parsedTexture.hasAlpha;
  18847. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18848. texture.level = parsedTexture.level;
  18849. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18850. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18851. texture.uOffset = parsedTexture.uOffset;
  18852. texture.vOffset = parsedTexture.vOffset;
  18853. texture.uScale = parsedTexture.uScale;
  18854. texture.vScale = parsedTexture.vScale;
  18855. texture.uAng = parsedTexture.uAng;
  18856. texture.vAng = parsedTexture.vAng;
  18857. texture.wAng = parsedTexture.wAng;
  18858. texture.wrapU = parsedTexture.wrapU;
  18859. texture.wrapV = parsedTexture.wrapV;
  18860. // Animations
  18861. if (parsedTexture.animations) {
  18862. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18863. var parsedAnimation = parsedTexture.animations[animationIndex];
  18864. texture.animations.push(parseAnimation(parsedAnimation));
  18865. }
  18866. }
  18867. return texture;
  18868. };
  18869. var parseSkeleton = function (parsedSkeleton, scene) {
  18870. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18871. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18872. var parsedBone = parsedSkeleton.bones[index];
  18873. var parentBone = null;
  18874. if (parsedBone.parentBoneIndex > -1) {
  18875. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18876. }
  18877. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18878. if (parsedBone.animation) {
  18879. bone.animations.push(parseAnimation(parsedBone.animation));
  18880. }
  18881. }
  18882. return skeleton;
  18883. };
  18884. var parseFresnelParameters = function (parsedFresnelParameters) {
  18885. var fresnelParameters = new BABYLON.FresnelParameters();
  18886. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18887. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18888. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18889. fresnelParameters.bias = parsedFresnelParameters.bias;
  18890. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18891. return fresnelParameters;
  18892. };
  18893. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18894. var material;
  18895. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18896. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18897. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18898. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18899. material.specularPower = parsedMaterial.specularPower;
  18900. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18901. material.alpha = parsedMaterial.alpha;
  18902. material.id = parsedMaterial.id;
  18903. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18904. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18905. material.wireframe = parsedMaterial.wireframe;
  18906. if (parsedMaterial.diffuseTexture) {
  18907. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18908. }
  18909. if (parsedMaterial.diffuseFresnelParameters) {
  18910. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18911. }
  18912. if (parsedMaterial.ambientTexture) {
  18913. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18914. }
  18915. if (parsedMaterial.opacityTexture) {
  18916. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18917. }
  18918. if (parsedMaterial.opacityFresnelParameters) {
  18919. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18920. }
  18921. if (parsedMaterial.reflectionTexture) {
  18922. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18923. }
  18924. if (parsedMaterial.reflectionFresnelParameters) {
  18925. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18926. }
  18927. if (parsedMaterial.emissiveTexture) {
  18928. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18929. }
  18930. if (parsedMaterial.emissiveFresnelParameters) {
  18931. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18932. }
  18933. if (parsedMaterial.specularTexture) {
  18934. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18935. }
  18936. if (parsedMaterial.bumpTexture) {
  18937. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18938. }
  18939. return material;
  18940. };
  18941. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18942. for (var index = 0; index < parsedData.materials.length; index++) {
  18943. var parsedMaterial = parsedData.materials[index];
  18944. if (parsedMaterial.id === id) {
  18945. return parseMaterial(parsedMaterial, scene, rootUrl);
  18946. }
  18947. }
  18948. return null;
  18949. };
  18950. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18951. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18952. multiMaterial.id = parsedMultiMaterial.id;
  18953. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18954. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18955. var subMatId = parsedMultiMaterial.materials[matIndex];
  18956. if (subMatId) {
  18957. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18958. }
  18959. else {
  18960. multiMaterial.subMaterials.push(null);
  18961. }
  18962. }
  18963. return multiMaterial;
  18964. };
  18965. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18966. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18967. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18968. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18969. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18970. var parsedFlare = parsedLensFlareSystem.flares[index];
  18971. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18972. }
  18973. return lensFlareSystem;
  18974. };
  18975. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18976. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18977. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18978. if (parsedParticleSystem.textureName) {
  18979. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18980. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18981. }
  18982. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18983. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18984. particleSystem.minSize = parsedParticleSystem.minSize;
  18985. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18986. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18987. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18988. particleSystem.emitter = emitter;
  18989. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18990. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18991. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18992. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18993. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18994. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18995. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18996. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18997. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18998. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18999. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19000. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19001. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19002. particleSystem.start();
  19003. return particleSystem;
  19004. };
  19005. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19006. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19007. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19008. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19009. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19010. shadowGenerator.getShadowMap().renderList.push(mesh);
  19011. }
  19012. if (parsedShadowGenerator.usePoissonSampling) {
  19013. shadowGenerator.usePoissonSampling = true;
  19014. }
  19015. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19016. shadowGenerator.useVarianceShadowMap = true;
  19017. }
  19018. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19019. shadowGenerator.useBlurVarianceShadowMap = true;
  19020. if (parsedShadowGenerator.blurScale) {
  19021. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19022. }
  19023. if (parsedShadowGenerator.blurBoxOffset) {
  19024. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19025. }
  19026. }
  19027. if (parsedShadowGenerator.bias !== undefined) {
  19028. shadowGenerator.bias = parsedShadowGenerator.bias;
  19029. }
  19030. return shadowGenerator;
  19031. };
  19032. var parseAnimation = function (parsedAnimation) {
  19033. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19034. var dataType = parsedAnimation.dataType;
  19035. var keys = [];
  19036. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19037. var key = parsedAnimation.keys[index];
  19038. var data;
  19039. switch (dataType) {
  19040. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19041. data = key.values[0];
  19042. break;
  19043. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19044. data = BABYLON.Quaternion.FromArray(key.values);
  19045. break;
  19046. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19047. data = BABYLON.Matrix.FromArray(key.values);
  19048. break;
  19049. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19050. default:
  19051. data = BABYLON.Vector3.FromArray(key.values);
  19052. break;
  19053. }
  19054. keys.push({
  19055. frame: key.frame,
  19056. value: data
  19057. });
  19058. }
  19059. animation.setKeys(keys);
  19060. return animation;
  19061. };
  19062. var parseLight = function (parsedLight, scene) {
  19063. var light;
  19064. switch (parsedLight.type) {
  19065. case 0:
  19066. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19067. break;
  19068. case 1:
  19069. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19070. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19071. break;
  19072. case 2:
  19073. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19074. break;
  19075. case 3:
  19076. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19077. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19078. break;
  19079. }
  19080. light.id = parsedLight.id;
  19081. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19082. if (parsedLight.intensity !== undefined) {
  19083. light.intensity = parsedLight.intensity;
  19084. }
  19085. if (parsedLight.range) {
  19086. light.range = parsedLight.range;
  19087. }
  19088. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19089. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19090. if (parsedLight.excludedMeshesIds) {
  19091. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19092. }
  19093. // Parent
  19094. if (parsedLight.parentId) {
  19095. light._waitingParentId = parsedLight.parentId;
  19096. }
  19097. if (parsedLight.includedOnlyMeshesIds) {
  19098. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19099. }
  19100. // Animations
  19101. if (parsedLight.animations) {
  19102. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19103. var parsedAnimation = parsedLight.animations[animationIndex];
  19104. light.animations.push(parseAnimation(parsedAnimation));
  19105. }
  19106. }
  19107. if (parsedLight.autoAnimate) {
  19108. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19109. }
  19110. };
  19111. var parseCamera = function (parsedCamera, scene) {
  19112. var camera;
  19113. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19114. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19115. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19116. var alpha = parsedCamera.alpha;
  19117. var beta = parsedCamera.beta;
  19118. var radius = parsedCamera.radius;
  19119. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19120. var eye_space = parsedCamera.eye_space;
  19121. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19122. }
  19123. else {
  19124. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19125. }
  19126. }
  19127. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19128. eye_space = parsedCamera.eye_space;
  19129. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19130. }
  19131. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19132. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19133. }
  19134. else if (parsedCamera.type === "FollowCamera") {
  19135. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19136. camera.heightOffset = parsedCamera.heightOffset;
  19137. camera.radius = parsedCamera.radius;
  19138. camera.rotationOffset = parsedCamera.rotationOffset;
  19139. if (lockedTargetMesh)
  19140. camera.target = lockedTargetMesh;
  19141. }
  19142. else if (parsedCamera.type === "GamepadCamera") {
  19143. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19144. }
  19145. else if (parsedCamera.type === "TouchCamera") {
  19146. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19147. }
  19148. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19149. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19150. }
  19151. else if (parsedCamera.type === "WebVRFreeCamera") {
  19152. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19153. }
  19154. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19155. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19156. }
  19157. else {
  19158. // Free Camera is the default value
  19159. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19160. }
  19161. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19162. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19163. camera.lockedTarget = lockedTargetMesh;
  19164. }
  19165. camera.id = parsedCamera.id;
  19166. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19167. // Parent
  19168. if (parsedCamera.parentId) {
  19169. camera._waitingParentId = parsedCamera.parentId;
  19170. }
  19171. // Target
  19172. if (parsedCamera.target) {
  19173. if (camera.setTarget) {
  19174. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19175. }
  19176. else {
  19177. //For ArcRotate
  19178. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19179. }
  19180. }
  19181. else {
  19182. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19183. }
  19184. camera.fov = parsedCamera.fov;
  19185. camera.minZ = parsedCamera.minZ;
  19186. camera.maxZ = parsedCamera.maxZ;
  19187. camera.speed = parsedCamera.speed;
  19188. camera.inertia = parsedCamera.inertia;
  19189. camera.checkCollisions = parsedCamera.checkCollisions;
  19190. camera.applyGravity = parsedCamera.applyGravity;
  19191. if (parsedCamera.ellipsoid) {
  19192. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19193. }
  19194. // Animations
  19195. if (parsedCamera.animations) {
  19196. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19197. var parsedAnimation = parsedCamera.animations[animationIndex];
  19198. camera.animations.push(parseAnimation(parsedAnimation));
  19199. }
  19200. }
  19201. if (parsedCamera.autoAnimate) {
  19202. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19203. }
  19204. // Layer Mask
  19205. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19206. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19207. }
  19208. else {
  19209. camera.layerMask = 0xFFFFFFFF;
  19210. }
  19211. return camera;
  19212. };
  19213. var parseGeometry = function (parsedGeometry, scene) {
  19214. var id = parsedGeometry.id;
  19215. return scene.getGeometryByID(id);
  19216. };
  19217. var parseBox = function (parsedBox, scene) {
  19218. if (parseGeometry(parsedBox, scene)) {
  19219. return null; // null since geometry could be something else than a box...
  19220. }
  19221. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19222. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19223. scene.pushGeometry(box, true);
  19224. return box;
  19225. };
  19226. var parseSphere = function (parsedSphere, scene) {
  19227. if (parseGeometry(parsedSphere, scene)) {
  19228. return null; // null since geometry could be something else than a sphere...
  19229. }
  19230. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19231. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19232. scene.pushGeometry(sphere, true);
  19233. return sphere;
  19234. };
  19235. var parseCylinder = function (parsedCylinder, scene) {
  19236. if (parseGeometry(parsedCylinder, scene)) {
  19237. return null; // null since geometry could be something else than a cylinder...
  19238. }
  19239. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19240. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19241. scene.pushGeometry(cylinder, true);
  19242. return cylinder;
  19243. };
  19244. var parseTorus = function (parsedTorus, scene) {
  19245. if (parseGeometry(parsedTorus, scene)) {
  19246. return null; // null since geometry could be something else than a torus...
  19247. }
  19248. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19249. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19250. scene.pushGeometry(torus, true);
  19251. return torus;
  19252. };
  19253. var parseGround = function (parsedGround, scene) {
  19254. if (parseGeometry(parsedGround, scene)) {
  19255. return null; // null since geometry could be something else than a ground...
  19256. }
  19257. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19258. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19259. scene.pushGeometry(ground, true);
  19260. return ground;
  19261. };
  19262. var parsePlane = function (parsedPlane, scene) {
  19263. if (parseGeometry(parsedPlane, scene)) {
  19264. return null; // null since geometry could be something else than a plane...
  19265. }
  19266. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19267. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19268. scene.pushGeometry(plane, true);
  19269. return plane;
  19270. };
  19271. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19272. if (parseGeometry(parsedTorusKnot, scene)) {
  19273. return null; // null since geometry could be something else than a torusKnot...
  19274. }
  19275. 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);
  19276. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19277. scene.pushGeometry(torusKnot, true);
  19278. return torusKnot;
  19279. };
  19280. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19281. if (parseGeometry(parsedVertexData, scene)) {
  19282. return null; // null since geometry could be a primitive
  19283. }
  19284. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19285. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19286. if (parsedVertexData.delayLoadingFile) {
  19287. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19288. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19289. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19290. geometry._delayInfo = [];
  19291. if (parsedVertexData.hasUVs) {
  19292. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19293. }
  19294. if (parsedVertexData.hasUVs2) {
  19295. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19296. }
  19297. if (parsedVertexData.hasColors) {
  19298. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19299. }
  19300. if (parsedVertexData.hasMatricesIndices) {
  19301. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19302. }
  19303. if (parsedVertexData.hasMatricesWeights) {
  19304. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19305. }
  19306. geometry._delayLoadingFunction = importVertexData;
  19307. }
  19308. else {
  19309. importVertexData(parsedVertexData, geometry);
  19310. }
  19311. scene.pushGeometry(geometry, true);
  19312. return geometry;
  19313. };
  19314. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19315. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19316. mesh.id = parsedMesh.id;
  19317. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19318. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19319. if (parsedMesh.rotationQuaternion) {
  19320. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19321. }
  19322. else if (parsedMesh.rotation) {
  19323. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19324. }
  19325. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19326. if (parsedMesh.localMatrix) {
  19327. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19328. }
  19329. else if (parsedMesh.pivotMatrix) {
  19330. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19331. }
  19332. mesh.setEnabled(parsedMesh.isEnabled);
  19333. mesh.isVisible = parsedMesh.isVisible;
  19334. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19335. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19336. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19337. if (parsedMesh.applyFog !== undefined) {
  19338. mesh.applyFog = parsedMesh.applyFog;
  19339. }
  19340. if (parsedMesh.pickable !== undefined) {
  19341. mesh.isPickable = parsedMesh.pickable;
  19342. }
  19343. if (parsedMesh.alphaIndex !== undefined) {
  19344. mesh.alphaIndex = parsedMesh.alphaIndex;
  19345. }
  19346. mesh.receiveShadows = parsedMesh.receiveShadows;
  19347. mesh.billboardMode = parsedMesh.billboardMode;
  19348. if (parsedMesh.visibility !== undefined) {
  19349. mesh.visibility = parsedMesh.visibility;
  19350. }
  19351. mesh.checkCollisions = parsedMesh.checkCollisions;
  19352. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19353. // Parent
  19354. if (parsedMesh.parentId) {
  19355. mesh._waitingParentId = parsedMesh.parentId;
  19356. }
  19357. // Actions
  19358. if (parsedMesh.actions !== undefined) {
  19359. mesh._waitingActions = parsedMesh.actions;
  19360. }
  19361. // Geometry
  19362. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19363. if (parsedMesh.delayLoadingFile) {
  19364. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19365. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19366. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19367. if (parsedMesh._binaryInfo) {
  19368. mesh._binaryInfo = parsedMesh._binaryInfo;
  19369. }
  19370. mesh._delayInfo = [];
  19371. if (parsedMesh.hasUVs) {
  19372. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19373. }
  19374. if (parsedMesh.hasUVs2) {
  19375. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19376. }
  19377. if (parsedMesh.hasColors) {
  19378. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19379. }
  19380. if (parsedMesh.hasMatricesIndices) {
  19381. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19382. }
  19383. if (parsedMesh.hasMatricesWeights) {
  19384. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19385. }
  19386. mesh._delayLoadingFunction = importGeometry;
  19387. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19388. mesh._checkDelayState();
  19389. }
  19390. }
  19391. else {
  19392. importGeometry(parsedMesh, mesh);
  19393. }
  19394. // Material
  19395. if (parsedMesh.materialId) {
  19396. mesh.setMaterialByID(parsedMesh.materialId);
  19397. }
  19398. else {
  19399. mesh.material = null;
  19400. }
  19401. // Skeleton
  19402. if (parsedMesh.skeletonId > -1) {
  19403. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19404. }
  19405. // Physics
  19406. if (parsedMesh.physicsImpostor) {
  19407. if (!scene.isPhysicsEnabled()) {
  19408. scene.enablePhysics();
  19409. }
  19410. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19411. }
  19412. // Animations
  19413. if (parsedMesh.animations) {
  19414. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19415. var parsedAnimation = parsedMesh.animations[animationIndex];
  19416. mesh.animations.push(parseAnimation(parsedAnimation));
  19417. }
  19418. }
  19419. if (parsedMesh.autoAnimate) {
  19420. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19421. }
  19422. // Layer Mask
  19423. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19424. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19425. }
  19426. else {
  19427. mesh.layerMask = 0xFFFFFFFF;
  19428. }
  19429. // Instances
  19430. if (parsedMesh.instances) {
  19431. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19432. var parsedInstance = parsedMesh.instances[index];
  19433. var instance = mesh.createInstance(parsedInstance.name);
  19434. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19435. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19436. if (parsedInstance.rotationQuaternion) {
  19437. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19438. }
  19439. else if (parsedInstance.rotation) {
  19440. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19441. }
  19442. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19443. instance.checkCollisions = mesh.checkCollisions;
  19444. if (parsedMesh.animations) {
  19445. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19446. parsedAnimation = parsedMesh.animations[animationIndex];
  19447. instance.animations.push(parseAnimation(parsedAnimation));
  19448. }
  19449. }
  19450. }
  19451. }
  19452. return mesh;
  19453. };
  19454. var parseActions = function (parsedActions, object, scene) {
  19455. var actionManager = new BABYLON.ActionManager(scene);
  19456. if (object === null)
  19457. scene.actionManager = actionManager;
  19458. else
  19459. object.actionManager = actionManager;
  19460. // instanciate a new object
  19461. var instanciate = function (name, params) {
  19462. var newInstance = Object.create(BABYLON[name].prototype);
  19463. newInstance.constructor.apply(newInstance, params);
  19464. return newInstance;
  19465. };
  19466. var parseParameter = function (name, value, target, propertyPath) {
  19467. if (propertyPath === null) {
  19468. // String, boolean or float
  19469. var floatValue = parseFloat(value);
  19470. if (value === "true" || value === "false")
  19471. return value === "true";
  19472. else
  19473. return isNaN(floatValue) ? value : floatValue;
  19474. }
  19475. var effectiveTarget = propertyPath.split(".");
  19476. var values = value.split(",");
  19477. // Get effective Target
  19478. for (var i = 0; i < effectiveTarget.length; i++) {
  19479. target = target[effectiveTarget[i]];
  19480. }
  19481. // Return appropriate value with its type
  19482. if (typeof (target) === "boolean")
  19483. return values[0] === "true";
  19484. if (typeof (target) === "string")
  19485. return values[0];
  19486. // Parameters with multiple values such as Vector3 etc.
  19487. var split = new Array();
  19488. for (var i = 0; i < values.length; i++)
  19489. split.push(parseFloat(values[i]));
  19490. if (target instanceof BABYLON.Vector3)
  19491. return BABYLON.Vector3.FromArray(split);
  19492. if (target instanceof BABYLON.Vector4)
  19493. return BABYLON.Vector4.FromArray(split);
  19494. if (target instanceof BABYLON.Color3)
  19495. return BABYLON.Color3.FromArray(split);
  19496. if (target instanceof BABYLON.Color4)
  19497. return BABYLON.Color4.FromArray(split);
  19498. return parseFloat(values[0]);
  19499. };
  19500. // traverse graph per trigger
  19501. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19502. if (combineArray === void 0) { combineArray = null; }
  19503. if (parsedAction.detached)
  19504. return;
  19505. var parameters = new Array();
  19506. var target = null;
  19507. var propertyPath = null;
  19508. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19509. // Parameters
  19510. if (parsedAction.type === 2)
  19511. parameters.push(actionManager);
  19512. else
  19513. parameters.push(trigger);
  19514. if (combine) {
  19515. var actions = new Array();
  19516. for (var j = 0; j < parsedAction.combine.length; j++) {
  19517. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19518. }
  19519. parameters.push(actions);
  19520. }
  19521. else {
  19522. for (var i = 0; i < parsedAction.properties.length; i++) {
  19523. var value = parsedAction.properties[i].value;
  19524. var name = parsedAction.properties[i].name;
  19525. var targetType = parsedAction.properties[i].targetType;
  19526. if (name === "target")
  19527. if (targetType !== null && targetType === "SceneProperties")
  19528. value = target = scene;
  19529. else
  19530. value = target = scene.getNodeByName(value);
  19531. else if (name === "parent")
  19532. value = scene.getNodeByName(value);
  19533. else if (name === "sound")
  19534. value = scene.getSoundByName(value);
  19535. else if (name !== "propertyPath") {
  19536. if (parsedAction.type === 2 && name === "operator")
  19537. value = BABYLON.ValueCondition[value];
  19538. else
  19539. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19540. }
  19541. else {
  19542. propertyPath = value;
  19543. }
  19544. parameters.push(value);
  19545. }
  19546. }
  19547. if (combineArray === null) {
  19548. parameters.push(condition);
  19549. }
  19550. else {
  19551. parameters.push(null);
  19552. }
  19553. // If interpolate value action
  19554. if (parsedAction.name === "InterpolateValueAction") {
  19555. var param = parameters[parameters.length - 2];
  19556. parameters[parameters.length - 1] = param;
  19557. parameters[parameters.length - 2] = condition;
  19558. }
  19559. // Action or condition(s) and not CombineAction
  19560. var newAction = instanciate(parsedAction.name, parameters);
  19561. if (combineArray === null) {
  19562. if (newAction instanceof BABYLON.Condition) {
  19563. condition = newAction;
  19564. newAction = action;
  19565. }
  19566. else {
  19567. condition = null;
  19568. if (action)
  19569. action.then(newAction);
  19570. else
  19571. actionManager.registerAction(newAction);
  19572. }
  19573. }
  19574. else {
  19575. combineArray.push(newAction);
  19576. }
  19577. for (var i = 0; i < parsedAction.children.length; i++)
  19578. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19579. };
  19580. // triggers
  19581. for (var i = 0; i < parsedActions.children.length; i++) {
  19582. var triggerParams;
  19583. var trigger = parsedActions.children[i];
  19584. if (trigger.properties.length > 0) {
  19585. var param = trigger.properties[0].value;
  19586. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19587. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19588. }
  19589. else
  19590. triggerParams = BABYLON.ActionManager[trigger.name];
  19591. for (var j = 0; j < trigger.children.length; j++) {
  19592. if (!trigger.detached)
  19593. traverse(trigger.children[j], triggerParams, null, null);
  19594. }
  19595. }
  19596. };
  19597. var parseSound = function (parsedSound, scene, rootUrl) {
  19598. var soundName = parsedSound.name;
  19599. var soundUrl = rootUrl + soundName;
  19600. var options = {
  19601. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19602. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19603. rolloffFactor: parsedSound.rolloffFactor,
  19604. refDistance: parsedSound.refDistance,
  19605. distanceModel: parsedSound.distanceModel,
  19606. playbackRate: parsedSound.playbackRate
  19607. };
  19608. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19609. scene._addPendingData(newSound);
  19610. if (parsedSound.position) {
  19611. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19612. newSound.setPosition(soundPosition);
  19613. }
  19614. if (parsedSound.isDirectional) {
  19615. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19616. if (parsedSound.localDirectionToMesh) {
  19617. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19618. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19619. }
  19620. }
  19621. if (parsedSound.connectedMeshId) {
  19622. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19623. if (connectedMesh) {
  19624. newSound.attachToMesh(connectedMesh);
  19625. }
  19626. }
  19627. };
  19628. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19629. names = (names instanceof Array) ? names : [names];
  19630. for (var i in names) {
  19631. if (mesh.name === names[i]) {
  19632. hierarchyIds.push(mesh.id);
  19633. return true;
  19634. }
  19635. }
  19636. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19637. hierarchyIds.push(mesh.id);
  19638. return true;
  19639. }
  19640. return false;
  19641. };
  19642. var importVertexData = function (parsedVertexData, geometry) {
  19643. var vertexData = new BABYLON.VertexData();
  19644. // positions
  19645. var positions = parsedVertexData.positions;
  19646. if (positions) {
  19647. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19648. }
  19649. // normals
  19650. var normals = parsedVertexData.normals;
  19651. if (normals) {
  19652. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19653. }
  19654. // uvs
  19655. var uvs = parsedVertexData.uvs;
  19656. if (uvs) {
  19657. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19658. }
  19659. // uv2s
  19660. var uv2s = parsedVertexData.uv2s;
  19661. if (uv2s) {
  19662. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19663. }
  19664. // colors
  19665. var colors = parsedVertexData.colors;
  19666. if (colors) {
  19667. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19668. }
  19669. // matricesIndices
  19670. var matricesIndices = parsedVertexData.matricesIndices;
  19671. if (matricesIndices) {
  19672. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19673. }
  19674. // matricesWeights
  19675. var matricesWeights = parsedVertexData.matricesWeights;
  19676. if (matricesWeights) {
  19677. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19678. }
  19679. // indices
  19680. var indices = parsedVertexData.indices;
  19681. if (indices) {
  19682. vertexData.indices = indices;
  19683. }
  19684. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19685. };
  19686. var importGeometry = function (parsedGeometry, mesh) {
  19687. var scene = mesh.getScene();
  19688. // Geometry
  19689. var geometryId = parsedGeometry.geometryId;
  19690. if (geometryId) {
  19691. var geometry = scene.getGeometryByID(geometryId);
  19692. if (geometry) {
  19693. geometry.applyToMesh(mesh);
  19694. }
  19695. }
  19696. else if (parsedGeometry instanceof ArrayBuffer) {
  19697. var binaryInfo = mesh._binaryInfo;
  19698. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19699. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19700. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19701. }
  19702. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19703. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19704. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19705. }
  19706. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19707. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19708. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19709. }
  19710. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19711. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19712. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19713. }
  19714. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19715. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19716. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19717. }
  19718. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19719. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19720. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19721. }
  19722. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19723. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19724. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19725. }
  19726. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19727. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19728. mesh.setIndices(indicesData);
  19729. }
  19730. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19731. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19732. mesh.subMeshes = [];
  19733. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19734. var materialIndex = subMeshesData[(i * 5) + 0];
  19735. var verticesStart = subMeshesData[(i * 5) + 1];
  19736. var verticesCount = subMeshesData[(i * 5) + 2];
  19737. var indexStart = subMeshesData[(i * 5) + 3];
  19738. var indexCount = subMeshesData[(i * 5) + 4];
  19739. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19740. }
  19741. }
  19742. }
  19743. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19744. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19745. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19746. if (parsedGeometry.uvs) {
  19747. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19748. }
  19749. if (parsedGeometry.uvs2) {
  19750. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19751. }
  19752. if (parsedGeometry.colors) {
  19753. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19754. }
  19755. if (parsedGeometry.matricesIndices) {
  19756. if (!parsedGeometry.matricesIndices._isExpanded) {
  19757. var floatIndices = [];
  19758. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19759. var matricesIndex = parsedGeometry.matricesIndices[i];
  19760. floatIndices.push(matricesIndex & 0x000000FF);
  19761. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19762. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19763. floatIndices.push(matricesIndex >> 24);
  19764. }
  19765. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19766. }
  19767. else {
  19768. delete parsedGeometry.matricesIndices._isExpanded;
  19769. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19770. }
  19771. }
  19772. if (parsedGeometry.matricesWeights) {
  19773. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19774. }
  19775. mesh.setIndices(parsedGeometry.indices);
  19776. // SubMeshes
  19777. if (parsedGeometry.subMeshes) {
  19778. mesh.subMeshes = [];
  19779. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19780. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19781. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19782. }
  19783. }
  19784. }
  19785. // Flat shading
  19786. if (mesh._shouldGenerateFlatShading) {
  19787. mesh.convertToFlatShadedMesh();
  19788. delete mesh._shouldGenerateFlatShading;
  19789. }
  19790. // Update
  19791. mesh.computeWorldMatrix(true);
  19792. // Octree
  19793. if (scene._selectionOctree) {
  19794. scene._selectionOctree.addMesh(mesh);
  19795. }
  19796. };
  19797. BABYLON.SceneLoader.RegisterPlugin({
  19798. extensions: ".babylon",
  19799. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19800. var parsedData = JSON.parse(data);
  19801. var loadedSkeletonsIds = [];
  19802. var loadedMaterialsIds = [];
  19803. var hierarchyIds = [];
  19804. for (var index = 0; index < parsedData.meshes.length; index++) {
  19805. var parsedMesh = parsedData.meshes[index];
  19806. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19807. if (meshesNames instanceof Array) {
  19808. // Remove found mesh name from list.
  19809. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19810. }
  19811. //Geometry?
  19812. if (parsedMesh.geometryId) {
  19813. //does the file contain geometries?
  19814. if (parsedData.geometries) {
  19815. //find the correct geometry and add it to the scene
  19816. var found = false;
  19817. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19818. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19819. return;
  19820. }
  19821. else {
  19822. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19823. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19824. switch (geometryType) {
  19825. case "boxes":
  19826. parseBox(parsedGeometryData, scene);
  19827. break;
  19828. case "spheres":
  19829. parseSphere(parsedGeometryData, scene);
  19830. break;
  19831. case "cylinders":
  19832. parseCylinder(parsedGeometryData, scene);
  19833. break;
  19834. case "toruses":
  19835. parseTorus(parsedGeometryData, scene);
  19836. break;
  19837. case "grounds":
  19838. parseGround(parsedGeometryData, scene);
  19839. break;
  19840. case "planes":
  19841. parsePlane(parsedGeometryData, scene);
  19842. break;
  19843. case "torusKnots":
  19844. parseTorusKnot(parsedGeometryData, scene);
  19845. break;
  19846. case "vertexData":
  19847. parseVertexData(parsedGeometryData, scene, rootUrl);
  19848. break;
  19849. }
  19850. found = true;
  19851. }
  19852. });
  19853. }
  19854. });
  19855. }
  19856. }
  19857. // Material ?
  19858. if (parsedMesh.materialId) {
  19859. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19860. if (!materialFound) {
  19861. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19862. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19863. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19864. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19865. var subMatId = parsedMultiMaterial.materials[matIndex];
  19866. loadedMaterialsIds.push(subMatId);
  19867. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19868. }
  19869. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19870. parseMultiMaterial(parsedMultiMaterial, scene);
  19871. materialFound = true;
  19872. break;
  19873. }
  19874. }
  19875. }
  19876. if (!materialFound) {
  19877. loadedMaterialsIds.push(parsedMesh.materialId);
  19878. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19879. }
  19880. }
  19881. // Skeleton ?
  19882. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19883. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19884. if (!skeletonAlreadyLoaded) {
  19885. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19886. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19887. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19888. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19889. loadedSkeletonsIds.push(parsedSkeleton.id);
  19890. }
  19891. }
  19892. }
  19893. }
  19894. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19895. meshes.push(mesh);
  19896. }
  19897. }
  19898. // Connecting parents
  19899. for (index = 0; index < scene.meshes.length; index++) {
  19900. var currentMesh = scene.meshes[index];
  19901. if (currentMesh._waitingParentId) {
  19902. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19903. currentMesh._waitingParentId = undefined;
  19904. }
  19905. }
  19906. // Particles
  19907. if (parsedData.particleSystems) {
  19908. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19909. var parsedParticleSystem = parsedData.particleSystems[index];
  19910. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19911. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19912. }
  19913. }
  19914. }
  19915. return true;
  19916. },
  19917. load: function (scene, data, rootUrl) {
  19918. var parsedData = JSON.parse(data);
  19919. // Scene
  19920. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19921. scene.autoClear = parsedData.autoClear;
  19922. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19923. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19924. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19925. // Fog
  19926. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19927. scene.fogMode = parsedData.fogMode;
  19928. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19929. scene.fogStart = parsedData.fogStart;
  19930. scene.fogEnd = parsedData.fogEnd;
  19931. scene.fogDensity = parsedData.fogDensity;
  19932. }
  19933. // Lights
  19934. for (var index = 0; index < parsedData.lights.length; index++) {
  19935. var parsedLight = parsedData.lights[index];
  19936. parseLight(parsedLight, scene);
  19937. }
  19938. // Materials
  19939. if (parsedData.materials) {
  19940. for (index = 0; index < parsedData.materials.length; index++) {
  19941. var parsedMaterial = parsedData.materials[index];
  19942. parseMaterial(parsedMaterial, scene, rootUrl);
  19943. }
  19944. }
  19945. if (parsedData.multiMaterials) {
  19946. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19947. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19948. parseMultiMaterial(parsedMultiMaterial, scene);
  19949. }
  19950. }
  19951. // Skeletons
  19952. if (parsedData.skeletons) {
  19953. for (index = 0; index < parsedData.skeletons.length; index++) {
  19954. var parsedSkeleton = parsedData.skeletons[index];
  19955. parseSkeleton(parsedSkeleton, scene);
  19956. }
  19957. }
  19958. // Geometries
  19959. var geometries = parsedData.geometries;
  19960. if (geometries) {
  19961. // Boxes
  19962. var boxes = geometries.boxes;
  19963. if (boxes) {
  19964. for (index = 0; index < boxes.length; index++) {
  19965. var parsedBox = boxes[index];
  19966. parseBox(parsedBox, scene);
  19967. }
  19968. }
  19969. // Spheres
  19970. var spheres = geometries.spheres;
  19971. if (spheres) {
  19972. for (index = 0; index < spheres.length; index++) {
  19973. var parsedSphere = spheres[index];
  19974. parseSphere(parsedSphere, scene);
  19975. }
  19976. }
  19977. // Cylinders
  19978. var cylinders = geometries.cylinders;
  19979. if (cylinders) {
  19980. for (index = 0; index < cylinders.length; index++) {
  19981. var parsedCylinder = cylinders[index];
  19982. parseCylinder(parsedCylinder, scene);
  19983. }
  19984. }
  19985. // Toruses
  19986. var toruses = geometries.toruses;
  19987. if (toruses) {
  19988. for (index = 0; index < toruses.length; index++) {
  19989. var parsedTorus = toruses[index];
  19990. parseTorus(parsedTorus, scene);
  19991. }
  19992. }
  19993. // Grounds
  19994. var grounds = geometries.grounds;
  19995. if (grounds) {
  19996. for (index = 0; index < grounds.length; index++) {
  19997. var parsedGround = grounds[index];
  19998. parseGround(parsedGround, scene);
  19999. }
  20000. }
  20001. // Planes
  20002. var planes = geometries.planes;
  20003. if (planes) {
  20004. for (index = 0; index < planes.length; index++) {
  20005. var parsedPlane = planes[index];
  20006. parsePlane(parsedPlane, scene);
  20007. }
  20008. }
  20009. // TorusKnots
  20010. var torusKnots = geometries.torusKnots;
  20011. if (torusKnots) {
  20012. for (index = 0; index < torusKnots.length; index++) {
  20013. var parsedTorusKnot = torusKnots[index];
  20014. parseTorusKnot(parsedTorusKnot, scene);
  20015. }
  20016. }
  20017. // VertexData
  20018. var vertexData = geometries.vertexData;
  20019. if (vertexData) {
  20020. for (index = 0; index < vertexData.length; index++) {
  20021. var parsedVertexData = vertexData[index];
  20022. parseVertexData(parsedVertexData, scene, rootUrl);
  20023. }
  20024. }
  20025. }
  20026. // Meshes
  20027. for (index = 0; index < parsedData.meshes.length; index++) {
  20028. var parsedMesh = parsedData.meshes[index];
  20029. parseMesh(parsedMesh, scene, rootUrl);
  20030. }
  20031. // Cameras
  20032. for (index = 0; index < parsedData.cameras.length; index++) {
  20033. var parsedCamera = parsedData.cameras[index];
  20034. parseCamera(parsedCamera, scene);
  20035. }
  20036. if (parsedData.activeCameraID) {
  20037. scene.setActiveCameraByID(parsedData.activeCameraID);
  20038. }
  20039. // Browsing all the graph to connect the dots
  20040. for (index = 0; index < scene.cameras.length; index++) {
  20041. var camera = scene.cameras[index];
  20042. if (camera._waitingParentId) {
  20043. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20044. camera._waitingParentId = undefined;
  20045. }
  20046. }
  20047. for (index = 0; index < scene.lights.length; index++) {
  20048. var light = scene.lights[index];
  20049. if (light._waitingParentId) {
  20050. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20051. light._waitingParentId = undefined;
  20052. }
  20053. }
  20054. // Sounds
  20055. if (parsedData.sounds) {
  20056. for (index = 0; index < parsedData.sounds.length; index++) {
  20057. var parsedSound = parsedData.sounds[index];
  20058. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20059. parseSound(parsedSound, scene, rootUrl);
  20060. }
  20061. else {
  20062. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20063. }
  20064. }
  20065. }
  20066. // Connect parents & children and parse actions
  20067. for (index = 0; index < scene.meshes.length; index++) {
  20068. var mesh = scene.meshes[index];
  20069. if (mesh._waitingParentId) {
  20070. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20071. mesh._waitingParentId = undefined;
  20072. }
  20073. if (mesh._waitingActions) {
  20074. parseActions(mesh._waitingActions, mesh, scene);
  20075. mesh._waitingActions = undefined;
  20076. }
  20077. }
  20078. // Particles Systems
  20079. if (parsedData.particleSystems) {
  20080. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20081. var parsedParticleSystem = parsedData.particleSystems[index];
  20082. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20083. }
  20084. }
  20085. // Lens flares
  20086. if (parsedData.lensFlareSystems) {
  20087. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20088. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20089. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20090. }
  20091. }
  20092. // Shadows
  20093. if (parsedData.shadowGenerators) {
  20094. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20095. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20096. parseShadowGenerator(parsedShadowGenerator, scene);
  20097. }
  20098. }
  20099. // Actions (scene)
  20100. if (parsedData.actions) {
  20101. parseActions(parsedData.actions, null, scene);
  20102. }
  20103. // Finish
  20104. return true;
  20105. }
  20106. });
  20107. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20108. })(BABYLON || (BABYLON = {}));
  20109. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  20110. var BABYLON;
  20111. (function (BABYLON) {
  20112. var SpriteManager = (function () {
  20113. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20115. this.name = name;
  20116. this.cellSize = cellSize;
  20117. this.sprites = new Array();
  20118. this.renderingGroupId = 0;
  20119. this.fogEnabled = true;
  20120. this._vertexDeclaration = [4, 4, 4, 4];
  20121. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20122. this._capacity = capacity;
  20123. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20124. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20125. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20126. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20127. this._scene = scene;
  20128. this._scene.spriteManagers.push(this);
  20129. // VBO
  20130. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20131. var indices = [];
  20132. var index = 0;
  20133. for (var count = 0; count < capacity; count++) {
  20134. indices.push(index);
  20135. indices.push(index + 1);
  20136. indices.push(index + 2);
  20137. indices.push(index);
  20138. indices.push(index + 2);
  20139. indices.push(index + 3);
  20140. index += 4;
  20141. }
  20142. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20143. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20144. // Effects
  20145. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20146. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20147. }
  20148. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20149. var arrayOffset = index * 16;
  20150. if (offsetX === 0)
  20151. offsetX = this._epsilon;
  20152. else if (offsetX === 1)
  20153. offsetX = 1 - this._epsilon;
  20154. if (offsetY === 0)
  20155. offsetY = this._epsilon;
  20156. else if (offsetY === 1)
  20157. offsetY = 1 - this._epsilon;
  20158. this._vertices[arrayOffset] = sprite.position.x;
  20159. this._vertices[arrayOffset + 1] = sprite.position.y;
  20160. this._vertices[arrayOffset + 2] = sprite.position.z;
  20161. this._vertices[arrayOffset + 3] = sprite.angle;
  20162. this._vertices[arrayOffset + 4] = sprite.width;
  20163. this._vertices[arrayOffset + 5] = sprite.height;
  20164. this._vertices[arrayOffset + 6] = offsetX;
  20165. this._vertices[arrayOffset + 7] = offsetY;
  20166. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20167. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20168. var offset = (sprite.cellIndex / rowSize) >> 0;
  20169. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20170. this._vertices[arrayOffset + 11] = offset;
  20171. // Color
  20172. this._vertices[arrayOffset + 12] = sprite.color.r;
  20173. this._vertices[arrayOffset + 13] = sprite.color.g;
  20174. this._vertices[arrayOffset + 14] = sprite.color.b;
  20175. this._vertices[arrayOffset + 15] = sprite.color.a;
  20176. };
  20177. SpriteManager.prototype.render = function () {
  20178. // Check
  20179. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20180. return;
  20181. var engine = this._scene.getEngine();
  20182. var baseSize = this._spriteTexture.getBaseSize();
  20183. // Sprites
  20184. var deltaTime = engine.getDeltaTime();
  20185. var max = Math.min(this._capacity, this.sprites.length);
  20186. var rowSize = baseSize.width / this.cellSize;
  20187. var offset = 0;
  20188. for (var index = 0; index < max; index++) {
  20189. var sprite = this.sprites[index];
  20190. if (!sprite) {
  20191. continue;
  20192. }
  20193. sprite._animate(deltaTime);
  20194. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20195. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20196. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20197. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20198. }
  20199. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20200. // Render
  20201. var effect = this._effectBase;
  20202. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20203. effect = this._effectFog;
  20204. }
  20205. engine.enableEffect(effect);
  20206. var viewMatrix = this._scene.getViewMatrix();
  20207. effect.setTexture("diffuseSampler", this._spriteTexture);
  20208. effect.setMatrix("view", viewMatrix);
  20209. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20210. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20211. // Fog
  20212. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20213. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20214. effect.setColor3("vFogColor", this._scene.fogColor);
  20215. }
  20216. // VBOs
  20217. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20218. // Draw order
  20219. engine.setDepthFunctionToLessOrEqual();
  20220. effect.setBool("alphaTest", true);
  20221. engine.setColorWrite(false);
  20222. engine.draw(true, 0, max * 6);
  20223. engine.setColorWrite(true);
  20224. effect.setBool("alphaTest", false);
  20225. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20226. engine.draw(true, 0, max * 6);
  20227. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20228. };
  20229. SpriteManager.prototype.dispose = function () {
  20230. if (this._vertexBuffer) {
  20231. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20232. this._vertexBuffer = null;
  20233. }
  20234. if (this._indexBuffer) {
  20235. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20236. this._indexBuffer = null;
  20237. }
  20238. if (this._spriteTexture) {
  20239. this._spriteTexture.dispose();
  20240. this._spriteTexture = null;
  20241. }
  20242. // Remove from scene
  20243. var index = this._scene.spriteManagers.indexOf(this);
  20244. this._scene.spriteManagers.splice(index, 1);
  20245. // Callback
  20246. if (this.onDispose) {
  20247. this.onDispose();
  20248. }
  20249. };
  20250. return SpriteManager;
  20251. })();
  20252. BABYLON.SpriteManager = SpriteManager;
  20253. })(BABYLON || (BABYLON = {}));
  20254. //# sourceMappingURL=babylon.spriteManager.js.map
  20255. var BABYLON;
  20256. (function (BABYLON) {
  20257. var Sprite = (function () {
  20258. function Sprite(name, manager) {
  20259. this.name = name;
  20260. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20261. this.width = 1.0;
  20262. this.height = 1.0;
  20263. this.angle = 0;
  20264. this.cellIndex = 0;
  20265. this.invertU = 0;
  20266. this.invertV = 0;
  20267. this.animations = new Array();
  20268. this._animationStarted = false;
  20269. this._loopAnimation = false;
  20270. this._fromIndex = 0;
  20271. this._toIndex = 0;
  20272. this._delay = 0;
  20273. this._direction = 1;
  20274. this._frameCount = 0;
  20275. this._time = 0;
  20276. this._manager = manager;
  20277. this._manager.sprites.push(this);
  20278. this.position = BABYLON.Vector3.Zero();
  20279. }
  20280. Object.defineProperty(Sprite.prototype, "size", {
  20281. get: function () {
  20282. return this.width;
  20283. },
  20284. set: function (value) {
  20285. this.width = value;
  20286. this.height = value;
  20287. },
  20288. enumerable: true,
  20289. configurable: true
  20290. });
  20291. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20292. this._fromIndex = from;
  20293. this._toIndex = to;
  20294. this._loopAnimation = loop;
  20295. this._delay = delay;
  20296. this._animationStarted = true;
  20297. this._direction = from < to ? 1 : -1;
  20298. this.cellIndex = from;
  20299. this._time = 0;
  20300. };
  20301. Sprite.prototype.stopAnimation = function () {
  20302. this._animationStarted = false;
  20303. };
  20304. Sprite.prototype._animate = function (deltaTime) {
  20305. if (!this._animationStarted)
  20306. return;
  20307. this._time += deltaTime;
  20308. if (this._time > this._delay) {
  20309. this._time = this._time % this._delay;
  20310. this.cellIndex += this._direction;
  20311. if (this.cellIndex == this._toIndex) {
  20312. if (this._loopAnimation) {
  20313. this.cellIndex = this._fromIndex;
  20314. }
  20315. else {
  20316. this._animationStarted = false;
  20317. if (this.disposeWhenFinishedAnimating) {
  20318. this.dispose();
  20319. }
  20320. }
  20321. }
  20322. }
  20323. };
  20324. Sprite.prototype.dispose = function () {
  20325. for (var i = 0; i < this._manager.sprites.length; i++) {
  20326. if (this._manager.sprites[i] == this) {
  20327. this._manager.sprites.splice(i, 1);
  20328. }
  20329. }
  20330. };
  20331. return Sprite;
  20332. })();
  20333. BABYLON.Sprite = Sprite;
  20334. })(BABYLON || (BABYLON = {}));
  20335. //# sourceMappingURL=babylon.sprite.js.map
  20336. var BABYLON;
  20337. (function (BABYLON) {
  20338. var Layer = (function () {
  20339. function Layer(name, imgUrl, scene, isBackground, color) {
  20340. this.name = name;
  20341. this._vertexDeclaration = [2];
  20342. this._vertexStrideSize = 2 * 4;
  20343. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20344. this.isBackground = isBackground === undefined ? true : isBackground;
  20345. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20346. this._scene = scene;
  20347. this._scene.layers.push(this);
  20348. // VBO
  20349. var vertices = [];
  20350. vertices.push(1, 1);
  20351. vertices.push(-1, 1);
  20352. vertices.push(-1, -1);
  20353. vertices.push(1, -1);
  20354. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20355. // Indices
  20356. var indices = [];
  20357. indices.push(0);
  20358. indices.push(1);
  20359. indices.push(2);
  20360. indices.push(0);
  20361. indices.push(2);
  20362. indices.push(3);
  20363. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20364. // Effects
  20365. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20366. }
  20367. Layer.prototype.render = function () {
  20368. // Check
  20369. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20370. return;
  20371. var engine = this._scene.getEngine();
  20372. // Render
  20373. engine.enableEffect(this._effect);
  20374. engine.setState(false);
  20375. // Texture
  20376. this._effect.setTexture("textureSampler", this.texture);
  20377. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20378. // Color
  20379. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20380. // VBOs
  20381. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20382. // Draw order
  20383. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20384. engine.draw(true, 0, 6);
  20385. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20386. };
  20387. Layer.prototype.dispose = function () {
  20388. if (this._vertexBuffer) {
  20389. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20390. this._vertexBuffer = null;
  20391. }
  20392. if (this._indexBuffer) {
  20393. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20394. this._indexBuffer = null;
  20395. }
  20396. if (this.texture) {
  20397. this.texture.dispose();
  20398. this.texture = null;
  20399. }
  20400. // Remove from scene
  20401. var index = this._scene.layers.indexOf(this);
  20402. this._scene.layers.splice(index, 1);
  20403. // Callback
  20404. if (this.onDispose) {
  20405. this.onDispose();
  20406. }
  20407. };
  20408. return Layer;
  20409. })();
  20410. BABYLON.Layer = Layer;
  20411. })(BABYLON || (BABYLON = {}));
  20412. //# sourceMappingURL=babylon.layer.js.map
  20413. var BABYLON;
  20414. (function (BABYLON) {
  20415. var Particle = (function () {
  20416. function Particle() {
  20417. this.position = BABYLON.Vector3.Zero();
  20418. this.direction = BABYLON.Vector3.Zero();
  20419. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20420. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20421. this.lifeTime = 1.0;
  20422. this.age = 0;
  20423. this.size = 0;
  20424. this.angle = 0;
  20425. this.angularSpeed = 0;
  20426. }
  20427. Particle.prototype.copyTo = function (other) {
  20428. other.position.copyFrom(this.position);
  20429. other.direction.copyFrom(this.direction);
  20430. other.color.copyFrom(this.color);
  20431. other.colorStep.copyFrom(this.colorStep);
  20432. other.lifeTime = this.lifeTime;
  20433. other.age = this.age;
  20434. other.size = this.size;
  20435. other.angle = this.angle;
  20436. other.angularSpeed = this.angularSpeed;
  20437. };
  20438. return Particle;
  20439. })();
  20440. BABYLON.Particle = Particle;
  20441. })(BABYLON || (BABYLON = {}));
  20442. //# sourceMappingURL=babylon.particle.js.map
  20443. var BABYLON;
  20444. (function (BABYLON) {
  20445. var randomNumber = function (min, max) {
  20446. if (min === max) {
  20447. return (min);
  20448. }
  20449. var random = Math.random();
  20450. return ((random * (max - min)) + min);
  20451. };
  20452. var ParticleSystem = (function () {
  20453. function ParticleSystem(name, capacity, scene, customEffect) {
  20454. var _this = this;
  20455. this.name = name;
  20456. this.renderingGroupId = 0;
  20457. this.emitter = null;
  20458. this.emitRate = 10;
  20459. this.manualEmitCount = -1;
  20460. this.updateSpeed = 0.01;
  20461. this.targetStopDuration = 0;
  20462. this.disposeOnStop = false;
  20463. this.minEmitPower = 1;
  20464. this.maxEmitPower = 1;
  20465. this.minLifeTime = 1;
  20466. this.maxLifeTime = 1;
  20467. this.minSize = 1;
  20468. this.maxSize = 1;
  20469. this.minAngularSpeed = 0;
  20470. this.maxAngularSpeed = 0;
  20471. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20472. this.forceDepthWrite = false;
  20473. this.gravity = BABYLON.Vector3.Zero();
  20474. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20475. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20476. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20477. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20478. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20479. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20480. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20481. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20482. this.particles = new Array();
  20483. this._vertexDeclaration = [3, 4, 4];
  20484. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20485. this._stockParticles = new Array();
  20486. this._newPartsExcess = 0;
  20487. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20488. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20489. this._scaledDirection = BABYLON.Vector3.Zero();
  20490. this._scaledGravity = BABYLON.Vector3.Zero();
  20491. this._currentRenderId = -1;
  20492. this._started = false;
  20493. this._stopped = false;
  20494. this._actualFrame = 0;
  20495. this.id = name;
  20496. this._capacity = capacity;
  20497. this._scene = scene;
  20498. this._customEffect = customEffect;
  20499. scene.particleSystems.push(this);
  20500. // VBO
  20501. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20502. var indices = [];
  20503. var index = 0;
  20504. for (var count = 0; count < capacity; count++) {
  20505. indices.push(index);
  20506. indices.push(index + 1);
  20507. indices.push(index + 2);
  20508. indices.push(index);
  20509. indices.push(index + 2);
  20510. indices.push(index + 3);
  20511. index += 4;
  20512. }
  20513. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20514. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20515. // Default behaviors
  20516. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20517. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20518. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20519. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20520. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20521. };
  20522. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20523. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20524. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20525. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20526. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20527. };
  20528. this.updateFunction = function (particles) {
  20529. for (var index = 0; index < particles.length; index++) {
  20530. var particle = particles[index];
  20531. particle.age += _this._scaledUpdateSpeed;
  20532. if (particle.age >= particle.lifeTime) {
  20533. _this.recycleParticle(particle);
  20534. index--;
  20535. continue;
  20536. }
  20537. else {
  20538. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20539. particle.color.addInPlace(_this._scaledColorStep);
  20540. if (particle.color.a < 0)
  20541. particle.color.a = 0;
  20542. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20543. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20544. particle.position.addInPlace(_this._scaledDirection);
  20545. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20546. particle.direction.addInPlace(_this._scaledGravity);
  20547. }
  20548. }
  20549. };
  20550. }
  20551. ParticleSystem.prototype.recycleParticle = function (particle) {
  20552. var lastParticle = this.particles.pop();
  20553. if (lastParticle !== particle) {
  20554. lastParticle.copyTo(particle);
  20555. this._stockParticles.push(lastParticle);
  20556. }
  20557. };
  20558. ParticleSystem.prototype.getCapacity = function () {
  20559. return this._capacity;
  20560. };
  20561. ParticleSystem.prototype.isAlive = function () {
  20562. return this._alive;
  20563. };
  20564. ParticleSystem.prototype.isStarted = function () {
  20565. return this._started;
  20566. };
  20567. ParticleSystem.prototype.start = function () {
  20568. this._started = true;
  20569. this._stopped = false;
  20570. this._actualFrame = 0;
  20571. };
  20572. ParticleSystem.prototype.stop = function () {
  20573. this._stopped = true;
  20574. };
  20575. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20576. var offset = index * 11;
  20577. this._vertices[offset] = particle.position.x;
  20578. this._vertices[offset + 1] = particle.position.y;
  20579. this._vertices[offset + 2] = particle.position.z;
  20580. this._vertices[offset + 3] = particle.color.r;
  20581. this._vertices[offset + 4] = particle.color.g;
  20582. this._vertices[offset + 5] = particle.color.b;
  20583. this._vertices[offset + 6] = particle.color.a;
  20584. this._vertices[offset + 7] = particle.angle;
  20585. this._vertices[offset + 8] = particle.size;
  20586. this._vertices[offset + 9] = offsetX;
  20587. this._vertices[offset + 10] = offsetY;
  20588. };
  20589. ParticleSystem.prototype._update = function (newParticles) {
  20590. // Update current
  20591. this._alive = this.particles.length > 0;
  20592. this.updateFunction(this.particles);
  20593. // Add new ones
  20594. var worldMatrix;
  20595. if (this.emitter.position) {
  20596. worldMatrix = this.emitter.getWorldMatrix();
  20597. }
  20598. else {
  20599. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20600. }
  20601. for (var index = 0; index < newParticles; index++) {
  20602. if (this.particles.length === this._capacity) {
  20603. break;
  20604. }
  20605. if (this._stockParticles.length !== 0) {
  20606. var particle = this._stockParticles.pop();
  20607. particle.age = 0;
  20608. }
  20609. else {
  20610. particle = new BABYLON.Particle();
  20611. }
  20612. this.particles.push(particle);
  20613. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20614. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20615. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20616. particle.size = randomNumber(this.minSize, this.maxSize);
  20617. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20618. this.startPositionFunction(worldMatrix, particle.position);
  20619. var step = randomNumber(0, 1.0);
  20620. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20621. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20622. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20623. }
  20624. };
  20625. ParticleSystem.prototype._getEffect = function () {
  20626. if (this._customEffect) {
  20627. return this._customEffect;
  20628. }
  20629. ;
  20630. var defines = [];
  20631. if (this._scene.clipPlane) {
  20632. defines.push("#define CLIPPLANE");
  20633. }
  20634. // Effect
  20635. var join = defines.join("\n");
  20636. if (this._cachedDefines !== join) {
  20637. this._cachedDefines = join;
  20638. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20639. }
  20640. return this._effect;
  20641. };
  20642. ParticleSystem.prototype.animate = function () {
  20643. if (!this._started)
  20644. return;
  20645. var effect = this._getEffect();
  20646. // Check
  20647. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20648. return;
  20649. if (this._currentRenderId === this._scene.getRenderId()) {
  20650. return;
  20651. }
  20652. this._currentRenderId = this._scene.getRenderId();
  20653. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20654. // determine the number of particles we need to create
  20655. var emitCout;
  20656. if (this.manualEmitCount > -1) {
  20657. emitCout = this.manualEmitCount;
  20658. this.manualEmitCount = 0;
  20659. }
  20660. else {
  20661. emitCout = this.emitRate;
  20662. }
  20663. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20664. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20665. if (this._newPartsExcess > 1.0) {
  20666. newParticles += this._newPartsExcess >> 0;
  20667. this._newPartsExcess -= this._newPartsExcess >> 0;
  20668. }
  20669. this._alive = false;
  20670. if (!this._stopped) {
  20671. this._actualFrame += this._scaledUpdateSpeed;
  20672. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20673. this.stop();
  20674. }
  20675. else {
  20676. newParticles = 0;
  20677. }
  20678. this._update(newParticles);
  20679. // Stopped?
  20680. if (this._stopped) {
  20681. if (!this._alive) {
  20682. this._started = false;
  20683. if (this.disposeOnStop) {
  20684. this._scene._toBeDisposed.push(this);
  20685. }
  20686. }
  20687. }
  20688. // Update VBO
  20689. var offset = 0;
  20690. for (var index = 0; index < this.particles.length; index++) {
  20691. var particle = this.particles[index];
  20692. this._appendParticleVertex(offset++, particle, 0, 0);
  20693. this._appendParticleVertex(offset++, particle, 1, 0);
  20694. this._appendParticleVertex(offset++, particle, 1, 1);
  20695. this._appendParticleVertex(offset++, particle, 0, 1);
  20696. }
  20697. var engine = this._scene.getEngine();
  20698. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20699. };
  20700. ParticleSystem.prototype.render = function () {
  20701. var effect = this._getEffect();
  20702. // Check
  20703. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20704. return 0;
  20705. var engine = this._scene.getEngine();
  20706. // Render
  20707. engine.enableEffect(effect);
  20708. engine.setState(false);
  20709. var viewMatrix = this._scene.getViewMatrix();
  20710. effect.setTexture("diffuseSampler", this.particleTexture);
  20711. effect.setMatrix("view", viewMatrix);
  20712. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20713. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20714. if (this._scene.clipPlane) {
  20715. var clipPlane = this._scene.clipPlane;
  20716. var invView = viewMatrix.clone();
  20717. invView.invert();
  20718. effect.setMatrix("invView", invView);
  20719. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20720. }
  20721. // VBOs
  20722. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20723. // Draw order
  20724. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20725. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20726. }
  20727. else {
  20728. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20729. }
  20730. if (this.forceDepthWrite) {
  20731. engine.setDepthWrite(true);
  20732. }
  20733. engine.draw(true, 0, this.particles.length * 6);
  20734. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20735. return this.particles.length;
  20736. };
  20737. ParticleSystem.prototype.dispose = function () {
  20738. if (this._vertexBuffer) {
  20739. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20740. this._vertexBuffer = null;
  20741. }
  20742. if (this._indexBuffer) {
  20743. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20744. this._indexBuffer = null;
  20745. }
  20746. if (this.particleTexture) {
  20747. this.particleTexture.dispose();
  20748. this.particleTexture = null;
  20749. }
  20750. // Remove from scene
  20751. var index = this._scene.particleSystems.indexOf(this);
  20752. this._scene.particleSystems.splice(index, 1);
  20753. // Callback
  20754. if (this.onDispose) {
  20755. this.onDispose();
  20756. }
  20757. };
  20758. // Clone
  20759. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20760. var result = new ParticleSystem(name, this._capacity, this._scene);
  20761. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20762. if (newEmitter === undefined) {
  20763. newEmitter = this.emitter;
  20764. }
  20765. result.emitter = newEmitter;
  20766. if (this.particleTexture) {
  20767. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20768. }
  20769. result.start();
  20770. return result;
  20771. };
  20772. // Statics
  20773. ParticleSystem.BLENDMODE_ONEONE = 0;
  20774. ParticleSystem.BLENDMODE_STANDARD = 1;
  20775. return ParticleSystem;
  20776. })();
  20777. BABYLON.ParticleSystem = ParticleSystem;
  20778. })(BABYLON || (BABYLON = {}));
  20779. //# sourceMappingURL=babylon.particleSystem.js.map
  20780. var BABYLON;
  20781. (function (BABYLON) {
  20782. var Animation = (function () {
  20783. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20784. this.name = name;
  20785. this.targetProperty = targetProperty;
  20786. this.framePerSecond = framePerSecond;
  20787. this.dataType = dataType;
  20788. this.loopMode = loopMode;
  20789. this._offsetsCache = {};
  20790. this._highLimitsCache = {};
  20791. this._stopped = false;
  20792. this.targetPropertyPath = targetProperty.split(".");
  20793. this.dataType = dataType;
  20794. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20795. }
  20796. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20797. var dataType = undefined;
  20798. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20799. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20800. }
  20801. else if (from instanceof BABYLON.Quaternion) {
  20802. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20803. }
  20804. else if (from instanceof BABYLON.Vector3) {
  20805. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20806. }
  20807. else if (from instanceof BABYLON.Vector2) {
  20808. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20809. }
  20810. else if (from instanceof BABYLON.Color3) {
  20811. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20812. }
  20813. if (dataType == undefined) {
  20814. return null;
  20815. }
  20816. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20817. var keys = [];
  20818. keys.push({ frame: 0, value: from });
  20819. keys.push({ frame: totalFrame, value: to });
  20820. animation.setKeys(keys);
  20821. mesh.animations.push(animation);
  20822. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20823. };
  20824. // Methods
  20825. Animation.prototype.isStopped = function () {
  20826. return this._stopped;
  20827. };
  20828. Animation.prototype.getKeys = function () {
  20829. return this._keys;
  20830. };
  20831. Animation.prototype.getEasingFunction = function () {
  20832. return this._easingFunction;
  20833. };
  20834. Animation.prototype.setEasingFunction = function (easingFunction) {
  20835. this._easingFunction = easingFunction;
  20836. };
  20837. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20838. return startValue + (endValue - startValue) * gradient;
  20839. };
  20840. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20841. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20842. };
  20843. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20844. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20845. };
  20846. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20847. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20848. };
  20849. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20850. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20851. };
  20852. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20853. var startScale = new BABYLON.Vector3(0, 0, 0);
  20854. var startRotation = new BABYLON.Quaternion();
  20855. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20856. startValue.decompose(startScale, startRotation, startTranslation);
  20857. var endScale = new BABYLON.Vector3(0, 0, 0);
  20858. var endRotation = new BABYLON.Quaternion();
  20859. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20860. endValue.decompose(endScale, endRotation, endTranslation);
  20861. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20862. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20863. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20864. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20865. return result;
  20866. };
  20867. Animation.prototype.clone = function () {
  20868. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20869. clone.setKeys(this._keys);
  20870. return clone;
  20871. };
  20872. Animation.prototype.setKeys = function (values) {
  20873. this._keys = values.slice(0);
  20874. this._offsetsCache = {};
  20875. this._highLimitsCache = {};
  20876. };
  20877. Animation.prototype._getKeyValue = function (value) {
  20878. if (typeof value === "function") {
  20879. return value();
  20880. }
  20881. return value;
  20882. };
  20883. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20884. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20885. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20886. }
  20887. this.currentFrame = currentFrame;
  20888. // Try to get a hash to find the right key
  20889. 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));
  20890. if (this._keys[startKey].frame >= currentFrame) {
  20891. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20892. startKey--;
  20893. }
  20894. }
  20895. for (var key = startKey; key < this._keys.length; key++) {
  20896. if (this._keys[key + 1].frame >= currentFrame) {
  20897. var startValue = this._getKeyValue(this._keys[key].value);
  20898. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20899. // gradient : percent of currentFrame between the frame inf and the frame sup
  20900. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20901. // check for easingFunction and correction of gradient
  20902. if (this._easingFunction != null) {
  20903. gradient = this._easingFunction.ease(gradient);
  20904. }
  20905. switch (this.dataType) {
  20906. // Float
  20907. case Animation.ANIMATIONTYPE_FLOAT:
  20908. switch (loopMode) {
  20909. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20910. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20911. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20912. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20913. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20914. }
  20915. break;
  20916. // Quaternion
  20917. case Animation.ANIMATIONTYPE_QUATERNION:
  20918. var quaternion = null;
  20919. switch (loopMode) {
  20920. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20921. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20922. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20923. break;
  20924. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20925. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20926. break;
  20927. }
  20928. return quaternion;
  20929. // Vector3
  20930. case Animation.ANIMATIONTYPE_VECTOR3:
  20931. switch (loopMode) {
  20932. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20933. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20934. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20935. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20936. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20937. }
  20938. // Vector2
  20939. case Animation.ANIMATIONTYPE_VECTOR2:
  20940. switch (loopMode) {
  20941. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20942. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20943. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20944. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20945. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20946. }
  20947. // Color3
  20948. case Animation.ANIMATIONTYPE_COLOR3:
  20949. switch (loopMode) {
  20950. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20951. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20952. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20953. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20954. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20955. }
  20956. // Matrix
  20957. case Animation.ANIMATIONTYPE_MATRIX:
  20958. switch (loopMode) {
  20959. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20960. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20961. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  20962. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20963. return startValue;
  20964. }
  20965. default:
  20966. break;
  20967. }
  20968. break;
  20969. }
  20970. }
  20971. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20972. };
  20973. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20974. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20975. this._stopped = true;
  20976. return false;
  20977. }
  20978. var returnValue = true;
  20979. // Adding a start key at frame 0 if missing
  20980. if (this._keys[0].frame !== 0) {
  20981. var newKey = { frame: 0, value: this._keys[0].value };
  20982. this._keys.splice(0, 0, newKey);
  20983. }
  20984. // Check limits
  20985. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20986. from = this._keys[0].frame;
  20987. }
  20988. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20989. to = this._keys[this._keys.length - 1].frame;
  20990. }
  20991. // Compute ratio
  20992. var range = to - from;
  20993. var offsetValue;
  20994. // ratio represents the frame delta between from and to
  20995. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20996. var highLimitValue = 0;
  20997. if (ratio > range && !loop) {
  20998. returnValue = false;
  20999. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21000. }
  21001. else {
  21002. // Get max value if required
  21003. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21004. var keyOffset = to.toString() + from.toString();
  21005. if (!this._offsetsCache[keyOffset]) {
  21006. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21007. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21008. switch (this.dataType) {
  21009. // Float
  21010. case Animation.ANIMATIONTYPE_FLOAT:
  21011. this._offsetsCache[keyOffset] = toValue - fromValue;
  21012. break;
  21013. // Quaternion
  21014. case Animation.ANIMATIONTYPE_QUATERNION:
  21015. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21016. break;
  21017. // Vector3
  21018. case Animation.ANIMATIONTYPE_VECTOR3:
  21019. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21020. // Vector2
  21021. case Animation.ANIMATIONTYPE_VECTOR2:
  21022. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21023. // Color3
  21024. case Animation.ANIMATIONTYPE_COLOR3:
  21025. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21026. default:
  21027. break;
  21028. }
  21029. this._highLimitsCache[keyOffset] = toValue;
  21030. }
  21031. highLimitValue = this._highLimitsCache[keyOffset];
  21032. offsetValue = this._offsetsCache[keyOffset];
  21033. }
  21034. }
  21035. if (offsetValue === undefined) {
  21036. switch (this.dataType) {
  21037. // Float
  21038. case Animation.ANIMATIONTYPE_FLOAT:
  21039. offsetValue = 0;
  21040. break;
  21041. // Quaternion
  21042. case Animation.ANIMATIONTYPE_QUATERNION:
  21043. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21044. break;
  21045. // Vector3
  21046. case Animation.ANIMATIONTYPE_VECTOR3:
  21047. offsetValue = BABYLON.Vector3.Zero();
  21048. break;
  21049. // Vector2
  21050. case Animation.ANIMATIONTYPE_VECTOR2:
  21051. offsetValue = BABYLON.Vector2.Zero();
  21052. break;
  21053. // Color3
  21054. case Animation.ANIMATIONTYPE_COLOR3:
  21055. offsetValue = BABYLON.Color3.Black();
  21056. }
  21057. }
  21058. // Compute value
  21059. var repeatCount = (ratio / range) >> 0;
  21060. var currentFrame = returnValue ? from + ratio % range : to;
  21061. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21062. // Set value
  21063. if (this.targetPropertyPath.length > 1) {
  21064. var property = this._target[this.targetPropertyPath[0]];
  21065. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21066. property = property[this.targetPropertyPath[index]];
  21067. }
  21068. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21069. }
  21070. else {
  21071. this._target[this.targetPropertyPath[0]] = currentValue;
  21072. }
  21073. if (this._target.markAsDirty) {
  21074. this._target.markAsDirty(this.targetProperty);
  21075. }
  21076. if (!returnValue) {
  21077. this._stopped = true;
  21078. }
  21079. return returnValue;
  21080. };
  21081. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21082. get: function () {
  21083. return Animation._ANIMATIONTYPE_FLOAT;
  21084. },
  21085. enumerable: true,
  21086. configurable: true
  21087. });
  21088. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21089. get: function () {
  21090. return Animation._ANIMATIONTYPE_VECTOR3;
  21091. },
  21092. enumerable: true,
  21093. configurable: true
  21094. });
  21095. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21096. get: function () {
  21097. return Animation._ANIMATIONTYPE_VECTOR2;
  21098. },
  21099. enumerable: true,
  21100. configurable: true
  21101. });
  21102. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21103. get: function () {
  21104. return Animation._ANIMATIONTYPE_QUATERNION;
  21105. },
  21106. enumerable: true,
  21107. configurable: true
  21108. });
  21109. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21110. get: function () {
  21111. return Animation._ANIMATIONTYPE_MATRIX;
  21112. },
  21113. enumerable: true,
  21114. configurable: true
  21115. });
  21116. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21117. get: function () {
  21118. return Animation._ANIMATIONTYPE_COLOR3;
  21119. },
  21120. enumerable: true,
  21121. configurable: true
  21122. });
  21123. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21124. get: function () {
  21125. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21126. },
  21127. enumerable: true,
  21128. configurable: true
  21129. });
  21130. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21131. get: function () {
  21132. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21133. },
  21134. enumerable: true,
  21135. configurable: true
  21136. });
  21137. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21138. get: function () {
  21139. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21140. },
  21141. enumerable: true,
  21142. configurable: true
  21143. });
  21144. // Statics
  21145. Animation._ANIMATIONTYPE_FLOAT = 0;
  21146. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21147. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21148. Animation._ANIMATIONTYPE_MATRIX = 3;
  21149. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21150. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21151. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21152. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21153. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21154. return Animation;
  21155. })();
  21156. BABYLON.Animation = Animation;
  21157. })(BABYLON || (BABYLON = {}));
  21158. //# sourceMappingURL=babylon.animation.js.map
  21159. var BABYLON;
  21160. (function (BABYLON) {
  21161. var Animatable = (function () {
  21162. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21163. if (fromFrame === void 0) { fromFrame = 0; }
  21164. if (toFrame === void 0) { toFrame = 100; }
  21165. if (loopAnimation === void 0) { loopAnimation = false; }
  21166. if (speedRatio === void 0) { speedRatio = 1.0; }
  21167. this.target = target;
  21168. this.fromFrame = fromFrame;
  21169. this.toFrame = toFrame;
  21170. this.loopAnimation = loopAnimation;
  21171. this.speedRatio = speedRatio;
  21172. this.onAnimationEnd = onAnimationEnd;
  21173. this._animations = new Array();
  21174. this._paused = false;
  21175. this.animationStarted = false;
  21176. if (animations) {
  21177. this.appendAnimations(target, animations);
  21178. }
  21179. this._scene = scene;
  21180. scene._activeAnimatables.push(this);
  21181. }
  21182. // Methods
  21183. Animatable.prototype.appendAnimations = function (target, animations) {
  21184. for (var index = 0; index < animations.length; index++) {
  21185. var animation = animations[index];
  21186. animation._target = target;
  21187. this._animations.push(animation);
  21188. }
  21189. };
  21190. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21191. var animations = this._animations;
  21192. for (var index = 0; index < animations.length; index++) {
  21193. if (animations[index].targetProperty === property) {
  21194. return animations[index];
  21195. }
  21196. }
  21197. return null;
  21198. };
  21199. Animatable.prototype.pause = function () {
  21200. if (this._paused) {
  21201. return;
  21202. }
  21203. this._paused = true;
  21204. };
  21205. Animatable.prototype.restart = function () {
  21206. this._paused = false;
  21207. };
  21208. Animatable.prototype.stop = function () {
  21209. var index = this._scene._activeAnimatables.indexOf(this);
  21210. if (index > -1) {
  21211. this._scene._activeAnimatables.splice(index, 1);
  21212. }
  21213. if (this.onAnimationEnd) {
  21214. this.onAnimationEnd();
  21215. }
  21216. };
  21217. Animatable.prototype._animate = function (delay) {
  21218. if (this._paused) {
  21219. if (!this._pausedDelay) {
  21220. this._pausedDelay = delay;
  21221. }
  21222. return true;
  21223. }
  21224. if (!this._localDelayOffset) {
  21225. this._localDelayOffset = delay;
  21226. }
  21227. else if (this._pausedDelay) {
  21228. this._localDelayOffset += delay - this._pausedDelay;
  21229. this._pausedDelay = null;
  21230. }
  21231. // Animating
  21232. var running = false;
  21233. var animations = this._animations;
  21234. for (var index = 0; index < animations.length; index++) {
  21235. var animation = animations[index];
  21236. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21237. running = running || isRunning;
  21238. }
  21239. if (!running) {
  21240. // Remove from active animatables
  21241. index = this._scene._activeAnimatables.indexOf(this);
  21242. this._scene._activeAnimatables.splice(index, 1);
  21243. }
  21244. if (!running && this.onAnimationEnd) {
  21245. this.onAnimationEnd();
  21246. }
  21247. return running;
  21248. };
  21249. return Animatable;
  21250. })();
  21251. BABYLON.Animatable = Animatable;
  21252. })(BABYLON || (BABYLON = {}));
  21253. //# sourceMappingURL=babylon.animatable.js.map
  21254. var __extends = this.__extends || function (d, b) {
  21255. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21256. function __() { this.constructor = d; }
  21257. __.prototype = b.prototype;
  21258. d.prototype = new __();
  21259. };
  21260. var BABYLON;
  21261. (function (BABYLON) {
  21262. var EasingFunction = (function () {
  21263. function EasingFunction() {
  21264. // Properties
  21265. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21266. }
  21267. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21268. get: function () {
  21269. return EasingFunction._EASINGMODE_EASEIN;
  21270. },
  21271. enumerable: true,
  21272. configurable: true
  21273. });
  21274. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21275. get: function () {
  21276. return EasingFunction._EASINGMODE_EASEOUT;
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21282. get: function () {
  21283. return EasingFunction._EASINGMODE_EASEINOUT;
  21284. },
  21285. enumerable: true,
  21286. configurable: true
  21287. });
  21288. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21289. var n = Math.min(Math.max(easingMode, 0), 2);
  21290. this._easingMode = n;
  21291. };
  21292. EasingFunction.prototype.getEasingMode = function () {
  21293. return this._easingMode;
  21294. };
  21295. EasingFunction.prototype.easeInCore = function (gradient) {
  21296. throw new Error('You must implement this method');
  21297. };
  21298. EasingFunction.prototype.ease = function (gradient) {
  21299. switch (this._easingMode) {
  21300. case EasingFunction.EASINGMODE_EASEIN:
  21301. return this.easeInCore(gradient);
  21302. case EasingFunction.EASINGMODE_EASEOUT:
  21303. return (1 - this.easeInCore(1 - gradient));
  21304. }
  21305. if (gradient >= 0.5) {
  21306. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21307. }
  21308. return (this.easeInCore(gradient * 2) * 0.5);
  21309. };
  21310. //Statics
  21311. EasingFunction._EASINGMODE_EASEIN = 0;
  21312. EasingFunction._EASINGMODE_EASEOUT = 1;
  21313. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21314. return EasingFunction;
  21315. })();
  21316. BABYLON.EasingFunction = EasingFunction;
  21317. var CircleEase = (function (_super) {
  21318. __extends(CircleEase, _super);
  21319. function CircleEase() {
  21320. _super.apply(this, arguments);
  21321. }
  21322. CircleEase.prototype.easeInCore = function (gradient) {
  21323. gradient = Math.max(0, Math.min(1, gradient));
  21324. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21325. };
  21326. return CircleEase;
  21327. })(EasingFunction);
  21328. BABYLON.CircleEase = CircleEase;
  21329. var BackEase = (function (_super) {
  21330. __extends(BackEase, _super);
  21331. function BackEase(amplitude) {
  21332. if (amplitude === void 0) { amplitude = 1; }
  21333. _super.call(this);
  21334. this.amplitude = amplitude;
  21335. }
  21336. BackEase.prototype.easeInCore = function (gradient) {
  21337. var num = Math.max(0, this.amplitude);
  21338. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21339. };
  21340. return BackEase;
  21341. })(EasingFunction);
  21342. BABYLON.BackEase = BackEase;
  21343. var BounceEase = (function (_super) {
  21344. __extends(BounceEase, _super);
  21345. function BounceEase(bounces, bounciness) {
  21346. if (bounces === void 0) { bounces = 3; }
  21347. if (bounciness === void 0) { bounciness = 2; }
  21348. _super.call(this);
  21349. this.bounces = bounces;
  21350. this.bounciness = bounciness;
  21351. }
  21352. BounceEase.prototype.easeInCore = function (gradient) {
  21353. var y = Math.max(0.0, this.bounces);
  21354. var bounciness = this.bounciness;
  21355. if (bounciness <= 1.0) {
  21356. bounciness = 1.001;
  21357. }
  21358. var num9 = Math.pow(bounciness, y);
  21359. var num5 = 1.0 - bounciness;
  21360. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21361. var num15 = gradient * num4;
  21362. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21363. var num3 = Math.floor(num65);
  21364. var num13 = num3 + 1.0;
  21365. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21366. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21367. var num7 = (num8 + num12) * 0.5;
  21368. var num6 = gradient - num7;
  21369. var num2 = num7 - num8;
  21370. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21371. };
  21372. return BounceEase;
  21373. })(EasingFunction);
  21374. BABYLON.BounceEase = BounceEase;
  21375. var CubicEase = (function (_super) {
  21376. __extends(CubicEase, _super);
  21377. function CubicEase() {
  21378. _super.apply(this, arguments);
  21379. }
  21380. CubicEase.prototype.easeInCore = function (gradient) {
  21381. return (gradient * gradient * gradient);
  21382. };
  21383. return CubicEase;
  21384. })(EasingFunction);
  21385. BABYLON.CubicEase = CubicEase;
  21386. var ElasticEase = (function (_super) {
  21387. __extends(ElasticEase, _super);
  21388. function ElasticEase(oscillations, springiness) {
  21389. if (oscillations === void 0) { oscillations = 3; }
  21390. if (springiness === void 0) { springiness = 3; }
  21391. _super.call(this);
  21392. this.oscillations = oscillations;
  21393. this.springiness = springiness;
  21394. }
  21395. ElasticEase.prototype.easeInCore = function (gradient) {
  21396. var num2;
  21397. var num3 = Math.max(0.0, this.oscillations);
  21398. var num = Math.max(0.0, this.springiness);
  21399. if (num == 0) {
  21400. num2 = gradient;
  21401. }
  21402. else {
  21403. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21404. }
  21405. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21406. };
  21407. return ElasticEase;
  21408. })(EasingFunction);
  21409. BABYLON.ElasticEase = ElasticEase;
  21410. var ExponentialEase = (function (_super) {
  21411. __extends(ExponentialEase, _super);
  21412. function ExponentialEase(exponent) {
  21413. if (exponent === void 0) { exponent = 2; }
  21414. _super.call(this);
  21415. this.exponent = exponent;
  21416. }
  21417. ExponentialEase.prototype.easeInCore = function (gradient) {
  21418. if (this.exponent <= 0) {
  21419. return gradient;
  21420. }
  21421. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21422. };
  21423. return ExponentialEase;
  21424. })(EasingFunction);
  21425. BABYLON.ExponentialEase = ExponentialEase;
  21426. var PowerEase = (function (_super) {
  21427. __extends(PowerEase, _super);
  21428. function PowerEase(power) {
  21429. if (power === void 0) { power = 2; }
  21430. _super.call(this);
  21431. this.power = power;
  21432. }
  21433. PowerEase.prototype.easeInCore = function (gradient) {
  21434. var y = Math.max(0.0, this.power);
  21435. return Math.pow(gradient, y);
  21436. };
  21437. return PowerEase;
  21438. })(EasingFunction);
  21439. BABYLON.PowerEase = PowerEase;
  21440. var QuadraticEase = (function (_super) {
  21441. __extends(QuadraticEase, _super);
  21442. function QuadraticEase() {
  21443. _super.apply(this, arguments);
  21444. }
  21445. QuadraticEase.prototype.easeInCore = function (gradient) {
  21446. return (gradient * gradient);
  21447. };
  21448. return QuadraticEase;
  21449. })(EasingFunction);
  21450. BABYLON.QuadraticEase = QuadraticEase;
  21451. var QuarticEase = (function (_super) {
  21452. __extends(QuarticEase, _super);
  21453. function QuarticEase() {
  21454. _super.apply(this, arguments);
  21455. }
  21456. QuarticEase.prototype.easeInCore = function (gradient) {
  21457. return (gradient * gradient * gradient * gradient);
  21458. };
  21459. return QuarticEase;
  21460. })(EasingFunction);
  21461. BABYLON.QuarticEase = QuarticEase;
  21462. var QuinticEase = (function (_super) {
  21463. __extends(QuinticEase, _super);
  21464. function QuinticEase() {
  21465. _super.apply(this, arguments);
  21466. }
  21467. QuinticEase.prototype.easeInCore = function (gradient) {
  21468. return (gradient * gradient * gradient * gradient * gradient);
  21469. };
  21470. return QuinticEase;
  21471. })(EasingFunction);
  21472. BABYLON.QuinticEase = QuinticEase;
  21473. var SineEase = (function (_super) {
  21474. __extends(SineEase, _super);
  21475. function SineEase() {
  21476. _super.apply(this, arguments);
  21477. }
  21478. SineEase.prototype.easeInCore = function (gradient) {
  21479. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21480. };
  21481. return SineEase;
  21482. })(EasingFunction);
  21483. BABYLON.SineEase = SineEase;
  21484. var BezierCurveEase = (function (_super) {
  21485. __extends(BezierCurveEase, _super);
  21486. function BezierCurveEase(x1, y1, x2, y2) {
  21487. if (x1 === void 0) { x1 = 0; }
  21488. if (y1 === void 0) { y1 = 0; }
  21489. if (x2 === void 0) { x2 = 1; }
  21490. if (y2 === void 0) { y2 = 1; }
  21491. _super.call(this);
  21492. this.x1 = x1;
  21493. this.y1 = y1;
  21494. this.x2 = x2;
  21495. this.y2 = y2;
  21496. }
  21497. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21498. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21499. };
  21500. return BezierCurveEase;
  21501. })(EasingFunction);
  21502. BABYLON.BezierCurveEase = BezierCurveEase;
  21503. })(BABYLON || (BABYLON = {}));
  21504. //# sourceMappingURL=babylon.easing.js.map
  21505. var BABYLON;
  21506. (function (BABYLON) {
  21507. var Octree = (function () {
  21508. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21509. if (maxDepth === void 0) { maxDepth = 2; }
  21510. this.maxDepth = maxDepth;
  21511. this.dynamicContent = new Array();
  21512. this._maxBlockCapacity = maxBlockCapacity || 64;
  21513. this._selectionContent = new BABYLON.SmartArray(1024);
  21514. this._creationFunc = creationFunc;
  21515. }
  21516. // Methods
  21517. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21518. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21519. };
  21520. Octree.prototype.addMesh = function (entry) {
  21521. for (var index = 0; index < this.blocks.length; index++) {
  21522. var block = this.blocks[index];
  21523. block.addEntry(entry);
  21524. }
  21525. };
  21526. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21527. this._selectionContent.reset();
  21528. for (var index = 0; index < this.blocks.length; index++) {
  21529. var block = this.blocks[index];
  21530. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21531. }
  21532. if (allowDuplicate) {
  21533. this._selectionContent.concat(this.dynamicContent);
  21534. }
  21535. else {
  21536. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21537. }
  21538. return this._selectionContent;
  21539. };
  21540. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21541. this._selectionContent.reset();
  21542. for (var index = 0; index < this.blocks.length; index++) {
  21543. var block = this.blocks[index];
  21544. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21545. }
  21546. if (allowDuplicate) {
  21547. this._selectionContent.concat(this.dynamicContent);
  21548. }
  21549. else {
  21550. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21551. }
  21552. return this._selectionContent;
  21553. };
  21554. Octree.prototype.intersectsRay = function (ray) {
  21555. this._selectionContent.reset();
  21556. for (var index = 0; index < this.blocks.length; index++) {
  21557. var block = this.blocks[index];
  21558. block.intersectsRay(ray, this._selectionContent);
  21559. }
  21560. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21561. return this._selectionContent;
  21562. };
  21563. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21564. target.blocks = new Array();
  21565. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21566. // Segmenting space
  21567. for (var x = 0; x < 2; x++) {
  21568. for (var y = 0; y < 2; y++) {
  21569. for (var z = 0; z < 2; z++) {
  21570. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21571. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21572. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21573. block.addEntries(entries);
  21574. target.blocks.push(block);
  21575. }
  21576. }
  21577. }
  21578. };
  21579. Octree.CreationFuncForMeshes = function (entry, block) {
  21580. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21581. block.entries.push(entry);
  21582. }
  21583. };
  21584. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21585. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21586. block.entries.push(entry);
  21587. }
  21588. };
  21589. return Octree;
  21590. })();
  21591. BABYLON.Octree = Octree;
  21592. })(BABYLON || (BABYLON = {}));
  21593. //# sourceMappingURL=babylon.octree.js.map
  21594. var BABYLON;
  21595. (function (BABYLON) {
  21596. var OctreeBlock = (function () {
  21597. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21598. this.entries = new Array();
  21599. this._boundingVectors = new Array();
  21600. this._capacity = capacity;
  21601. this._depth = depth;
  21602. this._maxDepth = maxDepth;
  21603. this._creationFunc = creationFunc;
  21604. this._minPoint = minPoint;
  21605. this._maxPoint = maxPoint;
  21606. this._boundingVectors.push(minPoint.clone());
  21607. this._boundingVectors.push(maxPoint.clone());
  21608. this._boundingVectors.push(minPoint.clone());
  21609. this._boundingVectors[2].x = maxPoint.x;
  21610. this._boundingVectors.push(minPoint.clone());
  21611. this._boundingVectors[3].y = maxPoint.y;
  21612. this._boundingVectors.push(minPoint.clone());
  21613. this._boundingVectors[4].z = maxPoint.z;
  21614. this._boundingVectors.push(maxPoint.clone());
  21615. this._boundingVectors[5].z = minPoint.z;
  21616. this._boundingVectors.push(maxPoint.clone());
  21617. this._boundingVectors[6].x = minPoint.x;
  21618. this._boundingVectors.push(maxPoint.clone());
  21619. this._boundingVectors[7].y = minPoint.y;
  21620. }
  21621. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21622. // Property
  21623. get: function () {
  21624. return this._capacity;
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21630. get: function () {
  21631. return this._minPoint;
  21632. },
  21633. enumerable: true,
  21634. configurable: true
  21635. });
  21636. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21637. get: function () {
  21638. return this._maxPoint;
  21639. },
  21640. enumerable: true,
  21641. configurable: true
  21642. });
  21643. // Methods
  21644. OctreeBlock.prototype.addEntry = function (entry) {
  21645. if (this.blocks) {
  21646. for (var index = 0; index < this.blocks.length; index++) {
  21647. var block = this.blocks[index];
  21648. block.addEntry(entry);
  21649. }
  21650. return;
  21651. }
  21652. this._creationFunc(entry, this);
  21653. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21654. this.createInnerBlocks();
  21655. }
  21656. };
  21657. OctreeBlock.prototype.addEntries = function (entries) {
  21658. for (var index = 0; index < entries.length; index++) {
  21659. var mesh = entries[index];
  21660. this.addEntry(mesh);
  21661. }
  21662. };
  21663. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21664. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21665. if (this.blocks) {
  21666. for (var index = 0; index < this.blocks.length; index++) {
  21667. var block = this.blocks[index];
  21668. block.select(frustumPlanes, selection, allowDuplicate);
  21669. }
  21670. return;
  21671. }
  21672. if (allowDuplicate) {
  21673. selection.concat(this.entries);
  21674. }
  21675. else {
  21676. selection.concatWithNoDuplicate(this.entries);
  21677. }
  21678. }
  21679. };
  21680. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21681. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21682. if (this.blocks) {
  21683. for (var index = 0; index < this.blocks.length; index++) {
  21684. var block = this.blocks[index];
  21685. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21686. }
  21687. return;
  21688. }
  21689. if (allowDuplicate) {
  21690. selection.concat(this.entries);
  21691. }
  21692. else {
  21693. selection.concatWithNoDuplicate(this.entries);
  21694. }
  21695. }
  21696. };
  21697. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21698. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21699. if (this.blocks) {
  21700. for (var index = 0; index < this.blocks.length; index++) {
  21701. var block = this.blocks[index];
  21702. block.intersectsRay(ray, selection);
  21703. }
  21704. return;
  21705. }
  21706. selection.concatWithNoDuplicate(this.entries);
  21707. }
  21708. };
  21709. OctreeBlock.prototype.createInnerBlocks = function () {
  21710. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21711. };
  21712. return OctreeBlock;
  21713. })();
  21714. BABYLON.OctreeBlock = OctreeBlock;
  21715. })(BABYLON || (BABYLON = {}));
  21716. //# sourceMappingURL=babylon.octreeBlock.js.map
  21717. var BABYLON;
  21718. (function (BABYLON) {
  21719. var Bone = (function () {
  21720. function Bone(name, skeleton, parentBone, matrix) {
  21721. this.name = name;
  21722. this.children = new Array();
  21723. this.animations = new Array();
  21724. this._worldTransform = new BABYLON.Matrix();
  21725. this._absoluteTransform = new BABYLON.Matrix();
  21726. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21727. this._skeleton = skeleton;
  21728. this._matrix = matrix;
  21729. this._baseMatrix = matrix;
  21730. skeleton.bones.push(this);
  21731. if (parentBone) {
  21732. this._parent = parentBone;
  21733. parentBone.children.push(this);
  21734. }
  21735. else {
  21736. this._parent = null;
  21737. }
  21738. this._updateDifferenceMatrix();
  21739. }
  21740. // Members
  21741. Bone.prototype.getParent = function () {
  21742. return this._parent;
  21743. };
  21744. Bone.prototype.getLocalMatrix = function () {
  21745. return this._matrix;
  21746. };
  21747. Bone.prototype.getBaseMatrix = function () {
  21748. return this._baseMatrix;
  21749. };
  21750. Bone.prototype.getWorldMatrix = function () {
  21751. return this._worldTransform;
  21752. };
  21753. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21754. return this._invertedAbsoluteTransform;
  21755. };
  21756. Bone.prototype.getAbsoluteMatrix = function () {
  21757. var matrix = this._matrix.clone();
  21758. var parent = this._parent;
  21759. while (parent) {
  21760. matrix = matrix.multiply(parent.getLocalMatrix());
  21761. parent = parent.getParent();
  21762. }
  21763. return matrix;
  21764. };
  21765. // Methods
  21766. Bone.prototype.updateMatrix = function (matrix) {
  21767. this._matrix = matrix;
  21768. this._skeleton._markAsDirty();
  21769. this._updateDifferenceMatrix();
  21770. };
  21771. Bone.prototype._updateDifferenceMatrix = function () {
  21772. if (this._parent) {
  21773. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21774. }
  21775. else {
  21776. this._absoluteTransform.copyFrom(this._matrix);
  21777. }
  21778. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21779. for (var index = 0; index < this.children.length; index++) {
  21780. this.children[index]._updateDifferenceMatrix();
  21781. }
  21782. };
  21783. Bone.prototype.markAsDirty = function () {
  21784. this._skeleton._markAsDirty();
  21785. };
  21786. return Bone;
  21787. })();
  21788. BABYLON.Bone = Bone;
  21789. })(BABYLON || (BABYLON = {}));
  21790. //# sourceMappingURL=babylon.bone.js.map
  21791. var BABYLON;
  21792. (function (BABYLON) {
  21793. var Skeleton = (function () {
  21794. function Skeleton(name, id, scene) {
  21795. this.name = name;
  21796. this.id = id;
  21797. this.bones = new Array();
  21798. this._isDirty = true;
  21799. this._identity = BABYLON.Matrix.Identity();
  21800. this.bones = [];
  21801. this._scene = scene;
  21802. scene.skeletons.push(this);
  21803. this.prepare();
  21804. //make sure it will recalculate the matrix next time prepare is called.
  21805. this._isDirty = true;
  21806. }
  21807. // Members
  21808. Skeleton.prototype.getTransformMatrices = function () {
  21809. return this._transformMatrices;
  21810. };
  21811. // Methods
  21812. Skeleton.prototype._markAsDirty = function () {
  21813. this._isDirty = true;
  21814. };
  21815. Skeleton.prototype.prepare = function () {
  21816. if (!this._isDirty) {
  21817. return;
  21818. }
  21819. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21820. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21821. }
  21822. for (var index = 0; index < this.bones.length; index++) {
  21823. var bone = this.bones[index];
  21824. var parentBone = bone.getParent();
  21825. if (parentBone) {
  21826. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21827. }
  21828. else {
  21829. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21830. }
  21831. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21832. }
  21833. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21834. this._isDirty = false;
  21835. this._scene._activeBones += this.bones.length;
  21836. };
  21837. Skeleton.prototype.getAnimatables = function () {
  21838. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21839. this._animatables = [];
  21840. for (var index = 0; index < this.bones.length; index++) {
  21841. this._animatables.push(this.bones[index]);
  21842. }
  21843. }
  21844. return this._animatables;
  21845. };
  21846. Skeleton.prototype.clone = function (name, id) {
  21847. var result = new Skeleton(name, id || name, this._scene);
  21848. for (var index = 0; index < this.bones.length; index++) {
  21849. var source = this.bones[index];
  21850. var parentBone = null;
  21851. if (source.getParent()) {
  21852. var parentIndex = this.bones.indexOf(source.getParent());
  21853. parentBone = result.bones[parentIndex];
  21854. }
  21855. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21856. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21857. }
  21858. return result;
  21859. };
  21860. return Skeleton;
  21861. })();
  21862. BABYLON.Skeleton = Skeleton;
  21863. })(BABYLON || (BABYLON = {}));
  21864. //# sourceMappingURL=babylon.skeleton.js.map
  21865. var BABYLON;
  21866. (function (BABYLON) {
  21867. var PostProcess = (function () {
  21868. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  21869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21870. this.name = name;
  21871. this.width = -1;
  21872. this.height = -1;
  21873. this._reusable = false;
  21874. this._textures = new BABYLON.SmartArray(2);
  21875. this._currentRenderTextureInd = 0;
  21876. if (camera != null) {
  21877. this._camera = camera;
  21878. this._scene = camera.getScene();
  21879. camera.attachPostProcess(this);
  21880. this._engine = this._scene.getEngine();
  21881. }
  21882. else {
  21883. this._engine = engine;
  21884. }
  21885. this._renderRatio = ratio;
  21886. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21887. this._reusable = reusable || false;
  21888. samplers = samplers || [];
  21889. samplers.push("textureSampler");
  21890. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21891. }
  21892. PostProcess.prototype.isReusable = function () {
  21893. return this._reusable;
  21894. };
  21895. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21896. camera = camera || this._camera;
  21897. var scene = camera.getScene();
  21898. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21899. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21900. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21901. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21902. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21903. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21904. if (this._textures.length > 0) {
  21905. for (var i = 0; i < this._textures.length; i++) {
  21906. this._engine._releaseTexture(this._textures.data[i]);
  21907. }
  21908. this._textures.reset();
  21909. }
  21910. this.width = desiredWidth;
  21911. this.height = desiredHeight;
  21912. 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 }));
  21913. if (this._reusable) {
  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. }
  21916. if (this.onSizeChanged) {
  21917. this.onSizeChanged();
  21918. }
  21919. }
  21920. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21921. if (this.onActivate) {
  21922. this.onActivate(camera);
  21923. }
  21924. // Clear
  21925. if (this.clearColor) {
  21926. this._engine.clear(this.clearColor, true, true);
  21927. }
  21928. else {
  21929. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21930. }
  21931. if (this._reusable) {
  21932. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21933. }
  21934. };
  21935. PostProcess.prototype.apply = function () {
  21936. // Check
  21937. if (!this._effect.isReady())
  21938. return null;
  21939. // States
  21940. this._engine.enableEffect(this._effect);
  21941. this._engine.setState(false);
  21942. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21943. this._engine.setDepthBuffer(false);
  21944. this._engine.setDepthWrite(false);
  21945. // Texture
  21946. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21947. // Parameters
  21948. if (this.onApply) {
  21949. this.onApply(this._effect);
  21950. }
  21951. return this._effect;
  21952. };
  21953. PostProcess.prototype.dispose = function (camera) {
  21954. camera = camera || this._camera;
  21955. if (this._textures.length > 0) {
  21956. for (var i = 0; i < this._textures.length; i++) {
  21957. this._engine._releaseTexture(this._textures.data[i]);
  21958. }
  21959. this._textures.reset();
  21960. }
  21961. if (!camera) {
  21962. return;
  21963. }
  21964. camera.detachPostProcess(this);
  21965. var index = camera._postProcesses.indexOf(this);
  21966. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21967. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21968. }
  21969. };
  21970. return PostProcess;
  21971. })();
  21972. BABYLON.PostProcess = PostProcess;
  21973. })(BABYLON || (BABYLON = {}));
  21974. //# sourceMappingURL=babylon.postProcess.js.map
  21975. var BABYLON;
  21976. (function (BABYLON) {
  21977. var PostProcessManager = (function () {
  21978. function PostProcessManager(scene) {
  21979. this._vertexDeclaration = [2];
  21980. this._vertexStrideSize = 2 * 4;
  21981. this._scene = scene;
  21982. }
  21983. PostProcessManager.prototype._prepareBuffers = function () {
  21984. if (this._vertexBuffer) {
  21985. return;
  21986. }
  21987. // VBO
  21988. var vertices = [];
  21989. vertices.push(1, 1);
  21990. vertices.push(-1, 1);
  21991. vertices.push(-1, -1);
  21992. vertices.push(1, -1);
  21993. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21994. // Indices
  21995. var indices = [];
  21996. indices.push(0);
  21997. indices.push(1);
  21998. indices.push(2);
  21999. indices.push(0);
  22000. indices.push(2);
  22001. indices.push(3);
  22002. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22003. };
  22004. // Methods
  22005. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22006. var postProcesses = this._scene.activeCamera._postProcesses;
  22007. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22008. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22009. return false;
  22010. }
  22011. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22012. return true;
  22013. };
  22014. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22015. var engine = this._scene.getEngine();
  22016. for (var index = 0; index < postProcesses.length; index++) {
  22017. if (index < postProcesses.length - 1) {
  22018. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22019. }
  22020. else {
  22021. if (targetTexture) {
  22022. engine.bindFramebuffer(targetTexture);
  22023. }
  22024. else {
  22025. engine.restoreDefaultFramebuffer();
  22026. }
  22027. }
  22028. var pp = postProcesses[index];
  22029. var effect = pp.apply();
  22030. if (effect) {
  22031. if (pp.onBeforeRender) {
  22032. pp.onBeforeRender(effect);
  22033. }
  22034. // VBOs
  22035. this._prepareBuffers();
  22036. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22037. // Draw order
  22038. engine.draw(true, 0, 6);
  22039. }
  22040. }
  22041. // Restore depth buffer
  22042. engine.setDepthBuffer(true);
  22043. engine.setDepthWrite(true);
  22044. };
  22045. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22046. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22047. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22048. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22049. return;
  22050. }
  22051. var engine = this._scene.getEngine();
  22052. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22053. if (index < postProcessesTakenIndices.length - 1) {
  22054. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22055. }
  22056. else {
  22057. if (targetTexture) {
  22058. engine.bindFramebuffer(targetTexture);
  22059. }
  22060. else {
  22061. engine.restoreDefaultFramebuffer();
  22062. }
  22063. }
  22064. if (doNotPresent) {
  22065. break;
  22066. }
  22067. var pp = postProcesses[postProcessesTakenIndices[index]];
  22068. var effect = pp.apply();
  22069. if (effect) {
  22070. if (pp.onBeforeRender) {
  22071. pp.onBeforeRender(effect);
  22072. }
  22073. // VBOs
  22074. this._prepareBuffers();
  22075. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22076. // Draw order
  22077. engine.draw(true, 0, 6);
  22078. }
  22079. }
  22080. // Restore depth buffer
  22081. engine.setDepthBuffer(true);
  22082. engine.setDepthWrite(true);
  22083. };
  22084. PostProcessManager.prototype.dispose = function () {
  22085. if (this._vertexBuffer) {
  22086. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22087. this._vertexBuffer = null;
  22088. }
  22089. if (this._indexBuffer) {
  22090. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22091. this._indexBuffer = null;
  22092. }
  22093. };
  22094. return PostProcessManager;
  22095. })();
  22096. BABYLON.PostProcessManager = PostProcessManager;
  22097. })(BABYLON || (BABYLON = {}));
  22098. //# sourceMappingURL=babylon.postProcessManager.js.map
  22099. var __extends = this.__extends || function (d, b) {
  22100. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22101. function __() { this.constructor = d; }
  22102. __.prototype = b.prototype;
  22103. d.prototype = new __();
  22104. };
  22105. var BABYLON;
  22106. (function (BABYLON) {
  22107. var PassPostProcess = (function (_super) {
  22108. __extends(PassPostProcess, _super);
  22109. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22110. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22111. }
  22112. return PassPostProcess;
  22113. })(BABYLON.PostProcess);
  22114. BABYLON.PassPostProcess = PassPostProcess;
  22115. })(BABYLON || (BABYLON = {}));
  22116. //# sourceMappingURL=babylon.passPostProcess.js.map
  22117. var __extends = this.__extends || function (d, b) {
  22118. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22119. function __() { this.constructor = d; }
  22120. __.prototype = b.prototype;
  22121. d.prototype = new __();
  22122. };
  22123. var BABYLON;
  22124. (function (BABYLON) {
  22125. var BlurPostProcess = (function (_super) {
  22126. __extends(BlurPostProcess, _super);
  22127. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22128. var _this = this;
  22129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22130. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22131. this.direction = direction;
  22132. this.blurWidth = blurWidth;
  22133. this.onApply = function (effect) {
  22134. effect.setFloat2("screenSize", _this.width, _this.height);
  22135. effect.setVector2("direction", _this.direction);
  22136. effect.setFloat("blurWidth", _this.blurWidth);
  22137. };
  22138. }
  22139. return BlurPostProcess;
  22140. })(BABYLON.PostProcess);
  22141. BABYLON.BlurPostProcess = BlurPostProcess;
  22142. })(BABYLON || (BABYLON = {}));
  22143. //# sourceMappingURL=babylon.blurPostProcess.js.map
  22144. var __extends = this.__extends || function (d, b) {
  22145. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22146. function __() { this.constructor = d; }
  22147. __.prototype = b.prototype;
  22148. d.prototype = new __();
  22149. };
  22150. var BABYLON;
  22151. (function (BABYLON) {
  22152. var RefractionPostProcess = (function (_super) {
  22153. __extends(RefractionPostProcess, _super);
  22154. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22155. var _this = this;
  22156. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22157. this.color = color;
  22158. this.depth = depth;
  22159. this.colorLevel = colorLevel;
  22160. this.onActivate = function (cam) {
  22161. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22162. };
  22163. this.onApply = function (effect) {
  22164. effect.setColor3("baseColor", _this.color);
  22165. effect.setFloat("depth", _this.depth);
  22166. effect.setFloat("colorLevel", _this.colorLevel);
  22167. effect.setTexture("refractionSampler", _this._refRexture);
  22168. };
  22169. }
  22170. // Methods
  22171. RefractionPostProcess.prototype.dispose = function (camera) {
  22172. if (this._refRexture) {
  22173. this._refRexture.dispose();
  22174. }
  22175. _super.prototype.dispose.call(this, camera);
  22176. };
  22177. return RefractionPostProcess;
  22178. })(BABYLON.PostProcess);
  22179. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22180. })(BABYLON || (BABYLON = {}));
  22181. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22182. var __extends = this.__extends || function (d, b) {
  22183. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22184. function __() { this.constructor = d; }
  22185. __.prototype = b.prototype;
  22186. d.prototype = new __();
  22187. };
  22188. var BABYLON;
  22189. (function (BABYLON) {
  22190. var BlackAndWhitePostProcess = (function (_super) {
  22191. __extends(BlackAndWhitePostProcess, _super);
  22192. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22193. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22194. }
  22195. return BlackAndWhitePostProcess;
  22196. })(BABYLON.PostProcess);
  22197. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22198. })(BABYLON || (BABYLON = {}));
  22199. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22200. var __extends = this.__extends || function (d, b) {
  22201. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22202. function __() { this.constructor = d; }
  22203. __.prototype = b.prototype;
  22204. d.prototype = new __();
  22205. };
  22206. var BABYLON;
  22207. (function (BABYLON) {
  22208. var ConvolutionPostProcess = (function (_super) {
  22209. __extends(ConvolutionPostProcess, _super);
  22210. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22211. var _this = this;
  22212. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22213. this.kernel = kernel;
  22214. this.onApply = function (effect) {
  22215. effect.setFloat2("screenSize", _this.width, _this.height);
  22216. effect.setArray("kernel", _this.kernel);
  22217. };
  22218. }
  22219. // Statics
  22220. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22221. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22222. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22223. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22224. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22225. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22226. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22227. return ConvolutionPostProcess;
  22228. })(BABYLON.PostProcess);
  22229. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22230. })(BABYLON || (BABYLON = {}));
  22231. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22232. var __extends = this.__extends || function (d, b) {
  22233. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22234. function __() { this.constructor = d; }
  22235. __.prototype = b.prototype;
  22236. d.prototype = new __();
  22237. };
  22238. var BABYLON;
  22239. (function (BABYLON) {
  22240. var FilterPostProcess = (function (_super) {
  22241. __extends(FilterPostProcess, _super);
  22242. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22243. var _this = this;
  22244. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22245. this.kernelMatrix = kernelMatrix;
  22246. this.onApply = function (effect) {
  22247. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22248. };
  22249. }
  22250. return FilterPostProcess;
  22251. })(BABYLON.PostProcess);
  22252. BABYLON.FilterPostProcess = FilterPostProcess;
  22253. })(BABYLON || (BABYLON = {}));
  22254. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22255. var __extends = this.__extends || function (d, b) {
  22256. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22257. function __() { this.constructor = d; }
  22258. __.prototype = b.prototype;
  22259. d.prototype = new __();
  22260. };
  22261. var BABYLON;
  22262. (function (BABYLON) {
  22263. var FxaaPostProcess = (function (_super) {
  22264. __extends(FxaaPostProcess, _super);
  22265. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22266. var _this = this;
  22267. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22268. this.onSizeChanged = function () {
  22269. _this.texelWidth = 1.0 / _this.width;
  22270. _this.texelHeight = 1.0 / _this.height;
  22271. };
  22272. this.onApply = function (effect) {
  22273. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22274. };
  22275. }
  22276. return FxaaPostProcess;
  22277. })(BABYLON.PostProcess);
  22278. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22279. })(BABYLON || (BABYLON = {}));
  22280. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22281. var __extends = this.__extends || function (d, b) {
  22282. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22283. function __() { this.constructor = d; }
  22284. __.prototype = b.prototype;
  22285. d.prototype = new __();
  22286. };
  22287. var BABYLON;
  22288. (function (BABYLON) {
  22289. var StereoscopicInterlacePostProcess = (function (_super) {
  22290. __extends(StereoscopicInterlacePostProcess, _super);
  22291. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  22292. var _this = this;
  22293. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  22294. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22295. this.onSizeChanged = function () {
  22296. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22297. };
  22298. this.onApply = function (effect) {
  22299. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22300. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22301. };
  22302. }
  22303. return StereoscopicInterlacePostProcess;
  22304. })(BABYLON.PostProcess);
  22305. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  22306. })(BABYLON || (BABYLON = {}));
  22307. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  22308. var BABYLON;
  22309. (function (BABYLON) {
  22310. var LensFlare = (function () {
  22311. function LensFlare(size, position, color, imgUrl, system) {
  22312. this.size = size;
  22313. this.position = position;
  22314. this.dispose = function () {
  22315. if (this.texture) {
  22316. this.texture.dispose();
  22317. }
  22318. // Remove from scene
  22319. var index = this._system.lensFlares.indexOf(this);
  22320. this._system.lensFlares.splice(index, 1);
  22321. };
  22322. this.color = color || new BABYLON.Color3(1, 1, 1);
  22323. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22324. this._system = system;
  22325. system.lensFlares.push(this);
  22326. }
  22327. return LensFlare;
  22328. })();
  22329. BABYLON.LensFlare = LensFlare;
  22330. })(BABYLON || (BABYLON = {}));
  22331. //# sourceMappingURL=babylon.lensFlare.js.map
  22332. var BABYLON;
  22333. (function (BABYLON) {
  22334. var LensFlareSystem = (function () {
  22335. function LensFlareSystem(name, emitter, scene) {
  22336. this.name = name;
  22337. this.lensFlares = new Array();
  22338. this.borderLimit = 300;
  22339. this._vertexDeclaration = [2];
  22340. this._vertexStrideSize = 2 * 4;
  22341. this._isEnabled = true;
  22342. this._scene = scene;
  22343. this._emitter = emitter;
  22344. scene.lensFlareSystems.push(this);
  22345. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22346. // VBO
  22347. var vertices = [];
  22348. vertices.push(1, 1);
  22349. vertices.push(-1, 1);
  22350. vertices.push(-1, -1);
  22351. vertices.push(1, -1);
  22352. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22353. // Indices
  22354. var indices = [];
  22355. indices.push(0);
  22356. indices.push(1);
  22357. indices.push(2);
  22358. indices.push(0);
  22359. indices.push(2);
  22360. indices.push(3);
  22361. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22362. // Effects
  22363. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22364. }
  22365. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22366. get: function () {
  22367. return this._isEnabled;
  22368. },
  22369. set: function (value) {
  22370. this._isEnabled = value;
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. LensFlareSystem.prototype.getScene = function () {
  22376. return this._scene;
  22377. };
  22378. LensFlareSystem.prototype.getEmitter = function () {
  22379. return this._emitter;
  22380. };
  22381. LensFlareSystem.prototype.getEmitterPosition = function () {
  22382. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22383. };
  22384. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22385. var position = this.getEmitterPosition();
  22386. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22387. this._positionX = position.x;
  22388. this._positionY = position.y;
  22389. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22390. if (position.z > 0) {
  22391. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22392. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22393. return true;
  22394. }
  22395. }
  22396. return false;
  22397. };
  22398. LensFlareSystem.prototype._isVisible = function () {
  22399. if (!this._isEnabled) {
  22400. return false;
  22401. }
  22402. var emitterPosition = this.getEmitterPosition();
  22403. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22404. var distance = direction.length();
  22405. direction.normalize();
  22406. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22407. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22408. return !pickInfo.hit || pickInfo.distance > distance;
  22409. };
  22410. LensFlareSystem.prototype.render = function () {
  22411. if (!this._effect.isReady())
  22412. return false;
  22413. var engine = this._scene.getEngine();
  22414. var viewport = this._scene.activeCamera.viewport;
  22415. var globalViewport = viewport.toGlobal(engine);
  22416. // Position
  22417. if (!this.computeEffectivePosition(globalViewport)) {
  22418. return false;
  22419. }
  22420. // Visibility
  22421. if (!this._isVisible()) {
  22422. return false;
  22423. }
  22424. // Intensity
  22425. var awayX;
  22426. var awayY;
  22427. if (this._positionX < this.borderLimit + globalViewport.x) {
  22428. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22429. }
  22430. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22431. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22432. }
  22433. else {
  22434. awayX = 0;
  22435. }
  22436. if (this._positionY < this.borderLimit + globalViewport.y) {
  22437. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22438. }
  22439. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22440. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22441. }
  22442. else {
  22443. awayY = 0;
  22444. }
  22445. var away = (awayX > awayY) ? awayX : awayY;
  22446. if (away > this.borderLimit) {
  22447. away = this.borderLimit;
  22448. }
  22449. var intensity = 1.0 - (away / this.borderLimit);
  22450. if (intensity < 0) {
  22451. return false;
  22452. }
  22453. if (intensity > 1.0) {
  22454. intensity = 1.0;
  22455. }
  22456. // Position
  22457. var centerX = globalViewport.x + globalViewport.width / 2;
  22458. var centerY = globalViewport.y + globalViewport.height / 2;
  22459. var distX = centerX - this._positionX;
  22460. var distY = centerY - this._positionY;
  22461. // Effects
  22462. engine.enableEffect(this._effect);
  22463. engine.setState(false);
  22464. engine.setDepthBuffer(false);
  22465. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22466. // VBOs
  22467. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22468. // Flares
  22469. for (var index = 0; index < this.lensFlares.length; index++) {
  22470. var flare = this.lensFlares[index];
  22471. var x = centerX - (distX * flare.position);
  22472. var y = centerY - (distY * flare.position);
  22473. var cw = flare.size;
  22474. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22475. var cx = 2 * (x / globalViewport.width) - 1.0;
  22476. var cy = 1.0 - 2 * (y / globalViewport.height);
  22477. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22478. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22479. // Texture
  22480. this._effect.setTexture("textureSampler", flare.texture);
  22481. // Color
  22482. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22483. // Draw order
  22484. engine.draw(true, 0, 6);
  22485. }
  22486. engine.setDepthBuffer(true);
  22487. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22488. return true;
  22489. };
  22490. LensFlareSystem.prototype.dispose = function () {
  22491. if (this._vertexBuffer) {
  22492. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22493. this._vertexBuffer = null;
  22494. }
  22495. if (this._indexBuffer) {
  22496. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22497. this._indexBuffer = null;
  22498. }
  22499. while (this.lensFlares.length) {
  22500. this.lensFlares[0].dispose();
  22501. }
  22502. // Remove from scene
  22503. var index = this._scene.lensFlareSystems.indexOf(this);
  22504. this._scene.lensFlareSystems.splice(index, 1);
  22505. };
  22506. return LensFlareSystem;
  22507. })();
  22508. BABYLON.LensFlareSystem = LensFlareSystem;
  22509. })(BABYLON || (BABYLON = {}));
  22510. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22511. var BABYLON;
  22512. (function (BABYLON) {
  22513. var CannonJSPlugin = (function () {
  22514. function CannonJSPlugin() {
  22515. this._registeredMeshes = [];
  22516. this._physicsMaterials = [];
  22517. this.updateBodyPosition = function (mesh) {
  22518. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22519. var registeredMesh = this._registeredMeshes[index];
  22520. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22521. var body = registeredMesh.body;
  22522. var center = mesh.getBoundingInfo().boundingBox.center;
  22523. body.position.set(center.x, center.z, center.y);
  22524. body.quaternion.x = mesh.rotationQuaternion.x;
  22525. body.quaternion.z = mesh.rotationQuaternion.y;
  22526. body.quaternion.y = mesh.rotationQuaternion.z;
  22527. body.quaternion.w = -mesh.rotationQuaternion.w;
  22528. return;
  22529. }
  22530. }
  22531. };
  22532. }
  22533. CannonJSPlugin.prototype.initialize = function (iterations) {
  22534. if (iterations === void 0) { iterations = 10; }
  22535. this._world = new CANNON.World();
  22536. this._world.broadphase = new CANNON.NaiveBroadphase();
  22537. this._world.solver.iterations = iterations;
  22538. };
  22539. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22540. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22541. };
  22542. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22543. this._world.step(delta);
  22544. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22545. var registeredMesh = this._registeredMeshes[index];
  22546. if (registeredMesh.isChild) {
  22547. continue;
  22548. }
  22549. // Body position
  22550. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22551. var deltaPos = registeredMesh.delta;
  22552. if (deltaPos) {
  22553. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22554. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22555. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22556. }
  22557. else {
  22558. registeredMesh.mesh.position.x = bodyX;
  22559. registeredMesh.mesh.position.y = bodyZ;
  22560. registeredMesh.mesh.position.z = bodyY;
  22561. }
  22562. if (!registeredMesh.mesh.rotationQuaternion) {
  22563. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22564. }
  22565. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22566. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22567. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22568. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22569. }
  22570. };
  22571. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22572. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22573. };
  22574. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22575. this.unregisterMesh(mesh);
  22576. mesh.computeWorldMatrix(true);
  22577. switch (impostor) {
  22578. case BABYLON.PhysicsEngine.SphereImpostor:
  22579. var bbox = mesh.getBoundingInfo().boundingBox;
  22580. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22581. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22582. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22583. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22584. case BABYLON.PhysicsEngine.BoxImpostor:
  22585. bbox = mesh.getBoundingInfo().boundingBox;
  22586. var min = bbox.minimumWorld;
  22587. var max = bbox.maximumWorld;
  22588. var box = max.subtract(min).scale(0.5);
  22589. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22590. case BABYLON.PhysicsEngine.PlaneImpostor:
  22591. return this._createPlane(mesh, options);
  22592. case BABYLON.PhysicsEngine.MeshImpostor:
  22593. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22594. var rawFaces = mesh.getIndices();
  22595. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22596. }
  22597. return null;
  22598. };
  22599. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22600. var shape = new CANNON.Sphere(radius);
  22601. if (!options) {
  22602. return shape;
  22603. }
  22604. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22605. };
  22606. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22607. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22608. if (!options) {
  22609. return shape;
  22610. }
  22611. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22612. };
  22613. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22614. var shape = new CANNON.Plane();
  22615. if (!options) {
  22616. return shape;
  22617. }
  22618. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22619. };
  22620. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22621. var verts = [], faces = [];
  22622. mesh.computeWorldMatrix(true);
  22623. // Get vertices
  22624. for (var i = 0; i < rawVerts.length; i += 3) {
  22625. var transformed = BABYLON.Vector3.Zero();
  22626. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22627. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22628. }
  22629. // Get faces
  22630. for (var j = 0; j < rawFaces.length; j += 3) {
  22631. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22632. }
  22633. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22634. if (!options) {
  22635. return shape;
  22636. }
  22637. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22638. };
  22639. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22640. var index;
  22641. var mat;
  22642. for (index = 0; index < this._physicsMaterials.length; index++) {
  22643. mat = this._physicsMaterials[index];
  22644. if (mat.friction === friction && mat.restitution === restitution) {
  22645. return mat;
  22646. }
  22647. }
  22648. var currentMat = new CANNON.Material();
  22649. currentMat.friction = friction;
  22650. currentMat.restitution = restitution;
  22651. this._physicsMaterials.push(currentMat);
  22652. for (index = 0; index < this._physicsMaterials.length; index++) {
  22653. mat = this._physicsMaterials[index];
  22654. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22655. contactMaterial.contactEquationStiffness = 1e10;
  22656. contactMaterial.contactEquationRegularizationTime = 10;
  22657. this._world.addContactMaterial(contactMaterial);
  22658. }
  22659. return currentMat;
  22660. };
  22661. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22662. var initialRotation = null;
  22663. if (mesh.rotationQuaternion) {
  22664. initialRotation = mesh.rotationQuaternion.clone();
  22665. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22666. }
  22667. // The delta between the mesh position and the mesh bounding box center
  22668. var bbox = mesh.getBoundingInfo().boundingBox;
  22669. var deltaPosition = mesh.position.subtract(bbox.center);
  22670. var material = this._addMaterial(friction, restitution);
  22671. var body = new CANNON.RigidBody(mass, shape, material);
  22672. if (initialRotation) {
  22673. body.quaternion.x = initialRotation.x;
  22674. body.quaternion.z = initialRotation.y;
  22675. body.quaternion.y = initialRotation.z;
  22676. body.quaternion.w = -initialRotation.w;
  22677. }
  22678. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22679. this._world.add(body);
  22680. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22681. return body;
  22682. };
  22683. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22684. var compoundShape = new CANNON.Compound();
  22685. for (var index = 0; index < parts.length; index++) {
  22686. var mesh = parts[index].mesh;
  22687. var shape = this.registerMesh(mesh, parts[index].impostor);
  22688. if (index == 0) {
  22689. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22690. }
  22691. else {
  22692. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22693. }
  22694. }
  22695. var initialMesh = parts[0].mesh;
  22696. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22697. body.parts = parts;
  22698. return body;
  22699. };
  22700. CannonJSPlugin.prototype._unbindBody = function (body) {
  22701. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22702. var registeredMesh = this._registeredMeshes[index];
  22703. if (registeredMesh.body === body) {
  22704. registeredMesh.body = null;
  22705. registeredMesh.delta = 0;
  22706. }
  22707. }
  22708. };
  22709. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22710. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22711. var registeredMesh = this._registeredMeshes[index];
  22712. if (registeredMesh.mesh === mesh) {
  22713. // Remove body
  22714. if (registeredMesh.body) {
  22715. this._world.remove(registeredMesh.body);
  22716. this._unbindBody(registeredMesh.body);
  22717. }
  22718. this._registeredMeshes.splice(index, 1);
  22719. return;
  22720. }
  22721. }
  22722. };
  22723. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22724. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22725. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22726. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22727. var registeredMesh = this._registeredMeshes[index];
  22728. if (registeredMesh.mesh === mesh) {
  22729. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22730. return;
  22731. }
  22732. }
  22733. };
  22734. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22735. var body1 = null, body2 = null;
  22736. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22737. var registeredMesh = this._registeredMeshes[index];
  22738. if (registeredMesh.mesh === mesh1) {
  22739. body1 = registeredMesh.body;
  22740. }
  22741. else if (registeredMesh.mesh === mesh2) {
  22742. body2 = registeredMesh.body;
  22743. }
  22744. }
  22745. if (!body1 || !body2) {
  22746. return false;
  22747. }
  22748. 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));
  22749. this._world.addConstraint(constraint);
  22750. return true;
  22751. };
  22752. CannonJSPlugin.prototype.dispose = function () {
  22753. while (this._registeredMeshes.length) {
  22754. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22755. }
  22756. };
  22757. CannonJSPlugin.prototype.isSupported = function () {
  22758. return window.CANNON !== undefined;
  22759. };
  22760. return CannonJSPlugin;
  22761. })();
  22762. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22763. })(BABYLON || (BABYLON = {}));
  22764. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22765. var BABYLON;
  22766. (function (BABYLON) {
  22767. var OimoJSPlugin = (function () {
  22768. function OimoJSPlugin() {
  22769. this._registeredMeshes = [];
  22770. /**
  22771. * Update the body position according to the mesh position
  22772. * @param mesh
  22773. */
  22774. this.updateBodyPosition = function (mesh) {
  22775. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22776. var registeredMesh = this._registeredMeshes[index];
  22777. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22778. var body = registeredMesh.body.body;
  22779. mesh.computeWorldMatrix(true);
  22780. var center = mesh.getBoundingInfo().boundingBox.center;
  22781. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22782. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22783. body.sleeping = false;
  22784. return;
  22785. }
  22786. // Case where the parent has been updated
  22787. if (registeredMesh.mesh.parent === mesh) {
  22788. mesh.computeWorldMatrix(true);
  22789. registeredMesh.mesh.computeWorldMatrix(true);
  22790. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22791. var absoluteRotation = mesh.rotation;
  22792. body = registeredMesh.body.body;
  22793. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22794. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22795. body.sleeping = false;
  22796. return;
  22797. }
  22798. }
  22799. };
  22800. }
  22801. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22802. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22803. };
  22804. OimoJSPlugin.prototype.initialize = function (iterations) {
  22805. this._world = new OIMO.World();
  22806. this._world.clear();
  22807. };
  22808. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22809. this._world.gravity = gravity;
  22810. };
  22811. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22812. var body = null;
  22813. this.unregisterMesh(mesh);
  22814. mesh.computeWorldMatrix(true);
  22815. var initialRotation = null;
  22816. if (mesh.rotationQuaternion) {
  22817. initialRotation = mesh.rotationQuaternion.clone();
  22818. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22819. mesh.computeWorldMatrix(true);
  22820. }
  22821. var bbox = mesh.getBoundingInfo().boundingBox;
  22822. // The delta between the mesh position and the mesh bounding box center
  22823. var deltaPosition = mesh.position.subtract(bbox.center);
  22824. // Transform delta position with the rotation
  22825. if (initialRotation) {
  22826. var m = new BABYLON.Matrix();
  22827. initialRotation.toRotationMatrix(m);
  22828. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22829. }
  22830. // register mesh
  22831. switch (impostor) {
  22832. case BABYLON.PhysicsEngine.SphereImpostor:
  22833. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22834. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22835. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22836. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22837. body = new OIMO.Body({
  22838. type: 'sphere',
  22839. size: [size],
  22840. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22841. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22842. move: options.mass != 0,
  22843. config: [options.mass, options.friction, options.restitution],
  22844. world: this._world
  22845. });
  22846. break;
  22847. case BABYLON.PhysicsEngine.PlaneImpostor:
  22848. //Oimo "fakes" a cylinder as a box, so why don't we!
  22849. case BABYLON.PhysicsEngine.CylinderImpostor:
  22850. case BABYLON.PhysicsEngine.BoxImpostor:
  22851. var min = bbox.minimumWorld;
  22852. var max = bbox.maximumWorld;
  22853. var box = max.subtract(min);
  22854. var sizeX = this._checkWithEpsilon(box.x);
  22855. var sizeY = this._checkWithEpsilon(box.y);
  22856. var sizeZ = this._checkWithEpsilon(box.z);
  22857. body = new OIMO.Body({
  22858. type: 'box',
  22859. size: [sizeX, sizeY, sizeZ],
  22860. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22861. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22862. move: options.mass != 0,
  22863. config: [options.mass, options.friction, options.restitution],
  22864. world: this._world
  22865. });
  22866. break;
  22867. }
  22868. //If quaternion was set as the rotation of the object
  22869. if (initialRotation) {
  22870. //We have to access the rigid body's properties to set the quaternion.
  22871. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22872. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22873. //update the internal rotation matrix
  22874. body.body.syncShapes();
  22875. }
  22876. this._registeredMeshes.push({
  22877. mesh: mesh,
  22878. body: body,
  22879. delta: deltaPosition
  22880. });
  22881. return body;
  22882. };
  22883. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22884. var types = [], sizes = [], positions = [], rotations = [];
  22885. var initialMesh = parts[0].mesh;
  22886. for (var index = 0; index < parts.length; index++) {
  22887. var part = parts[index];
  22888. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22889. types.push(bodyParameters.type);
  22890. sizes.push.apply(sizes, bodyParameters.size);
  22891. positions.push.apply(positions, bodyParameters.pos);
  22892. rotations.push.apply(rotations, bodyParameters.rot);
  22893. }
  22894. var body = new OIMO.Body({
  22895. type: types,
  22896. size: sizes,
  22897. pos: positions,
  22898. rot: rotations,
  22899. move: options.mass != 0,
  22900. config: [options.mass, options.friction, options.restitution],
  22901. world: this._world
  22902. });
  22903. this._registeredMeshes.push({
  22904. mesh: initialMesh,
  22905. body: body
  22906. });
  22907. return body;
  22908. };
  22909. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22910. var bodyParameters = null;
  22911. var mesh = part.mesh;
  22912. // We need the bounding box/sphere info to compute the physics body
  22913. mesh.computeWorldMatrix();
  22914. switch (part.impostor) {
  22915. case BABYLON.PhysicsEngine.SphereImpostor:
  22916. var bbox = mesh.getBoundingInfo().boundingBox;
  22917. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22918. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22919. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22920. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22921. bodyParameters = {
  22922. type: 'sphere',
  22923. /* bug with oimo : sphere needs 3 sizes in this case */
  22924. size: [size, -1, -1],
  22925. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22926. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22927. };
  22928. break;
  22929. case BABYLON.PhysicsEngine.PlaneImpostor:
  22930. case BABYLON.PhysicsEngine.BoxImpostor:
  22931. bbox = mesh.getBoundingInfo().boundingBox;
  22932. var min = bbox.minimumWorld;
  22933. var max = bbox.maximumWorld;
  22934. var box = max.subtract(min);
  22935. var sizeX = this._checkWithEpsilon(box.x);
  22936. var sizeY = this._checkWithEpsilon(box.y);
  22937. var sizeZ = this._checkWithEpsilon(box.z);
  22938. var relativePosition = mesh.position;
  22939. bodyParameters = {
  22940. type: 'box',
  22941. size: [sizeX, sizeY, sizeZ],
  22942. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22943. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22944. };
  22945. break;
  22946. }
  22947. return bodyParameters;
  22948. };
  22949. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22950. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22951. var registeredMesh = this._registeredMeshes[index];
  22952. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22953. if (registeredMesh.body) {
  22954. this._world.removeRigidBody(registeredMesh.body.body);
  22955. this._unbindBody(registeredMesh.body);
  22956. }
  22957. this._registeredMeshes.splice(index, 1);
  22958. return;
  22959. }
  22960. }
  22961. };
  22962. OimoJSPlugin.prototype._unbindBody = function (body) {
  22963. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22964. var registeredMesh = this._registeredMeshes[index];
  22965. if (registeredMesh.body === body) {
  22966. registeredMesh.body = null;
  22967. }
  22968. }
  22969. };
  22970. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22971. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22972. var registeredMesh = this._registeredMeshes[index];
  22973. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22974. // Get object mass to have a behaviour similar to cannon.js
  22975. var mass = registeredMesh.body.body.massInfo.mass;
  22976. // The force is scaled with the mass of object
  22977. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22978. return;
  22979. }
  22980. }
  22981. };
  22982. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22983. var body1 = null, body2 = null;
  22984. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22985. var registeredMesh = this._registeredMeshes[index];
  22986. if (registeredMesh.mesh === mesh1) {
  22987. body1 = registeredMesh.body.body;
  22988. }
  22989. else if (registeredMesh.mesh === mesh2) {
  22990. body2 = registeredMesh.body.body;
  22991. }
  22992. }
  22993. if (!body1 || !body2) {
  22994. return false;
  22995. }
  22996. if (!options) {
  22997. options = {};
  22998. }
  22999. new OIMO.Link({
  23000. type: options.type,
  23001. body1: body1,
  23002. body2: body2,
  23003. min: options.min,
  23004. max: options.max,
  23005. axe1: options.axe1,
  23006. axe2: options.axe2,
  23007. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23008. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23009. collision: options.collision,
  23010. spring: options.spring,
  23011. world: this._world
  23012. });
  23013. return true;
  23014. };
  23015. OimoJSPlugin.prototype.dispose = function () {
  23016. this._world.clear();
  23017. while (this._registeredMeshes.length) {
  23018. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23019. }
  23020. };
  23021. OimoJSPlugin.prototype.isSupported = function () {
  23022. return OIMO !== undefined;
  23023. };
  23024. OimoJSPlugin.prototype._getLastShape = function (body) {
  23025. var lastShape = body.shapes;
  23026. while (lastShape.next) {
  23027. lastShape = lastShape.next;
  23028. }
  23029. return lastShape;
  23030. };
  23031. OimoJSPlugin.prototype.runOneStep = function (time) {
  23032. this._world.step();
  23033. // Update the position of all registered meshes
  23034. var i = this._registeredMeshes.length;
  23035. var m;
  23036. while (i--) {
  23037. var body = this._registeredMeshes[i].body.body;
  23038. var mesh = this._registeredMeshes[i].mesh;
  23039. var delta = this._registeredMeshes[i].delta;
  23040. if (!body.sleeping) {
  23041. if (body.shapes.next) {
  23042. var parentShape = this._getLastShape(body);
  23043. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23044. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23045. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23046. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23047. if (!mesh.rotationQuaternion) {
  23048. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23049. }
  23050. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23051. mesh.computeWorldMatrix();
  23052. }
  23053. else {
  23054. m = body.getMatrix();
  23055. mtx = BABYLON.Matrix.FromArray(m);
  23056. // Body position
  23057. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23058. if (!delta) {
  23059. mesh.position.x = bodyX;
  23060. mesh.position.y = bodyY;
  23061. mesh.position.z = bodyZ;
  23062. }
  23063. else {
  23064. mesh.position.x = bodyX + delta.x;
  23065. mesh.position.y = bodyY + delta.y;
  23066. mesh.position.z = bodyZ + delta.z;
  23067. }
  23068. if (!mesh.rotationQuaternion) {
  23069. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23070. }
  23071. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23072. mesh.computeWorldMatrix();
  23073. }
  23074. }
  23075. }
  23076. };
  23077. return OimoJSPlugin;
  23078. })();
  23079. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23080. })(BABYLON || (BABYLON = {}));
  23081. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  23082. var BABYLON;
  23083. (function (BABYLON) {
  23084. var PhysicsEngine = (function () {
  23085. function PhysicsEngine(plugin) {
  23086. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23087. }
  23088. PhysicsEngine.prototype._initialize = function (gravity) {
  23089. this._currentPlugin.initialize();
  23090. this._setGravity(gravity);
  23091. };
  23092. PhysicsEngine.prototype._runOneStep = function (delta) {
  23093. if (delta > 0.1) {
  23094. delta = 0.1;
  23095. }
  23096. else if (delta <= 0) {
  23097. delta = 1.0 / 60.0;
  23098. }
  23099. this._currentPlugin.runOneStep(delta);
  23100. };
  23101. PhysicsEngine.prototype._setGravity = function (gravity) {
  23102. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  23103. this._currentPlugin.setGravity(this.gravity);
  23104. };
  23105. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23106. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23107. };
  23108. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23109. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23110. };
  23111. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23112. this._currentPlugin.unregisterMesh(mesh);
  23113. };
  23114. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23115. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23116. };
  23117. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23118. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23119. };
  23120. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23121. this._currentPlugin.updateBodyPosition(mesh);
  23122. };
  23123. PhysicsEngine.prototype.dispose = function () {
  23124. this._currentPlugin.dispose();
  23125. };
  23126. PhysicsEngine.prototype.isSupported = function () {
  23127. return this._currentPlugin.isSupported();
  23128. };
  23129. // Statics
  23130. PhysicsEngine.NoImpostor = 0;
  23131. PhysicsEngine.SphereImpostor = 1;
  23132. PhysicsEngine.BoxImpostor = 2;
  23133. PhysicsEngine.PlaneImpostor = 3;
  23134. PhysicsEngine.MeshImpostor = 4;
  23135. PhysicsEngine.CapsuleImpostor = 5;
  23136. PhysicsEngine.ConeImpostor = 6;
  23137. PhysicsEngine.CylinderImpostor = 7;
  23138. PhysicsEngine.ConvexHullImpostor = 8;
  23139. PhysicsEngine.Epsilon = 0.001;
  23140. return PhysicsEngine;
  23141. })();
  23142. BABYLON.PhysicsEngine = PhysicsEngine;
  23143. })(BABYLON || (BABYLON = {}));
  23144. //# sourceMappingURL=babylon.physicsEngine.js.map
  23145. var BABYLON;
  23146. (function (BABYLON) {
  23147. var serializeLight = function (light) {
  23148. var serializationObject = {};
  23149. serializationObject.name = light.name;
  23150. serializationObject.id = light.id;
  23151. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23152. if (light instanceof BABYLON.PointLight) {
  23153. serializationObject.type = 0;
  23154. serializationObject.position = light.position.asArray();
  23155. }
  23156. else if (light instanceof BABYLON.DirectionalLight) {
  23157. serializationObject.type = 1;
  23158. var directionalLight = light;
  23159. serializationObject.position = directionalLight.position.asArray();
  23160. serializationObject.direction = directionalLight.direction.asArray();
  23161. }
  23162. else if (light instanceof BABYLON.SpotLight) {
  23163. serializationObject.type = 2;
  23164. var spotLight = light;
  23165. serializationObject.position = spotLight.position.asArray();
  23166. serializationObject.direction = spotLight.position.asArray();
  23167. serializationObject.angle = spotLight.angle;
  23168. serializationObject.exponent = spotLight.exponent;
  23169. }
  23170. else if (light instanceof BABYLON.HemisphericLight) {
  23171. serializationObject.type = 3;
  23172. var hemisphericLight = light;
  23173. serializationObject.direction = hemisphericLight.direction.asArray();
  23174. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23175. }
  23176. if (light.intensity) {
  23177. serializationObject.intensity = light.intensity;
  23178. }
  23179. serializationObject.range = light.range;
  23180. serializationObject.diffuse = light.diffuse.asArray();
  23181. serializationObject.specular = light.specular.asArray();
  23182. return serializationObject;
  23183. };
  23184. var serializeFresnelParameter = function (fresnelParameter) {
  23185. var serializationObject = {};
  23186. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23187. serializationObject.leftColor = fresnelParameter.leftColor;
  23188. serializationObject.rightColor = fresnelParameter.rightColor;
  23189. serializationObject.bias = fresnelParameter.bias;
  23190. serializationObject.power = fresnelParameter.power;
  23191. return serializationObject;
  23192. };
  23193. var appendAnimations = function (source, destination) {
  23194. if (source.animations) {
  23195. destination.animations = [];
  23196. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23197. var animation = source.animations[animationIndex];
  23198. destination.animations.push(serializeAnimation(animation));
  23199. }
  23200. }
  23201. };
  23202. var serializeCamera = function (camera) {
  23203. var serializationObject = {};
  23204. serializationObject.name = camera.name;
  23205. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23206. serializationObject.id = camera.id;
  23207. serializationObject.position = camera.position.asArray();
  23208. // Parent
  23209. if (camera.parent) {
  23210. serializationObject.parentId = camera.parent.id;
  23211. }
  23212. serializationObject.fov = camera.fov;
  23213. serializationObject.minZ = camera.minZ;
  23214. serializationObject.maxZ = camera.maxZ;
  23215. serializationObject.inertia = camera.inertia;
  23216. //setting the type
  23217. if (camera instanceof BABYLON.FreeCamera) {
  23218. serializationObject.type = "FreeCamera";
  23219. }
  23220. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23221. serializationObject.type = "ArcRotateCamera";
  23222. }
  23223. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23224. serializationObject.type = "AnaglyphArcRotateCamera";
  23225. }
  23226. else if (camera instanceof BABYLON.GamepadCamera) {
  23227. serializationObject.type = "GamepadCamera";
  23228. }
  23229. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23230. serializationObject.type = "AnaglyphFreeCamera";
  23231. }
  23232. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23233. serializationObject.type = "DeviceOrientationCamera";
  23234. }
  23235. else if (camera instanceof BABYLON.FollowCamera) {
  23236. serializationObject.type = "FollowCamera";
  23237. }
  23238. else if (camera instanceof BABYLON.TouchCamera) {
  23239. serializationObject.type = "TouchCamera";
  23240. }
  23241. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23242. serializationObject.type = "VirtualJoysticksCamera";
  23243. }
  23244. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23245. serializationObject.type = "WebVRFreeCamera";
  23246. }
  23247. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23248. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23249. }
  23250. //special properties of specific cameras
  23251. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23252. var arcCamera = camera;
  23253. serializationObject.alpha = arcCamera.alpha;
  23254. serializationObject.beta = arcCamera.beta;
  23255. serializationObject.radius = arcCamera.radius;
  23256. if (arcCamera.target && arcCamera.target.id) {
  23257. serializationObject.lockedTargetId = arcCamera.target.id;
  23258. }
  23259. }
  23260. else if (camera instanceof BABYLON.FollowCamera) {
  23261. var followCam = camera;
  23262. serializationObject.radius = followCam.radius;
  23263. serializationObject.heightOffset = followCam.heightOffset;
  23264. serializationObject.rotationOffset = followCam.rotationOffset;
  23265. }
  23266. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23267. //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.
  23268. if (camera['_eyeSpace'] !== undefined) {
  23269. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  23270. }
  23271. }
  23272. //general properties that not all cameras have. The [] is due to typescript's type safety
  23273. if (camera['speed'] !== undefined) {
  23274. serializationObject.speed = camera['speed'];
  23275. }
  23276. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23277. serializationObject.target = camera['target'].asArray();
  23278. }
  23279. // Target
  23280. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23281. serializationObject.rotation = camera['rotation'].asArray();
  23282. }
  23283. // Locked target
  23284. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23285. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23286. }
  23287. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23288. serializationObject.applyGravity = camera['applyGravity'] || false;
  23289. if (camera['ellipsoid']) {
  23290. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23291. }
  23292. // Animations
  23293. appendAnimations(camera, serializationObject);
  23294. // Layer mask
  23295. serializationObject.layerMask = camera.layerMask;
  23296. return serializationObject;
  23297. };
  23298. var serializeAnimation = function (animation) {
  23299. var serializationObject = {};
  23300. serializationObject.name = animation.name;
  23301. serializationObject.property = animation.targetProperty;
  23302. serializationObject.framePerSecond = animation.framePerSecond;
  23303. serializationObject.dataType = animation.dataType;
  23304. serializationObject.loopBehavior = animation.loopMode;
  23305. var dataType = animation.dataType;
  23306. serializationObject.keys = [];
  23307. var keys = animation.getKeys();
  23308. for (var index = 0; index < keys.length; index++) {
  23309. var animationKey = keys[index];
  23310. var key = {};
  23311. key.frame = animationKey.frame;
  23312. switch (dataType) {
  23313. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23314. key.values = [animationKey.value];
  23315. break;
  23316. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23317. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23318. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23319. key.values = animationKey.value.asArray();
  23320. break;
  23321. }
  23322. serializationObject.keys.push(key);
  23323. }
  23324. return serializationObject;
  23325. };
  23326. var serializeMultiMaterial = function (material) {
  23327. var serializationObject = {};
  23328. serializationObject.name = material.name;
  23329. serializationObject.id = material.id;
  23330. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23331. serializationObject.materials = [];
  23332. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23333. var subMat = material.subMaterials[matIndex];
  23334. if (subMat) {
  23335. serializationObject.materials.push(subMat.id);
  23336. }
  23337. else {
  23338. serializationObject.materials.push(null);
  23339. }
  23340. }
  23341. return serializationObject;
  23342. };
  23343. var serializeMaterial = function (material) {
  23344. var serializationObject = {};
  23345. serializationObject.name = material.name;
  23346. serializationObject.ambient = material.ambientColor.asArray();
  23347. serializationObject.diffuse = material.diffuseColor.asArray();
  23348. serializationObject.specular = material.specularColor.asArray();
  23349. serializationObject.specularPower = material.specularPower;
  23350. serializationObject.emissive = material.emissiveColor.asArray();
  23351. serializationObject.alpha = material.alpha;
  23352. serializationObject.id = material.id;
  23353. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23354. serializationObject.backFaceCulling = material.backFaceCulling;
  23355. if (material.diffuseTexture) {
  23356. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23357. }
  23358. if (material.diffuseFresnelParameters) {
  23359. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23360. }
  23361. if (material.ambientTexture) {
  23362. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23363. }
  23364. if (material.opacityTexture) {
  23365. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23366. }
  23367. if (material.opacityFresnelParameters) {
  23368. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23369. }
  23370. if (material.reflectionTexture) {
  23371. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23372. }
  23373. if (material.reflectionFresnelParameters) {
  23374. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23375. }
  23376. if (material.emissiveTexture) {
  23377. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23378. }
  23379. if (material.emissiveFresnelParameters) {
  23380. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23381. }
  23382. if (material.specularTexture) {
  23383. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23384. }
  23385. if (material.bumpTexture) {
  23386. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23387. }
  23388. return serializationObject;
  23389. };
  23390. var serializeTexture = function (texture) {
  23391. var serializationObject = {};
  23392. if (!texture.name) {
  23393. return null;
  23394. }
  23395. if (texture instanceof BABYLON.CubeTexture) {
  23396. serializationObject.name = texture.name;
  23397. serializationObject.hasAlpha = texture.hasAlpha;
  23398. serializationObject.level = texture.level;
  23399. serializationObject.coordinatesMode = texture.coordinatesMode;
  23400. return serializationObject;
  23401. }
  23402. if (texture instanceof BABYLON.MirrorTexture) {
  23403. var mirrorTexture = texture;
  23404. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23405. serializationObject.renderList = [];
  23406. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23407. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23408. }
  23409. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23410. }
  23411. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23412. var renderTargetTexture = texture;
  23413. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23414. serializationObject.renderList = [];
  23415. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23416. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23417. }
  23418. }
  23419. var regularTexture = texture;
  23420. serializationObject.name = texture.name;
  23421. serializationObject.hasAlpha = texture.hasAlpha;
  23422. serializationObject.level = texture.level;
  23423. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23424. serializationObject.coordinatesMode = texture.coordinatesMode;
  23425. serializationObject.uOffset = regularTexture.uOffset;
  23426. serializationObject.vOffset = regularTexture.vOffset;
  23427. serializationObject.uScale = regularTexture.uScale;
  23428. serializationObject.vScale = regularTexture.vScale;
  23429. serializationObject.uAng = regularTexture.uAng;
  23430. serializationObject.vAng = regularTexture.vAng;
  23431. serializationObject.wAng = regularTexture.wAng;
  23432. serializationObject.wrapU = texture.wrapU;
  23433. serializationObject.wrapV = texture.wrapV;
  23434. // Animations
  23435. appendAnimations(texture, serializationObject);
  23436. return serializationObject;
  23437. };
  23438. var serializeSkeleton = function (skeleton) {
  23439. var serializationObject = {};
  23440. serializationObject.name = skeleton.name;
  23441. serializationObject.id = skeleton.id;
  23442. serializationObject.bones = [];
  23443. for (var index = 0; index < skeleton.bones.length; index++) {
  23444. var bone = skeleton.bones[index];
  23445. var serializedBone = {
  23446. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23447. name: bone.name,
  23448. matrix: bone.getLocalMatrix().toArray()
  23449. };
  23450. serializationObject.bones.push(serializedBone);
  23451. if (bone.animations && bone.animations.length > 0) {
  23452. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23453. }
  23454. }
  23455. return serializationObject;
  23456. };
  23457. var serializeParticleSystem = function (particleSystem) {
  23458. var serializationObject = {};
  23459. serializationObject.emitterId = particleSystem.emitter.id;
  23460. serializationObject.capacity = particleSystem.getCapacity();
  23461. if (particleSystem.particleTexture) {
  23462. serializationObject.textureName = particleSystem.particleTexture.name;
  23463. }
  23464. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23465. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23466. serializationObject.minSize = particleSystem.minSize;
  23467. serializationObject.maxSize = particleSystem.maxSize;
  23468. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23469. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23470. serializationObject.emitRate = particleSystem.emitRate;
  23471. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23472. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23473. serializationObject.gravity = particleSystem.gravity.asArray();
  23474. serializationObject.direction1 = particleSystem.direction1.asArray();
  23475. serializationObject.direction2 = particleSystem.direction2.asArray();
  23476. serializationObject.color1 = particleSystem.color1.asArray();
  23477. serializationObject.color2 = particleSystem.color2.asArray();
  23478. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23479. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23480. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23481. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23482. serializationObject.blendMode = particleSystem.blendMode;
  23483. return serializationObject;
  23484. };
  23485. var serializeLensFlareSystem = function (lensFlareSystem) {
  23486. var serializationObject = {};
  23487. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23488. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23489. serializationObject.flares = [];
  23490. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23491. var flare = lensFlareSystem.lensFlares[index];
  23492. serializationObject.flares.push({
  23493. size: flare.size,
  23494. position: flare.position,
  23495. color: flare.color.asArray(),
  23496. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23497. });
  23498. }
  23499. return serializationObject;
  23500. };
  23501. var serializeShadowGenerator = function (light) {
  23502. var serializationObject = {};
  23503. var shadowGenerator = light.getShadowGenerator();
  23504. serializationObject.lightId = light.id;
  23505. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23506. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23507. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23508. serializationObject.renderList = [];
  23509. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23510. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23511. serializationObject.renderList.push(mesh.id);
  23512. }
  23513. return serializationObject;
  23514. };
  23515. var serializedGeometries = [];
  23516. var serializeGeometry = function (geometry, serializationGeometries) {
  23517. if (serializedGeometries[geometry.id]) {
  23518. return;
  23519. }
  23520. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23521. serializationGeometries.boxes.push(serializeBox(geometry));
  23522. }
  23523. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23524. serializationGeometries.spheres.push(serializeSphere(geometry));
  23525. }
  23526. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23527. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23528. }
  23529. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23530. serializationGeometries.toruses.push(serializeTorus(geometry));
  23531. }
  23532. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23533. serializationGeometries.grounds.push(serializeGround(geometry));
  23534. }
  23535. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23536. serializationGeometries.planes.push(serializePlane(geometry));
  23537. }
  23538. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23539. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23540. }
  23541. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23542. throw new Error("Unknow primitive type");
  23543. }
  23544. else {
  23545. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23546. }
  23547. serializedGeometries[geometry.id] = true;
  23548. };
  23549. var serializeGeometryBase = function (geometry) {
  23550. var serializationObject = {};
  23551. serializationObject.id = geometry.id;
  23552. if (BABYLON.Tags.HasTags(geometry)) {
  23553. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23554. }
  23555. return serializationObject;
  23556. };
  23557. var serializeVertexData = function (vertexData) {
  23558. var serializationObject = serializeGeometryBase(vertexData);
  23559. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23560. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23561. }
  23562. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23563. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23564. }
  23565. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23566. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23567. }
  23568. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23569. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23570. }
  23571. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23572. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23573. }
  23574. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23575. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23576. serializationObject.matricesIndices._isExpanded = true;
  23577. }
  23578. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23579. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23580. }
  23581. serializationObject.indices = vertexData.getIndices();
  23582. return serializationObject;
  23583. };
  23584. var serializePrimitive = function (primitive) {
  23585. var serializationObject = serializeGeometryBase(primitive);
  23586. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23587. return serializationObject;
  23588. };
  23589. var serializeBox = function (box) {
  23590. var serializationObject = serializePrimitive(box);
  23591. serializationObject.size = box.size;
  23592. return serializationObject;
  23593. };
  23594. var serializeSphere = function (sphere) {
  23595. var serializationObject = serializePrimitive(sphere);
  23596. serializationObject.segments = sphere.segments;
  23597. serializationObject.diameter = sphere.diameter;
  23598. return serializationObject;
  23599. };
  23600. var serializeCylinder = function (cylinder) {
  23601. var serializationObject = serializePrimitive(cylinder);
  23602. serializationObject.height = cylinder.height;
  23603. serializationObject.diameterTop = cylinder.diameterTop;
  23604. serializationObject.diameterBottom = cylinder.diameterBottom;
  23605. serializationObject.tessellation = cylinder.tessellation;
  23606. return serializationObject;
  23607. };
  23608. var serializeTorus = function (torus) {
  23609. var serializationObject = serializePrimitive(torus);
  23610. serializationObject.diameter = torus.diameter;
  23611. serializationObject.thickness = torus.thickness;
  23612. serializationObject.tessellation = torus.tessellation;
  23613. return serializationObject;
  23614. };
  23615. var serializeGround = function (ground) {
  23616. var serializationObject = serializePrimitive(ground);
  23617. serializationObject.width = ground.width;
  23618. serializationObject.height = ground.height;
  23619. serializationObject.subdivisions = ground.subdivisions;
  23620. return serializationObject;
  23621. };
  23622. var serializePlane = function (plane) {
  23623. var serializationObject = serializePrimitive(plane);
  23624. serializationObject.size = plane.size;
  23625. return serializationObject;
  23626. };
  23627. var serializeTorusKnot = function (torusKnot) {
  23628. var serializationObject = serializePrimitive(torusKnot);
  23629. serializationObject.radius = torusKnot.radius;
  23630. serializationObject.tube = torusKnot.tube;
  23631. serializationObject.radialSegments = torusKnot.radialSegments;
  23632. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23633. serializationObject.p = torusKnot.p;
  23634. serializationObject.q = torusKnot.q;
  23635. return serializationObject;
  23636. };
  23637. var serializeMesh = function (mesh, serializationScene) {
  23638. var serializationObject = {};
  23639. serializationObject.name = mesh.name;
  23640. serializationObject.id = mesh.id;
  23641. if (BABYLON.Tags.HasTags(mesh)) {
  23642. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23643. }
  23644. serializationObject.position = mesh.position.asArray();
  23645. if (mesh.rotationQuaternion) {
  23646. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23647. }
  23648. else if (mesh.rotation) {
  23649. serializationObject.rotation = mesh.rotation.asArray();
  23650. }
  23651. serializationObject.scaling = mesh.scaling.asArray();
  23652. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23653. serializationObject.isEnabled = mesh.isEnabled();
  23654. serializationObject.isVisible = mesh.isVisible;
  23655. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23656. serializationObject.pickable = mesh.isPickable;
  23657. serializationObject.receiveShadows = mesh.receiveShadows;
  23658. serializationObject.billboardMode = mesh.billboardMode;
  23659. serializationObject.visibility = mesh.visibility;
  23660. serializationObject.checkCollisions = mesh.checkCollisions;
  23661. // Parent
  23662. if (mesh.parent) {
  23663. serializationObject.parentId = mesh.parent.id;
  23664. }
  23665. // Geometry
  23666. var geometry = mesh._geometry;
  23667. if (geometry) {
  23668. var geometryId = geometry.id;
  23669. serializationObject.geometryId = geometryId;
  23670. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23671. // 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
  23672. serializeGeometry(geometry, serializationScene.geometries);
  23673. }
  23674. // SubMeshes
  23675. serializationObject.subMeshes = [];
  23676. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23677. var subMesh = mesh.subMeshes[subIndex];
  23678. serializationObject.subMeshes.push({
  23679. materialIndex: subMesh.materialIndex,
  23680. verticesStart: subMesh.verticesStart,
  23681. verticesCount: subMesh.verticesCount,
  23682. indexStart: subMesh.indexStart,
  23683. indexCount: subMesh.indexCount
  23684. });
  23685. }
  23686. }
  23687. // Material
  23688. if (mesh.material) {
  23689. serializationObject.materialId = mesh.material.id;
  23690. }
  23691. else {
  23692. mesh.material = null;
  23693. }
  23694. // Skeleton
  23695. if (mesh.skeleton) {
  23696. serializationObject.skeletonId = mesh.skeleton.id;
  23697. }
  23698. // Physics
  23699. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23700. serializationObject.physicsMass = mesh.getPhysicsMass();
  23701. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23702. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23703. switch (mesh.getPhysicsImpostor()) {
  23704. case BABYLON.PhysicsEngine.BoxImpostor:
  23705. serializationObject.physicsImpostor = 1;
  23706. break;
  23707. case BABYLON.PhysicsEngine.SphereImpostor:
  23708. serializationObject.physicsImpostor = 2;
  23709. break;
  23710. }
  23711. }
  23712. // Instances
  23713. serializationObject.instances = [];
  23714. for (var index = 0; index < mesh.instances.length; index++) {
  23715. var instance = mesh.instances[index];
  23716. var serializationInstance = {
  23717. name: instance.name,
  23718. position: instance.position,
  23719. rotation: instance.rotation,
  23720. rotationQuaternion: instance.rotationQuaternion,
  23721. scaling: instance.scaling
  23722. };
  23723. serializationObject.instances.push(serializationInstance);
  23724. // Animations
  23725. appendAnimations(instance, serializationInstance);
  23726. }
  23727. // Animations
  23728. appendAnimations(mesh, serializationObject);
  23729. // Layer mask
  23730. serializationObject.layerMask = mesh.layerMask;
  23731. return serializationObject;
  23732. };
  23733. var SceneSerializer = (function () {
  23734. function SceneSerializer() {
  23735. }
  23736. SceneSerializer.Serialize = function (scene) {
  23737. var serializationObject = {};
  23738. // Scene
  23739. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23740. serializationObject.autoClear = scene.autoClear;
  23741. serializationObject.clearColor = scene.clearColor.asArray();
  23742. serializationObject.ambientColor = scene.ambientColor.asArray();
  23743. serializationObject.gravity = scene.gravity.asArray();
  23744. // Fog
  23745. if (scene.fogMode && scene.fogMode !== 0) {
  23746. serializationObject.fogMode = scene.fogMode;
  23747. serializationObject.fogColor = scene.fogColor.asArray();
  23748. serializationObject.fogStart = scene.fogStart;
  23749. serializationObject.fogEnd = scene.fogEnd;
  23750. serializationObject.fogDensity = scene.fogDensity;
  23751. }
  23752. // Lights
  23753. serializationObject.lights = [];
  23754. for (var index = 0; index < scene.lights.length; index++) {
  23755. var light = scene.lights[index];
  23756. serializationObject.lights.push(serializeLight(light));
  23757. }
  23758. // Cameras
  23759. serializationObject.cameras = [];
  23760. for (index = 0; index < scene.cameras.length; index++) {
  23761. var camera = scene.cameras[index];
  23762. serializationObject.cameras.push(serializeCamera(camera));
  23763. }
  23764. if (scene.activeCamera) {
  23765. serializationObject.activeCameraID = scene.activeCamera.id;
  23766. }
  23767. // Materials
  23768. serializationObject.materials = [];
  23769. serializationObject.multiMaterials = [];
  23770. for (index = 0; index < scene.materials.length; index++) {
  23771. var material = scene.materials[index];
  23772. if (material instanceof BABYLON.StandardMaterial) {
  23773. serializationObject.materials.push(serializeMaterial(material));
  23774. }
  23775. else if (material instanceof BABYLON.MultiMaterial) {
  23776. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23777. }
  23778. }
  23779. // Skeletons
  23780. serializationObject.skeletons = [];
  23781. for (index = 0; index < scene.skeletons.length; index++) {
  23782. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23783. }
  23784. // Geometries
  23785. serializationObject.geometries = {};
  23786. serializationObject.geometries.boxes = [];
  23787. serializationObject.geometries.spheres = [];
  23788. serializationObject.geometries.cylinders = [];
  23789. serializationObject.geometries.toruses = [];
  23790. serializationObject.geometries.grounds = [];
  23791. serializationObject.geometries.planes = [];
  23792. serializationObject.geometries.torusKnots = [];
  23793. serializationObject.geometries.vertexData = [];
  23794. serializedGeometries = [];
  23795. var geometries = scene.getGeometries();
  23796. for (index = 0; index < geometries.length; index++) {
  23797. var geometry = geometries[index];
  23798. if (geometry.isReady()) {
  23799. serializeGeometry(geometry, serializationObject.geometries);
  23800. }
  23801. }
  23802. // Meshes
  23803. serializationObject.meshes = [];
  23804. for (index = 0; index < scene.meshes.length; index++) {
  23805. var abstractMesh = scene.meshes[index];
  23806. if (abstractMesh instanceof BABYLON.Mesh) {
  23807. var mesh = abstractMesh;
  23808. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23809. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23810. }
  23811. }
  23812. }
  23813. // Particles Systems
  23814. serializationObject.particleSystems = [];
  23815. for (index = 0; index < scene.particleSystems.length; index++) {
  23816. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23817. }
  23818. // Lens flares
  23819. serializationObject.lensFlareSystems = [];
  23820. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23821. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23822. }
  23823. // Shadows
  23824. serializationObject.shadowGenerators = [];
  23825. for (index = 0; index < scene.lights.length; index++) {
  23826. light = scene.lights[index];
  23827. if (light.getShadowGenerator()) {
  23828. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23829. }
  23830. }
  23831. return serializationObject;
  23832. };
  23833. return SceneSerializer;
  23834. })();
  23835. BABYLON.SceneSerializer = SceneSerializer;
  23836. })(BABYLON || (BABYLON = {}));
  23837. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23838. var BABYLON;
  23839. (function (BABYLON) {
  23840. // Unique ID when we import meshes from Babylon to CSG
  23841. var currentCSGMeshId = 0;
  23842. // # class Vertex
  23843. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23844. // one to provide additional features like texture coordinates and vertex
  23845. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23846. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23847. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23848. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23849. // is not used anywhere else.
  23850. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23851. var Vertex = (function () {
  23852. function Vertex(pos, normal, uv) {
  23853. this.pos = pos;
  23854. this.normal = normal;
  23855. this.uv = uv;
  23856. }
  23857. Vertex.prototype.clone = function () {
  23858. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23859. };
  23860. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23861. // orientation of a polygon is flipped.
  23862. Vertex.prototype.flip = function () {
  23863. this.normal = this.normal.scale(-1);
  23864. };
  23865. // Create a new vertex between this vertex and `other` by linearly
  23866. // interpolating all properties using a parameter of `t`. Subclasses should
  23867. // override this to interpolate additional properties.
  23868. Vertex.prototype.interpolate = function (other, t) {
  23869. 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));
  23870. };
  23871. return Vertex;
  23872. })();
  23873. // # class Plane
  23874. // Represents a plane in 3D space.
  23875. var Plane = (function () {
  23876. function Plane(normal, w) {
  23877. this.normal = normal;
  23878. this.w = w;
  23879. }
  23880. Plane.FromPoints = function (a, b, c) {
  23881. var v0 = c.subtract(a);
  23882. var v1 = b.subtract(a);
  23883. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23884. return null;
  23885. }
  23886. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23887. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23888. };
  23889. Plane.prototype.clone = function () {
  23890. return new Plane(this.normal.clone(), this.w);
  23891. };
  23892. Plane.prototype.flip = function () {
  23893. this.normal.scaleInPlace(-1);
  23894. this.w = -this.w;
  23895. };
  23896. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23897. // fragments in the appropriate lists. Coplanar polygons go into either
  23898. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23899. // respect to this plane. Polygons in front or in back of this plane go into
  23900. // either `front` or `back`.
  23901. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23902. var COPLANAR = 0;
  23903. var FRONT = 1;
  23904. var BACK = 2;
  23905. var SPANNING = 3;
  23906. // Classify each point as well as the entire polygon into one of the above
  23907. // four classes.
  23908. var polygonType = 0;
  23909. var types = [];
  23910. for (var i = 0; i < polygon.vertices.length; i++) {
  23911. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23912. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23913. polygonType |= type;
  23914. types.push(type);
  23915. }
  23916. // Put the polygon in the correct list, splitting it when necessary.
  23917. switch (polygonType) {
  23918. case COPLANAR:
  23919. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23920. break;
  23921. case FRONT:
  23922. front.push(polygon);
  23923. break;
  23924. case BACK:
  23925. back.push(polygon);
  23926. break;
  23927. case SPANNING:
  23928. var f = [], b = [];
  23929. for (i = 0; i < polygon.vertices.length; i++) {
  23930. var j = (i + 1) % polygon.vertices.length;
  23931. var ti = types[i], tj = types[j];
  23932. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23933. if (ti != BACK)
  23934. f.push(vi);
  23935. if (ti != FRONT)
  23936. b.push(ti != BACK ? vi.clone() : vi);
  23937. if ((ti | tj) == SPANNING) {
  23938. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23939. var v = vi.interpolate(vj, t);
  23940. f.push(v);
  23941. b.push(v.clone());
  23942. }
  23943. }
  23944. if (f.length >= 3) {
  23945. var poly = new Polygon(f, polygon.shared);
  23946. if (poly.plane)
  23947. front.push(poly);
  23948. }
  23949. if (b.length >= 3) {
  23950. poly = new Polygon(b, polygon.shared);
  23951. if (poly.plane)
  23952. back.push(poly);
  23953. }
  23954. break;
  23955. }
  23956. };
  23957. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23958. // point is on the plane.
  23959. Plane.EPSILON = 1e-5;
  23960. return Plane;
  23961. })();
  23962. // # class Polygon
  23963. // Represents a convex polygon. The vertices used to initialize a polygon must
  23964. // be coplanar and form a convex loop.
  23965. //
  23966. // Each convex polygon has a `shared` property, which is shared between all
  23967. // polygons that are clones of each other or were split from the same polygon.
  23968. // This can be used to define per-polygon properties (such as surface color).
  23969. var Polygon = (function () {
  23970. function Polygon(vertices, shared) {
  23971. this.vertices = vertices;
  23972. this.shared = shared;
  23973. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23974. }
  23975. Polygon.prototype.clone = function () {
  23976. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23977. return new Polygon(vertices, this.shared);
  23978. };
  23979. Polygon.prototype.flip = function () {
  23980. this.vertices.reverse().map(function (v) { v.flip(); });
  23981. this.plane.flip();
  23982. };
  23983. return Polygon;
  23984. })();
  23985. // # class Node
  23986. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23987. // by picking a polygon to split along. That polygon (and all other coplanar
  23988. // polygons) are added directly to that node and the other polygons are added to
  23989. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23990. // no distinction between internal and leaf nodes.
  23991. var Node = (function () {
  23992. function Node(polygons) {
  23993. this.plane = null;
  23994. this.front = null;
  23995. this.back = null;
  23996. this.polygons = [];
  23997. if (polygons) {
  23998. this.build(polygons);
  23999. }
  24000. }
  24001. Node.prototype.clone = function () {
  24002. var node = new Node();
  24003. node.plane = this.plane && this.plane.clone();
  24004. node.front = this.front && this.front.clone();
  24005. node.back = this.back && this.back.clone();
  24006. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24007. return node;
  24008. };
  24009. // Convert solid space to empty space and empty space to solid space.
  24010. Node.prototype.invert = function () {
  24011. for (var i = 0; i < this.polygons.length; i++) {
  24012. this.polygons[i].flip();
  24013. }
  24014. if (this.plane) {
  24015. this.plane.flip();
  24016. }
  24017. if (this.front) {
  24018. this.front.invert();
  24019. }
  24020. if (this.back) {
  24021. this.back.invert();
  24022. }
  24023. var temp = this.front;
  24024. this.front = this.back;
  24025. this.back = temp;
  24026. };
  24027. // Recursively remove all polygons in `polygons` that are inside this BSP
  24028. // tree.
  24029. Node.prototype.clipPolygons = function (polygons) {
  24030. if (!this.plane)
  24031. return polygons.slice();
  24032. var front = [], back = [];
  24033. for (var i = 0; i < polygons.length; i++) {
  24034. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24035. }
  24036. if (this.front) {
  24037. front = this.front.clipPolygons(front);
  24038. }
  24039. if (this.back) {
  24040. back = this.back.clipPolygons(back);
  24041. }
  24042. else {
  24043. back = [];
  24044. }
  24045. return front.concat(back);
  24046. };
  24047. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24048. // `bsp`.
  24049. Node.prototype.clipTo = function (bsp) {
  24050. this.polygons = bsp.clipPolygons(this.polygons);
  24051. if (this.front)
  24052. this.front.clipTo(bsp);
  24053. if (this.back)
  24054. this.back.clipTo(bsp);
  24055. };
  24056. // Return a list of all polygons in this BSP tree.
  24057. Node.prototype.allPolygons = function () {
  24058. var polygons = this.polygons.slice();
  24059. if (this.front)
  24060. polygons = polygons.concat(this.front.allPolygons());
  24061. if (this.back)
  24062. polygons = polygons.concat(this.back.allPolygons());
  24063. return polygons;
  24064. };
  24065. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24066. // new polygons are filtered down to the bottom of the tree and become new
  24067. // nodes there. Each set of polygons is partitioned using the first polygon
  24068. // (no heuristic is used to pick a good split).
  24069. Node.prototype.build = function (polygons) {
  24070. if (!polygons.length)
  24071. return;
  24072. if (!this.plane)
  24073. this.plane = polygons[0].plane.clone();
  24074. var front = [], back = [];
  24075. for (var i = 0; i < polygons.length; i++) {
  24076. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24077. }
  24078. if (front.length) {
  24079. if (!this.front)
  24080. this.front = new Node();
  24081. this.front.build(front);
  24082. }
  24083. if (back.length) {
  24084. if (!this.back)
  24085. this.back = new Node();
  24086. this.back.build(back);
  24087. }
  24088. };
  24089. return Node;
  24090. })();
  24091. var CSG = (function () {
  24092. function CSG() {
  24093. this.polygons = new Array();
  24094. }
  24095. // Convert BABYLON.Mesh to BABYLON.CSG
  24096. CSG.FromMesh = function (mesh) {
  24097. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  24098. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  24099. if (mesh instanceof BABYLON.Mesh) {
  24100. mesh.computeWorldMatrix(true);
  24101. matrix = mesh.getWorldMatrix();
  24102. meshPosition = mesh.position.clone();
  24103. meshRotation = mesh.rotation.clone();
  24104. if (mesh.rotationQuaternion) {
  24105. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24106. }
  24107. meshScaling = mesh.scaling.clone();
  24108. }
  24109. else {
  24110. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24111. }
  24112. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24113. var subMeshes = mesh.subMeshes;
  24114. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24115. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24116. vertices = [];
  24117. for (var j = 0; j < 3; j++) {
  24118. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24119. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24120. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24121. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24122. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24123. vertex = new Vertex(position, normal, uv);
  24124. vertices.push(vertex);
  24125. }
  24126. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24127. // To handle the case of degenerated triangle
  24128. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24129. if (polygon.plane)
  24130. polygons.push(polygon);
  24131. }
  24132. }
  24133. var csg = CSG.FromPolygons(polygons);
  24134. csg.matrix = matrix;
  24135. csg.position = meshPosition;
  24136. csg.rotation = meshRotation;
  24137. csg.scaling = meshScaling;
  24138. csg.rotationQuaternion = meshRotationQuaternion;
  24139. currentCSGMeshId++;
  24140. return csg;
  24141. };
  24142. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24143. CSG.FromPolygons = function (polygons) {
  24144. var csg = new BABYLON.CSG();
  24145. csg.polygons = polygons;
  24146. return csg;
  24147. };
  24148. CSG.prototype.clone = function () {
  24149. var csg = new BABYLON.CSG();
  24150. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24151. csg.copyTransformAttributes(this);
  24152. return csg;
  24153. };
  24154. CSG.prototype.toPolygons = function () {
  24155. return this.polygons;
  24156. };
  24157. CSG.prototype.union = function (csg) {
  24158. var a = new Node(this.clone().polygons);
  24159. var b = new Node(csg.clone().polygons);
  24160. a.clipTo(b);
  24161. b.clipTo(a);
  24162. b.invert();
  24163. b.clipTo(a);
  24164. b.invert();
  24165. a.build(b.allPolygons());
  24166. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24167. };
  24168. CSG.prototype.unionInPlace = function (csg) {
  24169. var a = new Node(this.polygons);
  24170. var b = new Node(csg.polygons);
  24171. a.clipTo(b);
  24172. b.clipTo(a);
  24173. b.invert();
  24174. b.clipTo(a);
  24175. b.invert();
  24176. a.build(b.allPolygons());
  24177. this.polygons = a.allPolygons();
  24178. };
  24179. CSG.prototype.subtract = function (csg) {
  24180. var a = new Node(this.clone().polygons);
  24181. var b = new Node(csg.clone().polygons);
  24182. a.invert();
  24183. a.clipTo(b);
  24184. b.clipTo(a);
  24185. b.invert();
  24186. b.clipTo(a);
  24187. b.invert();
  24188. a.build(b.allPolygons());
  24189. a.invert();
  24190. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24191. };
  24192. CSG.prototype.subtractInPlace = function (csg) {
  24193. var a = new Node(this.polygons);
  24194. var b = new Node(csg.polygons);
  24195. a.invert();
  24196. a.clipTo(b);
  24197. b.clipTo(a);
  24198. b.invert();
  24199. b.clipTo(a);
  24200. b.invert();
  24201. a.build(b.allPolygons());
  24202. a.invert();
  24203. this.polygons = a.allPolygons();
  24204. };
  24205. CSG.prototype.intersect = function (csg) {
  24206. var a = new Node(this.clone().polygons);
  24207. var b = new Node(csg.clone().polygons);
  24208. a.invert();
  24209. b.clipTo(a);
  24210. b.invert();
  24211. a.clipTo(b);
  24212. b.clipTo(a);
  24213. a.build(b.allPolygons());
  24214. a.invert();
  24215. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24216. };
  24217. CSG.prototype.intersectInPlace = function (csg) {
  24218. var a = new Node(this.polygons);
  24219. var b = new Node(csg.polygons);
  24220. a.invert();
  24221. b.clipTo(a);
  24222. b.invert();
  24223. a.clipTo(b);
  24224. b.clipTo(a);
  24225. a.build(b.allPolygons());
  24226. a.invert();
  24227. this.polygons = a.allPolygons();
  24228. };
  24229. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24230. // not modified.
  24231. CSG.prototype.inverse = function () {
  24232. var csg = this.clone();
  24233. csg.inverseInPlace();
  24234. return csg;
  24235. };
  24236. CSG.prototype.inverseInPlace = function () {
  24237. this.polygons.map(function (p) { p.flip(); });
  24238. };
  24239. // This is used to keep meshes transformations so they can be restored
  24240. // when we build back a Babylon Mesh
  24241. // NB : All CSG operations are performed in world coordinates
  24242. CSG.prototype.copyTransformAttributes = function (csg) {
  24243. this.matrix = csg.matrix;
  24244. this.position = csg.position;
  24245. this.rotation = csg.rotation;
  24246. this.scaling = csg.scaling;
  24247. this.rotationQuaternion = csg.rotationQuaternion;
  24248. return this;
  24249. };
  24250. // Build Raw mesh from CSG
  24251. // Coordinates here are in world space
  24252. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24253. var matrix = this.matrix.clone();
  24254. matrix.invert();
  24255. 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;
  24256. if (keepSubMeshes) {
  24257. // Sort Polygons, since subMeshes are indices range
  24258. polygons.sort(function (a, b) {
  24259. if (a.shared.meshId === b.shared.meshId) {
  24260. return a.shared.subMeshId - b.shared.subMeshId;
  24261. }
  24262. else {
  24263. return a.shared.meshId - b.shared.meshId;
  24264. }
  24265. });
  24266. }
  24267. for (var i = 0, il = polygons.length; i < il; i++) {
  24268. polygon = polygons[i];
  24269. // Building SubMeshes
  24270. if (!subMesh_dict[polygon.shared.meshId]) {
  24271. subMesh_dict[polygon.shared.meshId] = {};
  24272. }
  24273. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24274. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24275. indexStart: +Infinity,
  24276. indexEnd: -Infinity,
  24277. materialIndex: polygon.shared.materialIndex
  24278. };
  24279. }
  24280. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24281. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24282. polygonIndices[0] = 0;
  24283. polygonIndices[1] = j - 1;
  24284. polygonIndices[2] = j;
  24285. for (var k = 0; k < 3; k++) {
  24286. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24287. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24288. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24289. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24290. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24291. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24292. // Check if 2 points can be merged
  24293. if (!(typeof vertex_idx !== 'undefined' &&
  24294. normals[vertex_idx * 3] === localNormal.x &&
  24295. normals[vertex_idx * 3 + 1] === localNormal.y &&
  24296. normals[vertex_idx * 3 + 2] === localNormal.z &&
  24297. uvs[vertex_idx * 2] === uv.x &&
  24298. uvs[vertex_idx * 2 + 1] === uv.y)) {
  24299. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24300. uvs.push(uv.x, uv.y);
  24301. normals.push(normal.x, normal.y, normal.z);
  24302. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24303. }
  24304. indices.push(vertex_idx);
  24305. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24306. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24307. currentIndex++;
  24308. }
  24309. }
  24310. }
  24311. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24312. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24313. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24314. mesh.setIndices(indices);
  24315. if (keepSubMeshes) {
  24316. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24317. var materialIndexOffset = 0, materialMaxIndex;
  24318. mesh.subMeshes.length = 0;
  24319. for (var m in subMesh_dict) {
  24320. materialMaxIndex = -1;
  24321. for (var sm in subMesh_dict[m]) {
  24322. subMesh_obj = subMesh_dict[m][sm];
  24323. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24324. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24325. }
  24326. materialIndexOffset += ++materialMaxIndex;
  24327. }
  24328. }
  24329. return mesh;
  24330. };
  24331. // Build Mesh from CSG taking material and transforms into account
  24332. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24333. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24334. mesh.material = material;
  24335. mesh.position.copyFrom(this.position);
  24336. mesh.rotation.copyFrom(this.rotation);
  24337. if (this.rotationQuaternion) {
  24338. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  24339. }
  24340. mesh.scaling.copyFrom(this.scaling);
  24341. mesh.computeWorldMatrix(true);
  24342. return mesh;
  24343. };
  24344. return CSG;
  24345. })();
  24346. BABYLON.CSG = CSG;
  24347. })(BABYLON || (BABYLON = {}));
  24348. //# sourceMappingURL=babylon.csg.js.map
  24349. var __extends = this.__extends || function (d, b) {
  24350. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24351. function __() { this.constructor = d; }
  24352. __.prototype = b.prototype;
  24353. d.prototype = new __();
  24354. };
  24355. var BABYLON;
  24356. (function (BABYLON) {
  24357. var VRDistortionCorrectionPostProcess = (function (_super) {
  24358. __extends(VRDistortionCorrectionPostProcess, _super);
  24359. //ANY
  24360. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24361. var _this = this;
  24362. _super.call(this, name, "vrDistortionCorrection", [
  24363. 'LensCenter',
  24364. 'Scale',
  24365. 'ScaleIn',
  24366. 'HmdWarpParam'
  24367. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24368. this._isRightEye = isRightEye;
  24369. this._distortionFactors = vrMetrics.distortionK;
  24370. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24371. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24372. this.onSizeChanged = function () {
  24373. _this.aspectRatio = _this.width * .5 / _this.height;
  24374. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24375. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24376. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24377. };
  24378. this.onApply = function (effect) {
  24379. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24380. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24381. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24382. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24383. };
  24384. }
  24385. return VRDistortionCorrectionPostProcess;
  24386. })(BABYLON.PostProcess);
  24387. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24388. })(BABYLON || (BABYLON = {}));
  24389. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24390. // Mainly based on these 2 articles :
  24391. // 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
  24392. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24393. var BABYLON;
  24394. (function (BABYLON) {
  24395. (function (JoystickAxis) {
  24396. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24397. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24398. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24399. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24400. var JoystickAxis = BABYLON.JoystickAxis;
  24401. var VirtualJoystick = (function () {
  24402. function VirtualJoystick(leftJoystick) {
  24403. var _this = this;
  24404. if (leftJoystick) {
  24405. this._leftJoystick = true;
  24406. }
  24407. else {
  24408. this._leftJoystick = false;
  24409. }
  24410. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24411. VirtualJoystick._globalJoystickIndex++;
  24412. // By default left & right arrow keys are moving the X
  24413. // and up & down keys are moving the Y
  24414. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24415. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24416. this.reverseLeftRight = false;
  24417. this.reverseUpDown = false;
  24418. // collections of pointers
  24419. this._touches = new BABYLON.SmartCollection();
  24420. this.deltaPosition = BABYLON.Vector3.Zero();
  24421. this._joystickSensibility = 25;
  24422. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24423. this._rotationSpeed = 25;
  24424. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24425. this._rotateOnAxisRelativeToMesh = false;
  24426. // injecting a canvas element on top of the canvas 3D game
  24427. if (!VirtualJoystick.vjCanvas) {
  24428. window.addEventListener("resize", function () {
  24429. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24430. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24431. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24432. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24433. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24434. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24435. }, false);
  24436. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24437. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24438. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24439. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24440. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24441. VirtualJoystick.vjCanvas.style.width = "100%";
  24442. VirtualJoystick.vjCanvas.style.height = "100%";
  24443. VirtualJoystick.vjCanvas.style.position = "absolute";
  24444. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24445. VirtualJoystick.vjCanvas.style.top = "0px";
  24446. VirtualJoystick.vjCanvas.style.left = "0px";
  24447. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24448. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24449. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24450. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24451. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24452. document.body.appendChild(VirtualJoystick.vjCanvas);
  24453. }
  24454. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24455. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24456. this.pressed = false;
  24457. // default joystick color
  24458. this._joystickColor = "cyan";
  24459. this._joystickPointerID = -1;
  24460. // current joystick position
  24461. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24462. // origin joystick position
  24463. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24464. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24465. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24466. _this._onPointerDown(evt);
  24467. }, false);
  24468. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24469. _this._onPointerMove(evt);
  24470. }, false);
  24471. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24472. _this._onPointerUp(evt);
  24473. }, false);
  24474. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24475. _this._onPointerUp(evt);
  24476. }, false);
  24477. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24478. evt.preventDefault(); // Disables system menu
  24479. }, false);
  24480. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24481. }
  24482. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24483. this._joystickSensibility = newJoystickSensibility;
  24484. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24485. };
  24486. VirtualJoystick.prototype._onPointerDown = function (e) {
  24487. var positionOnScreenCondition;
  24488. e.preventDefault();
  24489. if (this._leftJoystick === true) {
  24490. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24491. }
  24492. else {
  24493. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24494. }
  24495. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24496. // First contact will be dedicated to the virtual joystick
  24497. this._joystickPointerID = e.pointerId;
  24498. this._joystickPointerStartPos.x = e.clientX;
  24499. this._joystickPointerStartPos.y = e.clientY;
  24500. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24501. this._deltaJoystickVector.x = 0;
  24502. this._deltaJoystickVector.y = 0;
  24503. this.pressed = true;
  24504. this._touches.add(e.pointerId.toString(), e);
  24505. }
  24506. else {
  24507. // You can only trigger the action buttons with a joystick declared
  24508. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24509. this._action();
  24510. this._touches.add(e.pointerId.toString(), e);
  24511. }
  24512. }
  24513. };
  24514. VirtualJoystick.prototype._onPointerMove = function (e) {
  24515. // If the current pointer is the one associated to the joystick (first touch contact)
  24516. if (this._joystickPointerID == e.pointerId) {
  24517. this._joystickPointerPos.x = e.clientX;
  24518. this._joystickPointerPos.y = e.clientY;
  24519. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24520. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24521. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24522. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24523. switch (this._axisTargetedByLeftAndRight) {
  24524. case JoystickAxis.X:
  24525. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24526. break;
  24527. case JoystickAxis.Y:
  24528. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24529. break;
  24530. case JoystickAxis.Z:
  24531. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24532. break;
  24533. }
  24534. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24535. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24536. switch (this._axisTargetedByUpAndDown) {
  24537. case JoystickAxis.X:
  24538. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24539. break;
  24540. case JoystickAxis.Y:
  24541. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24542. break;
  24543. case JoystickAxis.Z:
  24544. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24545. break;
  24546. }
  24547. }
  24548. else {
  24549. if (this._touches.item(e.pointerId.toString())) {
  24550. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24551. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24552. }
  24553. }
  24554. };
  24555. VirtualJoystick.prototype._onPointerUp = function (e) {
  24556. this._clearCanvas();
  24557. if (this._joystickPointerID == e.pointerId) {
  24558. this._joystickPointerID = -1;
  24559. this.pressed = false;
  24560. }
  24561. this._deltaJoystickVector.x = 0;
  24562. this._deltaJoystickVector.y = 0;
  24563. this._touches.remove(e.pointerId.toString());
  24564. };
  24565. /**
  24566. * Change the color of the virtual joystick
  24567. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24568. */
  24569. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24570. this._joystickColor = newColor;
  24571. };
  24572. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24573. this._action = action;
  24574. };
  24575. // Define which axis you'd like to control for left & right
  24576. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24577. switch (axis) {
  24578. case JoystickAxis.X:
  24579. case JoystickAxis.Y:
  24580. case JoystickAxis.Z:
  24581. this._axisTargetedByLeftAndRight = axis;
  24582. break;
  24583. default:
  24584. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24585. break;
  24586. }
  24587. };
  24588. // Define which axis you'd like to control for up & down
  24589. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24590. switch (axis) {
  24591. case JoystickAxis.X:
  24592. case JoystickAxis.Y:
  24593. case JoystickAxis.Z:
  24594. this._axisTargetedByUpAndDown = axis;
  24595. break;
  24596. default:
  24597. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24598. break;
  24599. }
  24600. };
  24601. VirtualJoystick.prototype._clearCanvas = function () {
  24602. if (this._leftJoystick) {
  24603. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24604. }
  24605. else {
  24606. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24607. }
  24608. };
  24609. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24610. var _this = this;
  24611. if (this.pressed) {
  24612. this._clearCanvas();
  24613. this._touches.forEach(function (touch) {
  24614. if (touch.pointerId === _this._joystickPointerID) {
  24615. VirtualJoystick.vjCanvasContext.beginPath();
  24616. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24617. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24618. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24619. VirtualJoystick.vjCanvasContext.stroke();
  24620. VirtualJoystick.vjCanvasContext.beginPath();
  24621. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24622. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24623. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24624. VirtualJoystick.vjCanvasContext.stroke();
  24625. VirtualJoystick.vjCanvasContext.beginPath();
  24626. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24627. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24628. VirtualJoystick.vjCanvasContext.stroke();
  24629. }
  24630. else {
  24631. VirtualJoystick.vjCanvasContext.beginPath();
  24632. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24633. VirtualJoystick.vjCanvasContext.beginPath();
  24634. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24635. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24636. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24637. VirtualJoystick.vjCanvasContext.stroke();
  24638. }
  24639. ;
  24640. });
  24641. }
  24642. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24643. };
  24644. VirtualJoystick.prototype.releaseCanvas = function () {
  24645. if (VirtualJoystick.vjCanvas) {
  24646. document.body.removeChild(VirtualJoystick.vjCanvas);
  24647. VirtualJoystick.vjCanvas = null;
  24648. }
  24649. };
  24650. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24651. VirtualJoystick._globalJoystickIndex = 0;
  24652. return VirtualJoystick;
  24653. })();
  24654. BABYLON.VirtualJoystick = VirtualJoystick;
  24655. })(BABYLON || (BABYLON = {}));
  24656. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24657. var __extends = this.__extends || function (d, b) {
  24658. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24659. function __() { this.constructor = d; }
  24660. __.prototype = b.prototype;
  24661. d.prototype = new __();
  24662. };
  24663. var BABYLON;
  24664. (function (BABYLON) {
  24665. // We're mainly based on the logic defined into the FreeCamera code
  24666. var VirtualJoysticksCamera = (function (_super) {
  24667. __extends(VirtualJoysticksCamera, _super);
  24668. function VirtualJoysticksCamera(name, position, scene) {
  24669. _super.call(this, name, position, scene);
  24670. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24671. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  24672. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  24673. this._leftjoystick.setJoystickSensibility(0.15);
  24674. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24675. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  24676. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  24677. this._rightjoystick.reverseUpDown = true;
  24678. this._rightjoystick.setJoystickSensibility(0.05);
  24679. this._rightjoystick.setJoystickColor("yellow");
  24680. }
  24681. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24682. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24683. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24684. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24685. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24686. if (!this._leftjoystick.pressed) {
  24687. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24688. }
  24689. if (!this._rightjoystick.pressed) {
  24690. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24691. }
  24692. _super.prototype._checkInputs.call(this);
  24693. };
  24694. VirtualJoysticksCamera.prototype.dispose = function () {
  24695. this._leftjoystick.releaseCanvas();
  24696. _super.prototype.dispose.call(this);
  24697. };
  24698. return VirtualJoysticksCamera;
  24699. })(BABYLON.FreeCamera);
  24700. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24701. })(BABYLON || (BABYLON = {}));
  24702. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24703. var __extends = this.__extends || function (d, b) {
  24704. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24705. function __() { this.constructor = d; }
  24706. __.prototype = b.prototype;
  24707. d.prototype = new __();
  24708. };
  24709. var BABYLON;
  24710. (function (BABYLON) {
  24711. var ShaderMaterial = (function (_super) {
  24712. __extends(ShaderMaterial, _super);
  24713. function ShaderMaterial(name, scene, shaderPath, options) {
  24714. _super.call(this, name, scene);
  24715. this._textures = new Array();
  24716. this._floats = new Array();
  24717. this._floatsArrays = {};
  24718. this._colors3 = new Array();
  24719. this._colors4 = new Array();
  24720. this._vectors2 = new Array();
  24721. this._vectors3 = new Array();
  24722. this._matrices = new Array();
  24723. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24724. this._shaderPath = shaderPath;
  24725. options.needAlphaBlending = options.needAlphaBlending || false;
  24726. options.needAlphaTesting = options.needAlphaTesting || false;
  24727. options.attributes = options.attributes || ["position", "normal", "uv"];
  24728. options.uniforms = options.uniforms || ["worldViewProjection"];
  24729. options.samplers = options.samplers || [];
  24730. this._options = options;
  24731. }
  24732. ShaderMaterial.prototype.needAlphaBlending = function () {
  24733. return this._options.needAlphaBlending;
  24734. };
  24735. ShaderMaterial.prototype.needAlphaTesting = function () {
  24736. return this._options.needAlphaTesting;
  24737. };
  24738. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24739. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24740. this._options.uniforms.push(uniformName);
  24741. }
  24742. };
  24743. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24744. if (this._options.samplers.indexOf(name) === -1) {
  24745. this._options.samplers.push(name);
  24746. }
  24747. this._textures[name] = texture;
  24748. return this;
  24749. };
  24750. ShaderMaterial.prototype.setFloat = function (name, value) {
  24751. this._checkUniform(name);
  24752. this._floats[name] = value;
  24753. return this;
  24754. };
  24755. ShaderMaterial.prototype.setFloats = function (name, value) {
  24756. this._checkUniform(name);
  24757. this._floatsArrays[name] = value;
  24758. return this;
  24759. };
  24760. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24761. this._checkUniform(name);
  24762. this._colors3[name] = value;
  24763. return this;
  24764. };
  24765. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24766. this._checkUniform(name);
  24767. this._colors4[name] = value;
  24768. return this;
  24769. };
  24770. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24771. this._checkUniform(name);
  24772. this._vectors2[name] = value;
  24773. return this;
  24774. };
  24775. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24776. this._checkUniform(name);
  24777. this._vectors3[name] = value;
  24778. return this;
  24779. };
  24780. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24781. this._checkUniform(name);
  24782. this._matrices[name] = value;
  24783. return this;
  24784. };
  24785. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24786. var scene = this.getScene();
  24787. var engine = scene.getEngine();
  24788. if (!this.checkReadyOnEveryCall) {
  24789. if (this._renderId === scene.getRenderId()) {
  24790. return true;
  24791. }
  24792. }
  24793. // Instances
  24794. var defines = [];
  24795. var fallbacks = new BABYLON.EffectFallbacks();
  24796. if (useInstances) {
  24797. defines.push("#define INSTANCES");
  24798. }
  24799. // Bones
  24800. if (mesh && mesh.useBones) {
  24801. defines.push("#define BONES");
  24802. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24803. defines.push("#define BONES4");
  24804. fallbacks.addFallback(0, "BONES4");
  24805. }
  24806. // Alpha test
  24807. if (engine.getAlphaTesting()) {
  24808. defines.push("#define ALPHATEST");
  24809. }
  24810. var previousEffect = this._effect;
  24811. var join = defines.join("\n");
  24812. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24813. if (!this._effect.isReady()) {
  24814. return false;
  24815. }
  24816. if (previousEffect !== this._effect) {
  24817. scene.resetCachedMaterial();
  24818. }
  24819. this._renderId = scene.getRenderId();
  24820. return true;
  24821. };
  24822. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24823. var scene = this.getScene();
  24824. if (this._options.uniforms.indexOf("world") !== -1) {
  24825. this._effect.setMatrix("world", world);
  24826. }
  24827. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24828. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24829. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24830. }
  24831. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24832. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24833. }
  24834. };
  24835. ShaderMaterial.prototype.bind = function (world, mesh) {
  24836. // Std values
  24837. this.bindOnlyWorldMatrix(world);
  24838. if (this.getScene().getCachedMaterial() !== this) {
  24839. if (this._options.uniforms.indexOf("view") !== -1) {
  24840. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24841. }
  24842. if (this._options.uniforms.indexOf("projection") !== -1) {
  24843. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24844. }
  24845. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24846. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24847. }
  24848. // Bones
  24849. if (mesh && mesh.useBones) {
  24850. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24851. }
  24852. // Texture
  24853. for (var name in this._textures) {
  24854. this._effect.setTexture(name, this._textures[name]);
  24855. }
  24856. // Float
  24857. for (name in this._floats) {
  24858. this._effect.setFloat(name, this._floats[name]);
  24859. }
  24860. // Float s
  24861. for (name in this._floatsArrays) {
  24862. this._effect.setArray(name, this._floatsArrays[name]);
  24863. }
  24864. // Color3
  24865. for (name in this._colors3) {
  24866. this._effect.setColor3(name, this._colors3[name]);
  24867. }
  24868. // Color4
  24869. for (name in this._colors4) {
  24870. var color = this._colors4[name];
  24871. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24872. }
  24873. // Vector2
  24874. for (name in this._vectors2) {
  24875. this._effect.setVector2(name, this._vectors2[name]);
  24876. }
  24877. // Vector3
  24878. for (name in this._vectors3) {
  24879. this._effect.setVector3(name, this._vectors3[name]);
  24880. }
  24881. // Matrix
  24882. for (name in this._matrices) {
  24883. this._effect.setMatrix(name, this._matrices[name]);
  24884. }
  24885. }
  24886. _super.prototype.bind.call(this, world, mesh);
  24887. };
  24888. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24889. for (var name in this._textures) {
  24890. this._textures[name].dispose();
  24891. }
  24892. this._textures = [];
  24893. _super.prototype.dispose.call(this, forceDisposeEffect);
  24894. };
  24895. return ShaderMaterial;
  24896. })(BABYLON.Material);
  24897. BABYLON.ShaderMaterial = ShaderMaterial;
  24898. })(BABYLON || (BABYLON = {}));
  24899. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24900. var BABYLON;
  24901. (function (BABYLON) {
  24902. var VertexData = (function () {
  24903. function VertexData() {
  24904. }
  24905. VertexData.prototype.set = function (data, kind) {
  24906. switch (kind) {
  24907. case BABYLON.VertexBuffer.PositionKind:
  24908. this.positions = data;
  24909. break;
  24910. case BABYLON.VertexBuffer.NormalKind:
  24911. this.normals = data;
  24912. break;
  24913. case BABYLON.VertexBuffer.UVKind:
  24914. this.uvs = data;
  24915. break;
  24916. case BABYLON.VertexBuffer.UV2Kind:
  24917. this.uv2s = data;
  24918. break;
  24919. case BABYLON.VertexBuffer.ColorKind:
  24920. this.colors = data;
  24921. break;
  24922. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24923. this.matricesIndices = data;
  24924. break;
  24925. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24926. this.matricesWeights = data;
  24927. break;
  24928. }
  24929. };
  24930. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24931. this._applyTo(mesh, updatable);
  24932. };
  24933. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24934. this._applyTo(geometry, updatable);
  24935. };
  24936. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24937. this._update(mesh);
  24938. };
  24939. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24940. this._update(geometry);
  24941. };
  24942. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24943. if (this.positions) {
  24944. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24945. }
  24946. if (this.normals) {
  24947. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24948. }
  24949. if (this.uvs) {
  24950. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24951. }
  24952. if (this.uv2s) {
  24953. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24954. }
  24955. if (this.colors) {
  24956. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24957. }
  24958. if (this.matricesIndices) {
  24959. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24960. }
  24961. if (this.matricesWeights) {
  24962. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24963. }
  24964. if (this.indices) {
  24965. meshOrGeometry.setIndices(this.indices);
  24966. }
  24967. };
  24968. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24969. if (this.positions) {
  24970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24971. }
  24972. if (this.normals) {
  24973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24974. }
  24975. if (this.uvs) {
  24976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24977. }
  24978. if (this.uv2s) {
  24979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24980. }
  24981. if (this.colors) {
  24982. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24983. }
  24984. if (this.matricesIndices) {
  24985. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24986. }
  24987. if (this.matricesWeights) {
  24988. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24989. }
  24990. if (this.indices) {
  24991. meshOrGeometry.setIndices(this.indices);
  24992. }
  24993. };
  24994. VertexData.prototype.transform = function (matrix) {
  24995. var transformed = BABYLON.Vector3.Zero();
  24996. if (this.positions) {
  24997. var position = BABYLON.Vector3.Zero();
  24998. for (var index = 0; index < this.positions.length; index += 3) {
  24999. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25000. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25001. this.positions[index] = transformed.x;
  25002. this.positions[index + 1] = transformed.y;
  25003. this.positions[index + 2] = transformed.z;
  25004. }
  25005. }
  25006. if (this.normals) {
  25007. var normal = BABYLON.Vector3.Zero();
  25008. for (index = 0; index < this.normals.length; index += 3) {
  25009. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25010. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25011. this.normals[index] = transformed.x;
  25012. this.normals[index + 1] = transformed.y;
  25013. this.normals[index + 2] = transformed.z;
  25014. }
  25015. }
  25016. };
  25017. VertexData.prototype.merge = function (other) {
  25018. if (other.indices) {
  25019. if (!this.indices) {
  25020. this.indices = [];
  25021. }
  25022. var offset = this.positions ? this.positions.length / 3 : 0;
  25023. for (var index = 0; index < other.indices.length; index++) {
  25024. this.indices.push(other.indices[index] + offset);
  25025. }
  25026. }
  25027. if (other.positions) {
  25028. if (!this.positions) {
  25029. this.positions = [];
  25030. }
  25031. for (index = 0; index < other.positions.length; index++) {
  25032. this.positions.push(other.positions[index]);
  25033. }
  25034. }
  25035. if (other.normals) {
  25036. if (!this.normals) {
  25037. this.normals = [];
  25038. }
  25039. for (index = 0; index < other.normals.length; index++) {
  25040. this.normals.push(other.normals[index]);
  25041. }
  25042. }
  25043. if (other.uvs) {
  25044. if (!this.uvs) {
  25045. this.uvs = [];
  25046. }
  25047. for (index = 0; index < other.uvs.length; index++) {
  25048. this.uvs.push(other.uvs[index]);
  25049. }
  25050. }
  25051. if (other.uv2s) {
  25052. if (!this.uv2s) {
  25053. this.uv2s = [];
  25054. }
  25055. for (index = 0; index < other.uv2s.length; index++) {
  25056. this.uv2s.push(other.uv2s[index]);
  25057. }
  25058. }
  25059. if (other.matricesIndices) {
  25060. if (!this.matricesIndices) {
  25061. this.matricesIndices = [];
  25062. }
  25063. for (index = 0; index < other.matricesIndices.length; index++) {
  25064. this.matricesIndices.push(other.matricesIndices[index]);
  25065. }
  25066. }
  25067. if (other.matricesWeights) {
  25068. if (!this.matricesWeights) {
  25069. this.matricesWeights = [];
  25070. }
  25071. for (index = 0; index < other.matricesWeights.length; index++) {
  25072. this.matricesWeights.push(other.matricesWeights[index]);
  25073. }
  25074. }
  25075. if (other.colors) {
  25076. if (!this.colors) {
  25077. this.colors = [];
  25078. }
  25079. for (index = 0; index < other.colors.length; index++) {
  25080. this.colors.push(other.colors[index]);
  25081. }
  25082. }
  25083. };
  25084. // Statics
  25085. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  25086. return VertexData._ExtractFrom(mesh, copyWhenShared);
  25087. };
  25088. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  25089. return VertexData._ExtractFrom(geometry, copyWhenShared);
  25090. };
  25091. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  25092. var result = new VertexData();
  25093. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25094. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  25095. }
  25096. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25097. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  25098. }
  25099. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25100. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  25101. }
  25102. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25103. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  25104. }
  25105. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25106. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  25107. }
  25108. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25109. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  25110. }
  25111. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25112. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  25113. }
  25114. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25115. return result;
  25116. };
  25117. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  25118. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25119. closeArray = closeArray || false;
  25120. closePath = closePath || false;
  25121. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25122. offset = offset || defaultOffset;
  25123. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25124. var positions = [];
  25125. var indices = [];
  25126. var normals = [];
  25127. var uvs = [];
  25128. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25129. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25130. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25131. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25132. var minlg; // minimal length among all paths from pathArray
  25133. var lg = []; // array of path lengths : nb of vertex per path
  25134. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  25135. var p; // path iterator
  25136. var i; // point iterator
  25137. var j; // point iterator
  25138. // if single path in pathArray
  25139. if (pathArray.length < 2) {
  25140. var ar1 = [];
  25141. var ar2 = [];
  25142. for (i = 0; i < pathArray[0].length - offset; i++) {
  25143. ar1.push(pathArray[0][i]);
  25144. ar2.push(pathArray[0][i + offset]);
  25145. }
  25146. pathArray = [ar1, ar2];
  25147. }
  25148. // positions and horizontal distances (u)
  25149. var idc = 0;
  25150. minlg = pathArray[0].length;
  25151. for (p = 0; p < pathArray.length; p++) {
  25152. uTotalDistance[p] = 0;
  25153. us[p] = [0];
  25154. var path = pathArray[p];
  25155. var l = path.length;
  25156. minlg = (minlg < l) ? minlg : l;
  25157. lg[p] = l;
  25158. idx[p] = idc;
  25159. j = 0;
  25160. while (j < l) {
  25161. positions.push(path[j].x, path[j].y, path[j].z);
  25162. if (j > 0) {
  25163. var vectlg = path[j].subtract(path[j - 1]).length();
  25164. var dist = vectlg + uTotalDistance[p];
  25165. us[p].push(dist);
  25166. uTotalDistance[p] = dist;
  25167. }
  25168. j++;
  25169. }
  25170. if (closePath) {
  25171. vectlg = path[0].subtract(path[j - 1]).length();
  25172. dist = vectlg + uTotalDistance[p];
  25173. uTotalDistance[p] = dist;
  25174. }
  25175. idc += l;
  25176. }
  25177. // vertical distances (v)
  25178. for (i = 0; i < minlg; i++) {
  25179. vTotalDistance[i] = 0;
  25180. vs[i] = [0];
  25181. var path1;
  25182. var path2;
  25183. for (p = 0; p < pathArray.length - 1; p++) {
  25184. path1 = pathArray[p];
  25185. path2 = pathArray[p + 1];
  25186. vectlg = path2[i].subtract(path1[i]).length();
  25187. dist = vectlg + vTotalDistance[i];
  25188. vs[i].push(dist);
  25189. vTotalDistance[i] = dist;
  25190. }
  25191. if (closeArray) {
  25192. path1 = pathArray[p];
  25193. path2 = pathArray[0];
  25194. vectlg = path2[i].subtract(path1[i]).length();
  25195. dist = vectlg + vTotalDistance[i];
  25196. vTotalDistance[i] = dist;
  25197. }
  25198. }
  25199. // uvs
  25200. var u;
  25201. var v;
  25202. for (p = 0; p < pathArray.length; p++) {
  25203. for (i = 0; i < minlg; i++) {
  25204. u = us[p][i] / uTotalDistance[p];
  25205. v = vs[i][p] / vTotalDistance[i];
  25206. uvs.push(u, v);
  25207. }
  25208. }
  25209. // indices
  25210. p = 0; // path index
  25211. var pi = 0; // positions array index
  25212. var l1 = lg[p] - 1; // path1 length
  25213. var l2 = lg[p + 1] - 1; // path2 length
  25214. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25215. var shft = idx[1] - idx[0]; // shift
  25216. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  25217. var t1; // two consecutive triangles, so 4 points : point1
  25218. var t2; // point2
  25219. var t3; // point3
  25220. var t4; // point4
  25221. while (pi <= min && p < path1nb) {
  25222. // 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
  25223. t1 = pi;
  25224. t2 = pi + shft;
  25225. t3 = pi + 1;
  25226. t4 = pi + shft + 1;
  25227. indices.push(pi, pi + shft, pi + 1);
  25228. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25229. pi += 1;
  25230. if (pi === min) {
  25231. if (closePath) {
  25232. indices.push(pi, pi + shft, idx[p]);
  25233. indices.push(idx[p] + shft, idx[p], pi + shft);
  25234. t3 = idx[p];
  25235. t4 = idx[p] + shft;
  25236. }
  25237. p++;
  25238. if (p === lg.length - 1) {
  25239. shft = idx[0] - idx[p];
  25240. l1 = lg[p] - 1;
  25241. l2 = lg[0] - 1;
  25242. }
  25243. else {
  25244. shft = idx[p + 1] - idx[p];
  25245. l1 = lg[p] - 1;
  25246. l2 = lg[p + 1] - 1;
  25247. }
  25248. pi = idx[p];
  25249. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25250. }
  25251. }
  25252. // normals
  25253. VertexData.ComputeNormals(positions, indices, normals);
  25254. // sides
  25255. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25256. // Result
  25257. var vertexData = new VertexData();
  25258. vertexData.indices = indices;
  25259. vertexData.positions = positions;
  25260. vertexData.normals = normals;
  25261. vertexData.uvs = uvs;
  25262. return vertexData;
  25263. };
  25264. VertexData.CreateBox = function (size, sideOrientation) {
  25265. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25266. var normalsSource = [
  25267. new BABYLON.Vector3(0, 0, 1),
  25268. new BABYLON.Vector3(0, 0, -1),
  25269. new BABYLON.Vector3(1, 0, 0),
  25270. new BABYLON.Vector3(-1, 0, 0),
  25271. new BABYLON.Vector3(0, 1, 0),
  25272. new BABYLON.Vector3(0, -1, 0)
  25273. ];
  25274. var indices = [];
  25275. var positions = [];
  25276. var normals = [];
  25277. var uvs = [];
  25278. size = size || 1;
  25279. // Create each face in turn.
  25280. for (var index = 0; index < normalsSource.length; index++) {
  25281. var normal = normalsSource[index];
  25282. // Get two vectors perpendicular to the face normal and to each other.
  25283. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25284. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25285. // Six indices (two triangles) per face.
  25286. var verticesLength = positions.length / 3;
  25287. indices.push(verticesLength);
  25288. indices.push(verticesLength + 1);
  25289. indices.push(verticesLength + 2);
  25290. indices.push(verticesLength);
  25291. indices.push(verticesLength + 2);
  25292. indices.push(verticesLength + 3);
  25293. // Four vertices per face.
  25294. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25295. positions.push(vertex.x, vertex.y, vertex.z);
  25296. normals.push(normal.x, normal.y, normal.z);
  25297. uvs.push(1.0, 1.0);
  25298. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25299. positions.push(vertex.x, vertex.y, vertex.z);
  25300. normals.push(normal.x, normal.y, normal.z);
  25301. uvs.push(0.0, 1.0);
  25302. vertex = normal.add(side1).add(side2).scale(size / 2);
  25303. positions.push(vertex.x, vertex.y, vertex.z);
  25304. normals.push(normal.x, normal.y, normal.z);
  25305. uvs.push(0.0, 0.0);
  25306. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25307. positions.push(vertex.x, vertex.y, vertex.z);
  25308. normals.push(normal.x, normal.y, normal.z);
  25309. uvs.push(1.0, 0.0);
  25310. }
  25311. // sides
  25312. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25313. // Result
  25314. var vertexData = new VertexData();
  25315. vertexData.indices = indices;
  25316. vertexData.positions = positions;
  25317. vertexData.normals = normals;
  25318. vertexData.uvs = uvs;
  25319. return vertexData;
  25320. };
  25321. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25322. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25323. segments = segments || 32;
  25324. diameter = diameter || 1;
  25325. var radius = diameter / 2;
  25326. var totalZRotationSteps = 2 + segments;
  25327. var totalYRotationSteps = 2 * totalZRotationSteps;
  25328. var indices = [];
  25329. var positions = [];
  25330. var normals = [];
  25331. var uvs = [];
  25332. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25333. var normalizedZ = zRotationStep / totalZRotationSteps;
  25334. var angleZ = (normalizedZ * Math.PI);
  25335. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25336. var normalizedY = yRotationStep / totalYRotationSteps;
  25337. var angleY = normalizedY * Math.PI * 2;
  25338. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25339. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25340. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25341. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25342. var vertex = complete.scale(radius);
  25343. var normal = BABYLON.Vector3.Normalize(vertex);
  25344. positions.push(vertex.x, vertex.y, vertex.z);
  25345. normals.push(normal.x, normal.y, normal.z);
  25346. uvs.push(normalizedZ, normalizedY);
  25347. }
  25348. if (zRotationStep > 0) {
  25349. var verticesCount = positions.length / 3;
  25350. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25351. indices.push((firstIndex));
  25352. indices.push((firstIndex + 1));
  25353. indices.push(firstIndex + totalYRotationSteps + 1);
  25354. indices.push((firstIndex + totalYRotationSteps + 1));
  25355. indices.push((firstIndex + 1));
  25356. indices.push((firstIndex + totalYRotationSteps + 2));
  25357. }
  25358. }
  25359. }
  25360. // Sides
  25361. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25362. // Result
  25363. var vertexData = new VertexData();
  25364. vertexData.indices = indices;
  25365. vertexData.positions = positions;
  25366. vertexData.normals = normals;
  25367. vertexData.uvs = uvs;
  25368. return vertexData;
  25369. };
  25370. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25371. if (subdivisions === void 0) { subdivisions = 1; }
  25372. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25373. var radiusTop = diameterTop / 2;
  25374. var radiusBottom = diameterBottom / 2;
  25375. var indices = [];
  25376. var positions = [];
  25377. var normals = [];
  25378. var uvs = [];
  25379. height = height || 1;
  25380. diameterTop = diameterTop || 0.5;
  25381. diameterBottom = diameterBottom || 1;
  25382. tessellation = tessellation || 16;
  25383. subdivisions = subdivisions || 1;
  25384. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25385. var getCircleVector = function (i) {
  25386. var angle = (i * 2.0 * Math.PI / tessellation);
  25387. var dx = Math.cos(angle);
  25388. var dz = Math.sin(angle);
  25389. return new BABYLON.Vector3(dx, 0, dz);
  25390. };
  25391. var createCylinderCap = function (isTop) {
  25392. var radius = isTop ? radiusTop : radiusBottom;
  25393. if (radius === 0) {
  25394. return;
  25395. }
  25396. var vbase = positions.length / 3;
  25397. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25398. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25399. if (!isTop) {
  25400. offset.scaleInPlace(-1);
  25401. textureScale.x = -textureScale.x;
  25402. }
  25403. // Positions, normals & uvs
  25404. for (var i = 0; i < tessellation; i++) {
  25405. var circleVector = getCircleVector(i);
  25406. var position = circleVector.scale(radius).add(offset);
  25407. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25408. positions.push(position.x, position.y, position.z);
  25409. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25410. }
  25411. // Indices
  25412. for (i = 0; i < tessellation - 2; i++) {
  25413. if (!isTop) {
  25414. indices.push(vbase);
  25415. indices.push(vbase + (i + 2) % tessellation);
  25416. indices.push(vbase + (i + 1) % tessellation);
  25417. }
  25418. else {
  25419. indices.push(vbase);
  25420. indices.push(vbase + (i + 1) % tessellation);
  25421. indices.push(vbase + (i + 2) % tessellation);
  25422. }
  25423. }
  25424. };
  25425. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25426. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25427. var stride = tessellation + 1;
  25428. // Positions, normals & uvs
  25429. for (var i = 0; i <= tessellation; i++) {
  25430. var circleVector = getCircleVector(i);
  25431. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25432. var position, radius = radiusBottom;
  25433. for (var s = 0; s <= subdivisions; s++) {
  25434. // Update variables
  25435. position = circleVector.scale(radius);
  25436. position.addInPlace(base.add(offset.scale(s)));
  25437. textureCoordinate.y += 1 / subdivisions;
  25438. radius += (radiusTop - radiusBottom) / subdivisions;
  25439. // Push in arrays
  25440. positions.push(position.x, position.y, position.z);
  25441. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25442. }
  25443. }
  25444. subdivisions += 1;
  25445. // Indices
  25446. for (s = 0; s < subdivisions - 1; s++) {
  25447. for (i = 0; i <= tessellation; i++) {
  25448. indices.push(i * subdivisions + s);
  25449. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25450. indices.push(i * subdivisions + (s + 1));
  25451. indices.push(i * subdivisions + (s + 1));
  25452. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25453. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25454. }
  25455. }
  25456. // Create flat triangle fan caps to seal the top and bottom.
  25457. createCylinderCap(true);
  25458. createCylinderCap(false);
  25459. // Normals
  25460. VertexData.ComputeNormals(positions, indices, normals);
  25461. // Sides
  25462. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25463. // Result
  25464. var vertexData = new VertexData();
  25465. vertexData.indices = indices;
  25466. vertexData.positions = positions;
  25467. vertexData.normals = normals;
  25468. vertexData.uvs = uvs;
  25469. return vertexData;
  25470. };
  25471. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25472. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25473. var indices = [];
  25474. var positions = [];
  25475. var normals = [];
  25476. var uvs = [];
  25477. diameter = diameter || 1;
  25478. thickness = thickness || 0.5;
  25479. tessellation = tessellation || 16;
  25480. var stride = tessellation + 1;
  25481. for (var i = 0; i <= tessellation; i++) {
  25482. var u = i / tessellation;
  25483. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25484. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25485. for (var j = 0; j <= tessellation; j++) {
  25486. var v = 1 - j / tessellation;
  25487. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25488. var dx = Math.cos(innerAngle);
  25489. var dy = Math.sin(innerAngle);
  25490. // Create a vertex.
  25491. var normal = new BABYLON.Vector3(dx, dy, 0);
  25492. var position = normal.scale(thickness / 2);
  25493. var textureCoordinate = new BABYLON.Vector2(u, v);
  25494. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25495. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25496. positions.push(position.x, position.y, position.z);
  25497. normals.push(normal.x, normal.y, normal.z);
  25498. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25499. // And create indices for two triangles.
  25500. var nextI = (i + 1) % stride;
  25501. var nextJ = (j + 1) % stride;
  25502. indices.push(i * stride + j);
  25503. indices.push(i * stride + nextJ);
  25504. indices.push(nextI * stride + j);
  25505. indices.push(i * stride + nextJ);
  25506. indices.push(nextI * stride + nextJ);
  25507. indices.push(nextI * stride + j);
  25508. }
  25509. }
  25510. // Sides
  25511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25512. // Result
  25513. var vertexData = new VertexData();
  25514. vertexData.indices = indices;
  25515. vertexData.positions = positions;
  25516. vertexData.normals = normals;
  25517. vertexData.uvs = uvs;
  25518. return vertexData;
  25519. };
  25520. VertexData.CreateLines = function (points) {
  25521. var indices = [];
  25522. var positions = [];
  25523. for (var index = 0; index < points.length; index++) {
  25524. positions.push(points[index].x, points[index].y, points[index].z);
  25525. if (index > 0) {
  25526. indices.push(index - 1);
  25527. indices.push(index);
  25528. }
  25529. }
  25530. // Result
  25531. var vertexData = new VertexData();
  25532. vertexData.indices = indices;
  25533. vertexData.positions = positions;
  25534. return vertexData;
  25535. };
  25536. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25537. dashSize = dashSize || 3;
  25538. gapSize = gapSize || 1;
  25539. dashNb = dashNb || 200;
  25540. var positions = new Array();
  25541. var indices = new Array();
  25542. var curvect = BABYLON.Vector3.Zero();
  25543. var lg = 0;
  25544. var nb = 0;
  25545. var shft = 0;
  25546. var dashshft = 0;
  25547. var curshft = 0;
  25548. var idx = 0;
  25549. var i = 0;
  25550. for (i = 0; i < points.length - 1; i++) {
  25551. points[i + 1].subtractToRef(points[i], curvect);
  25552. lg += curvect.length();
  25553. }
  25554. shft = lg / dashNb;
  25555. dashshft = dashSize * shft / (dashSize + gapSize);
  25556. for (i = 0; i < points.length - 1; i++) {
  25557. points[i + 1].subtractToRef(points[i], curvect);
  25558. nb = Math.floor(curvect.length() / shft);
  25559. curvect.normalize();
  25560. for (var j = 0; j < nb; j++) {
  25561. curshft = shft * j;
  25562. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25563. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25564. indices.push(idx, idx + 1);
  25565. idx += 2;
  25566. }
  25567. }
  25568. // Result
  25569. var vertexData = new VertexData();
  25570. vertexData.positions = positions;
  25571. vertexData.indices = indices;
  25572. return vertexData;
  25573. };
  25574. VertexData.CreateGround = function (width, height, subdivisions) {
  25575. var indices = [];
  25576. var positions = [];
  25577. var normals = [];
  25578. var uvs = [];
  25579. var row, col;
  25580. width = width || 1;
  25581. height = height || 1;
  25582. subdivisions = subdivisions || 1;
  25583. for (row = 0; row <= subdivisions; row++) {
  25584. for (col = 0; col <= subdivisions; col++) {
  25585. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25586. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25587. positions.push(position.x, position.y, position.z);
  25588. normals.push(normal.x, normal.y, normal.z);
  25589. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25590. }
  25591. }
  25592. for (row = 0; row < subdivisions; row++) {
  25593. for (col = 0; col < subdivisions; col++) {
  25594. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25595. indices.push(col + 1 + row * (subdivisions + 1));
  25596. indices.push(col + row * (subdivisions + 1));
  25597. indices.push(col + (row + 1) * (subdivisions + 1));
  25598. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25599. indices.push(col + row * (subdivisions + 1));
  25600. }
  25601. }
  25602. // Result
  25603. var vertexData = new VertexData();
  25604. vertexData.indices = indices;
  25605. vertexData.positions = positions;
  25606. vertexData.normals = normals;
  25607. vertexData.uvs = uvs;
  25608. return vertexData;
  25609. };
  25610. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25611. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25612. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25613. var indices = [];
  25614. var positions = [];
  25615. var normals = [];
  25616. var uvs = [];
  25617. var row, col, tileRow, tileCol;
  25618. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25619. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25620. precision.w = (precision.w < 1) ? 1 : precision.w;
  25621. precision.h = (precision.h < 1) ? 1 : precision.h;
  25622. var tileSize = {
  25623. 'w': (xmax - xmin) / subdivisions.w,
  25624. 'h': (zmax - zmin) / subdivisions.h
  25625. };
  25626. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25627. // Indices
  25628. var base = positions.length / 3;
  25629. var rowLength = precision.w + 1;
  25630. for (row = 0; row < precision.h; row++) {
  25631. for (col = 0; col < precision.w; col++) {
  25632. var square = [
  25633. base + col + row * rowLength,
  25634. base + (col + 1) + row * rowLength,
  25635. base + (col + 1) + (row + 1) * rowLength,
  25636. base + col + (row + 1) * rowLength
  25637. ];
  25638. indices.push(square[1]);
  25639. indices.push(square[2]);
  25640. indices.push(square[3]);
  25641. indices.push(square[0]);
  25642. indices.push(square[1]);
  25643. indices.push(square[3]);
  25644. }
  25645. }
  25646. // Position, normals and uvs
  25647. var position = BABYLON.Vector3.Zero();
  25648. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25649. for (row = 0; row <= precision.h; row++) {
  25650. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25651. for (col = 0; col <= precision.w; col++) {
  25652. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25653. position.y = 0;
  25654. positions.push(position.x, position.y, position.z);
  25655. normals.push(normal.x, normal.y, normal.z);
  25656. uvs.push(col / precision.w, row / precision.h);
  25657. }
  25658. }
  25659. }
  25660. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25661. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25662. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25663. }
  25664. }
  25665. // Result
  25666. var vertexData = new VertexData();
  25667. vertexData.indices = indices;
  25668. vertexData.positions = positions;
  25669. vertexData.normals = normals;
  25670. vertexData.uvs = uvs;
  25671. return vertexData;
  25672. };
  25673. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25674. var indices = [];
  25675. var positions = [];
  25676. var normals = [];
  25677. var uvs = [];
  25678. var row, col;
  25679. // Vertices
  25680. for (row = 0; row <= subdivisions; row++) {
  25681. for (col = 0; col <= subdivisions; col++) {
  25682. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25683. // Compute height
  25684. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25685. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25686. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25687. var r = buffer[pos] / 255.0;
  25688. var g = buffer[pos + 1] / 255.0;
  25689. var b = buffer[pos + 2] / 255.0;
  25690. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25691. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25692. // Add vertex
  25693. positions.push(position.x, position.y, position.z);
  25694. normals.push(0, 0, 0);
  25695. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25696. }
  25697. }
  25698. // Indices
  25699. for (row = 0; row < subdivisions; row++) {
  25700. for (col = 0; col < subdivisions; col++) {
  25701. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25702. indices.push(col + 1 + row * (subdivisions + 1));
  25703. indices.push(col + row * (subdivisions + 1));
  25704. indices.push(col + (row + 1) * (subdivisions + 1));
  25705. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25706. indices.push(col + row * (subdivisions + 1));
  25707. }
  25708. }
  25709. // Normals
  25710. VertexData.ComputeNormals(positions, indices, normals);
  25711. // Result
  25712. var vertexData = new VertexData();
  25713. vertexData.indices = indices;
  25714. vertexData.positions = positions;
  25715. vertexData.normals = normals;
  25716. vertexData.uvs = uvs;
  25717. return vertexData;
  25718. };
  25719. VertexData.CreatePlane = function (size, sideOrientation) {
  25720. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25721. var indices = [];
  25722. var positions = [];
  25723. var normals = [];
  25724. var uvs = [];
  25725. size = size || 1;
  25726. // Vertices
  25727. var halfSize = size / 2.0;
  25728. positions.push(-halfSize, -halfSize, 0);
  25729. normals.push(0, 0, -1.0);
  25730. uvs.push(0.0, 0.0);
  25731. positions.push(halfSize, -halfSize, 0);
  25732. normals.push(0, 0, -1.0);
  25733. uvs.push(1.0, 0.0);
  25734. positions.push(halfSize, halfSize, 0);
  25735. normals.push(0, 0, -1.0);
  25736. uvs.push(1.0, 1.0);
  25737. positions.push(-halfSize, halfSize, 0);
  25738. normals.push(0, 0, -1.0);
  25739. uvs.push(0.0, 1.0);
  25740. // Indices
  25741. indices.push(0);
  25742. indices.push(1);
  25743. indices.push(2);
  25744. indices.push(0);
  25745. indices.push(2);
  25746. indices.push(3);
  25747. // Sides
  25748. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25749. // Result
  25750. var vertexData = new VertexData();
  25751. vertexData.indices = indices;
  25752. vertexData.positions = positions;
  25753. vertexData.normals = normals;
  25754. vertexData.uvs = uvs;
  25755. return vertexData;
  25756. };
  25757. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25758. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25759. var positions = [];
  25760. var indices = [];
  25761. var normals = [];
  25762. var uvs = [];
  25763. // positions and uvs
  25764. positions.push(0, 0, 0); // disc center first
  25765. uvs.push(0.5, 0.5);
  25766. var step = Math.PI * 2 / tessellation;
  25767. for (var a = 0; a < Math.PI * 2; a += step) {
  25768. var x = Math.cos(a);
  25769. var y = Math.sin(a);
  25770. var u = (x + 1) / 2;
  25771. var v = (1 - y) / 2;
  25772. positions.push(radius * x, radius * y, 0);
  25773. uvs.push(u, v);
  25774. }
  25775. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25776. uvs.push(uvs[2], uvs[3]);
  25777. //indices
  25778. var vertexNb = positions.length / 3;
  25779. for (var i = 1; i < vertexNb - 1; i++) {
  25780. indices.push(i + 1, 0, i);
  25781. }
  25782. // result
  25783. VertexData.ComputeNormals(positions, indices, normals);
  25784. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25785. var vertexData = new VertexData();
  25786. vertexData.indices = indices;
  25787. vertexData.positions = positions;
  25788. vertexData.normals = normals;
  25789. vertexData.uvs = uvs;
  25790. return vertexData;
  25791. };
  25792. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25793. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25794. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25795. var indices = [];
  25796. var positions = [];
  25797. var normals = [];
  25798. var uvs = [];
  25799. radius = radius || 2;
  25800. tube = tube || 0.5;
  25801. radialSegments = radialSegments || 32;
  25802. tubularSegments = tubularSegments || 32;
  25803. p = p || 2;
  25804. q = q || 3;
  25805. // Helper
  25806. var getPos = function (angle) {
  25807. var cu = Math.cos(angle);
  25808. var su = Math.sin(angle);
  25809. var quOverP = q / p * angle;
  25810. var cs = Math.cos(quOverP);
  25811. var tx = radius * (2 + cs) * 0.5 * cu;
  25812. var ty = radius * (2 + cs) * su * 0.5;
  25813. var tz = radius * Math.sin(quOverP) * 0.5;
  25814. return new BABYLON.Vector3(tx, ty, tz);
  25815. };
  25816. // Vertices
  25817. for (var i = 0; i <= radialSegments; i++) {
  25818. var modI = i % radialSegments;
  25819. var u = modI / radialSegments * 2 * p * Math.PI;
  25820. var p1 = getPos(u);
  25821. var p2 = getPos(u + 0.01);
  25822. var tang = p2.subtract(p1);
  25823. var n = p2.add(p1);
  25824. var bitan = BABYLON.Vector3.Cross(tang, n);
  25825. n = BABYLON.Vector3.Cross(bitan, tang);
  25826. bitan.normalize();
  25827. n.normalize();
  25828. for (var j = 0; j < tubularSegments; j++) {
  25829. var modJ = j % tubularSegments;
  25830. var v = modJ / tubularSegments * 2 * Math.PI;
  25831. var cx = -tube * Math.cos(v);
  25832. var cy = tube * Math.sin(v);
  25833. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25834. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25835. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25836. uvs.push(i / radialSegments);
  25837. uvs.push(j / tubularSegments);
  25838. }
  25839. }
  25840. for (i = 0; i < radialSegments; i++) {
  25841. for (j = 0; j < tubularSegments; j++) {
  25842. var jNext = (j + 1) % tubularSegments;
  25843. var a = i * tubularSegments + j;
  25844. var b = (i + 1) * tubularSegments + j;
  25845. var c = (i + 1) * tubularSegments + jNext;
  25846. var d = i * tubularSegments + jNext;
  25847. indices.push(d);
  25848. indices.push(b);
  25849. indices.push(a);
  25850. indices.push(d);
  25851. indices.push(c);
  25852. indices.push(b);
  25853. }
  25854. }
  25855. // Normals
  25856. VertexData.ComputeNormals(positions, indices, normals);
  25857. // Sides
  25858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25859. // Result
  25860. var vertexData = new VertexData();
  25861. vertexData.indices = indices;
  25862. vertexData.positions = positions;
  25863. vertexData.normals = normals;
  25864. vertexData.uvs = uvs;
  25865. return vertexData;
  25866. };
  25867. // Tools
  25868. /**
  25869. * @param {any} - positions (number[] or Float32Array)
  25870. * @param {any} - indices (number[] or Uint16Array)
  25871. * @param {any} - normals (number[] or Float32Array)
  25872. */
  25873. VertexData.ComputeNormals = function (positions, indices, normals) {
  25874. var index = 0;
  25875. // temp Vector3
  25876. var p1 = BABYLON.Vector3.Zero();
  25877. var p2 = BABYLON.Vector3.Zero();
  25878. var p3 = BABYLON.Vector3.Zero();
  25879. var p1p2 = BABYLON.Vector3.Zero();
  25880. var p3p2 = BABYLON.Vector3.Zero();
  25881. var faceNormal = BABYLON.Vector3.Zero();
  25882. var vertexNormali1 = BABYLON.Vector3.Zero();
  25883. var vertexNormali2 = BABYLON.Vector3.Zero();
  25884. var vertexNormali3 = BABYLON.Vector3.Zero();
  25885. // indice triplet = 1 face
  25886. var nbFaces = indices.length / 3;
  25887. for (index = 0; index < nbFaces; index++) {
  25888. var i1 = indices[index * 3];
  25889. var i2 = indices[index * 3 + 1];
  25890. var i3 = indices[index * 3 + 2];
  25891. // setting the temp V3
  25892. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25893. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25894. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25895. p1.subtractToRef(p2, p1p2);
  25896. p3.subtractToRef(p2, p3p2);
  25897. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25898. faceNormal.normalize();
  25899. // All intermediate results are stored in the normals array :
  25900. // get the normals at i1, i2 and i3 indexes
  25901. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25902. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25903. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25904. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25905. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25906. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25907. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25908. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25909. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25910. // make intermediate vectors3 from normals values
  25911. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25912. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25913. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25914. // add the current face normals to these intermediate vectors3
  25915. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25916. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25917. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25918. // store back intermediate vectors3 into the normals array
  25919. normals[i1 * 3] = vertexNormali1.x;
  25920. normals[i1 * 3 + 1] = vertexNormali1.y;
  25921. normals[i1 * 3 + 2] = vertexNormali1.z;
  25922. normals[i2 * 3] = vertexNormali2.x;
  25923. normals[i2 * 3 + 1] = vertexNormali2.y;
  25924. normals[i2 * 3 + 2] = vertexNormali2.z;
  25925. normals[i3 * 3] = vertexNormali3.x;
  25926. normals[i3 * 3 + 1] = vertexNormali3.y;
  25927. normals[i3 * 3 + 2] = vertexNormali3.z;
  25928. }
  25929. // last normalization
  25930. for (index = 0; index < normals.length / 3; index++) {
  25931. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25932. vertexNormali1.normalize();
  25933. normals[index * 3] = vertexNormali1.x;
  25934. normals[index * 3 + 1] = vertexNormali1.y;
  25935. normals[index * 3 + 2] = vertexNormali1.z;
  25936. }
  25937. };
  25938. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25939. var li = indices.length;
  25940. var ln = normals.length;
  25941. var i;
  25942. var n;
  25943. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25944. switch (sideOrientation) {
  25945. case BABYLON.Mesh.FRONTSIDE:
  25946. // nothing changed
  25947. break;
  25948. case BABYLON.Mesh.BACKSIDE:
  25949. var tmp;
  25950. // indices
  25951. for (i = 0; i < li; i += 3) {
  25952. tmp = indices[i];
  25953. indices[i] = indices[i + 2];
  25954. indices[i + 2] = tmp;
  25955. }
  25956. // normals
  25957. for (n = 0; n < ln; n++) {
  25958. normals[n] = -normals[n];
  25959. }
  25960. break;
  25961. case BABYLON.Mesh.DOUBLESIDE:
  25962. // positions
  25963. var lp = positions.length;
  25964. var l = lp / 3;
  25965. for (var p = 0; p < lp; p++) {
  25966. positions[lp + p] = positions[p];
  25967. }
  25968. // indices
  25969. for (i = 0; i < li; i += 3) {
  25970. indices[i + li] = indices[i + 2] + l;
  25971. indices[i + 1 + li] = indices[i + 1] + l;
  25972. indices[i + 2 + li] = indices[i] + l;
  25973. }
  25974. // normals
  25975. for (n = 0; n < ln; n++) {
  25976. normals[ln + n] = -normals[n];
  25977. }
  25978. // uvs
  25979. var lu = uvs.length;
  25980. for (var u = 0; u < lu; u++) {
  25981. uvs[u + lu] = uvs[u];
  25982. }
  25983. break;
  25984. }
  25985. };
  25986. return VertexData;
  25987. })();
  25988. BABYLON.VertexData = VertexData;
  25989. })(BABYLON || (BABYLON = {}));
  25990. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25991. var __extends = this.__extends || function (d, b) {
  25992. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25993. function __() { this.constructor = d; }
  25994. __.prototype = b.prototype;
  25995. d.prototype = new __();
  25996. };
  25997. var BABYLON;
  25998. (function (BABYLON) {
  25999. var AnaglyphFreeCamera = (function (_super) {
  26000. __extends(AnaglyphFreeCamera, _super);
  26001. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  26002. _super.call(this, name, position, scene);
  26003. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  26004. }
  26005. return AnaglyphFreeCamera;
  26006. })(BABYLON.FreeCamera);
  26007. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  26008. var AnaglyphArcRotateCamera = (function (_super) {
  26009. __extends(AnaglyphArcRotateCamera, _super);
  26010. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  26011. _super.call(this, name, alpha, beta, radius, target, scene);
  26012. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  26013. }
  26014. return AnaglyphArcRotateCamera;
  26015. })(BABYLON.ArcRotateCamera);
  26016. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  26017. var AnaglyphGamepadCamera = (function (_super) {
  26018. __extends(AnaglyphGamepadCamera, _super);
  26019. function AnaglyphGamepadCamera(name, position, eyeSpace, scene) {
  26020. _super.call(this, name, position, scene);
  26021. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  26022. }
  26023. return AnaglyphGamepadCamera;
  26024. })(BABYLON.GamepadCamera);
  26025. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  26026. })(BABYLON || (BABYLON = {}));
  26027. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  26028. var __extends = this.__extends || function (d, b) {
  26029. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26030. function __() { this.constructor = d; }
  26031. __.prototype = b.prototype;
  26032. d.prototype = new __();
  26033. };
  26034. var BABYLON;
  26035. (function (BABYLON) {
  26036. var AnaglyphPostProcess = (function (_super) {
  26037. __extends(AnaglyphPostProcess, _super);
  26038. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26039. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  26040. }
  26041. return AnaglyphPostProcess;
  26042. })(BABYLON.PostProcess);
  26043. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  26044. })(BABYLON || (BABYLON = {}));
  26045. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  26046. var BABYLON;
  26047. (function (BABYLON) {
  26048. var Tags = (function () {
  26049. function Tags() {
  26050. }
  26051. Tags.EnableFor = function (obj) {
  26052. obj._tags = obj._tags || {};
  26053. obj.hasTags = function () {
  26054. return Tags.HasTags(obj);
  26055. };
  26056. obj.addTags = function (tagsString) {
  26057. return Tags.AddTagsTo(obj, tagsString);
  26058. };
  26059. obj.removeTags = function (tagsString) {
  26060. return Tags.RemoveTagsFrom(obj, tagsString);
  26061. };
  26062. obj.matchesTagsQuery = function (tagsQuery) {
  26063. return Tags.MatchesQuery(obj, tagsQuery);
  26064. };
  26065. };
  26066. Tags.DisableFor = function (obj) {
  26067. delete obj._tags;
  26068. delete obj.hasTags;
  26069. delete obj.addTags;
  26070. delete obj.removeTags;
  26071. delete obj.matchesTagsQuery;
  26072. };
  26073. Tags.HasTags = function (obj) {
  26074. if (!obj._tags) {
  26075. return false;
  26076. }
  26077. return !BABYLON.Tools.IsEmpty(obj._tags);
  26078. };
  26079. Tags.GetTags = function (obj) {
  26080. if (!obj._tags) {
  26081. return null;
  26082. }
  26083. return obj._tags;
  26084. };
  26085. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26086. // a tag cannot start with '||', '&&', and '!'
  26087. // it cannot contain whitespaces
  26088. Tags.AddTagsTo = function (obj, tagsString) {
  26089. if (!tagsString) {
  26090. return;
  26091. }
  26092. var tags = tagsString.split(" ");
  26093. for (var t in tags) {
  26094. Tags._AddTagTo(obj, tags[t]);
  26095. }
  26096. };
  26097. Tags._AddTagTo = function (obj, tag) {
  26098. tag = tag.trim();
  26099. if (tag === "" || tag === "true" || tag === "false") {
  26100. return;
  26101. }
  26102. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26103. return;
  26104. }
  26105. Tags.EnableFor(obj);
  26106. obj._tags[tag] = true;
  26107. };
  26108. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26109. if (!Tags.HasTags(obj)) {
  26110. return;
  26111. }
  26112. var tags = tagsString.split(" ");
  26113. for (var t in tags) {
  26114. Tags._RemoveTagFrom(obj, tags[t]);
  26115. }
  26116. };
  26117. Tags._RemoveTagFrom = function (obj, tag) {
  26118. delete obj._tags[tag];
  26119. };
  26120. Tags.MatchesQuery = function (obj, tagsQuery) {
  26121. if (tagsQuery === undefined) {
  26122. return true;
  26123. }
  26124. if (tagsQuery === "") {
  26125. return Tags.HasTags(obj);
  26126. }
  26127. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26128. };
  26129. return Tags;
  26130. })();
  26131. BABYLON.Tags = Tags;
  26132. })(BABYLON || (BABYLON = {}));
  26133. //# sourceMappingURL=babylon.tags.js.map
  26134. var BABYLON;
  26135. (function (BABYLON) {
  26136. var Internals;
  26137. (function (Internals) {
  26138. var AndOrNotEvaluator = (function () {
  26139. function AndOrNotEvaluator() {
  26140. }
  26141. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26142. if (!query.match(/\([^\(\)]*\)/g)) {
  26143. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26144. }
  26145. else {
  26146. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26147. // remove parenthesis
  26148. r = r.slice(1, r.length - 1);
  26149. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26150. });
  26151. }
  26152. if (query === "true") {
  26153. return true;
  26154. }
  26155. if (query === "false") {
  26156. return false;
  26157. }
  26158. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26159. };
  26160. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26161. evaluateCallback = evaluateCallback || (function (r) {
  26162. return r === "true" ? true : false;
  26163. });
  26164. var result;
  26165. var or = parenthesisContent.split("||");
  26166. for (var i in or) {
  26167. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26168. var and = ori.split("&&");
  26169. if (and.length > 1) {
  26170. for (var j = 0; j < and.length; ++j) {
  26171. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26172. if (andj !== "true" && andj !== "false") {
  26173. if (andj[0] === "!") {
  26174. result = !evaluateCallback(andj.substring(1));
  26175. }
  26176. else {
  26177. result = evaluateCallback(andj);
  26178. }
  26179. }
  26180. else {
  26181. result = andj === "true" ? true : false;
  26182. }
  26183. if (!result) {
  26184. ori = "false";
  26185. break;
  26186. }
  26187. }
  26188. }
  26189. if (result || ori === "true") {
  26190. result = true;
  26191. break;
  26192. }
  26193. // result equals false (or undefined)
  26194. if (ori !== "true" && ori !== "false") {
  26195. if (ori[0] === "!") {
  26196. result = !evaluateCallback(ori.substring(1));
  26197. }
  26198. else {
  26199. result = evaluateCallback(ori);
  26200. }
  26201. }
  26202. else {
  26203. result = ori === "true" ? true : false;
  26204. }
  26205. }
  26206. // the whole parenthesis scope is replaced by 'true' or 'false'
  26207. return result ? "true" : "false";
  26208. };
  26209. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26210. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26211. // remove whitespaces
  26212. r = r.replace(/[\s]/g, function () { return ""; });
  26213. return r.length % 2 ? "!" : "";
  26214. });
  26215. booleanString = booleanString.trim();
  26216. if (booleanString === "!true") {
  26217. booleanString = "false";
  26218. }
  26219. else if (booleanString === "!false") {
  26220. booleanString = "true";
  26221. }
  26222. return booleanString;
  26223. };
  26224. return AndOrNotEvaluator;
  26225. })();
  26226. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26227. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26228. })(BABYLON || (BABYLON = {}));
  26229. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  26230. var BABYLON;
  26231. (function (BABYLON) {
  26232. var PostProcessRenderPass = (function () {
  26233. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26234. this._enabled = true;
  26235. this._refCount = 0;
  26236. this._name = name;
  26237. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26238. this.setRenderList(renderList);
  26239. this._renderTexture.onBeforeRender = beforeRender;
  26240. this._renderTexture.onAfterRender = afterRender;
  26241. this._scene = scene;
  26242. this._renderList = renderList;
  26243. }
  26244. // private
  26245. PostProcessRenderPass.prototype._incRefCount = function () {
  26246. if (this._refCount === 0) {
  26247. this._scene.customRenderTargets.push(this._renderTexture);
  26248. }
  26249. return ++this._refCount;
  26250. };
  26251. PostProcessRenderPass.prototype._decRefCount = function () {
  26252. this._refCount--;
  26253. if (this._refCount <= 0) {
  26254. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26255. }
  26256. return this._refCount;
  26257. };
  26258. PostProcessRenderPass.prototype._update = function () {
  26259. this.setRenderList(this._renderList);
  26260. };
  26261. // public
  26262. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26263. this._renderTexture.renderList = renderList;
  26264. };
  26265. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26266. return this._renderTexture;
  26267. };
  26268. return PostProcessRenderPass;
  26269. })();
  26270. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26271. })(BABYLON || (BABYLON = {}));
  26272. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26273. var BABYLON;
  26274. (function (BABYLON) {
  26275. var PostProcessRenderEffect = (function () {
  26276. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26277. this._engine = engine;
  26278. this._name = name;
  26279. this._singleInstance = singleInstance || true;
  26280. this._getPostProcess = getPostProcess;
  26281. this._cameras = [];
  26282. this._indicesForCamera = [];
  26283. this._postProcesses = {};
  26284. this._renderPasses = {};
  26285. this._renderEffectAsPasses = {};
  26286. }
  26287. PostProcessRenderEffect.prototype._update = function () {
  26288. for (var renderPassName in this._renderPasses) {
  26289. this._renderPasses[renderPassName]._update();
  26290. }
  26291. };
  26292. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26293. this._renderPasses[renderPass._name] = renderPass;
  26294. this._linkParameters();
  26295. };
  26296. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26297. delete this._renderPasses[renderPass._name];
  26298. this._linkParameters();
  26299. };
  26300. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26301. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26302. this._linkParameters();
  26303. };
  26304. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26305. for (var renderPassName in this._renderPasses) {
  26306. if (renderPassName === passName) {
  26307. return this._renderPasses[passName];
  26308. }
  26309. }
  26310. };
  26311. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26312. this._renderPasses = {};
  26313. this._linkParameters();
  26314. };
  26315. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26316. var cameraKey;
  26317. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26318. for (var i = 0; i < _cam.length; i++) {
  26319. var camera = _cam[i];
  26320. var cameraName = camera.name;
  26321. if (this._singleInstance) {
  26322. cameraKey = 0;
  26323. }
  26324. else {
  26325. cameraKey = cameraName;
  26326. }
  26327. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26328. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26329. if (!this._indicesForCamera[cameraName]) {
  26330. this._indicesForCamera[cameraName] = [];
  26331. }
  26332. this._indicesForCamera[cameraName].push(index);
  26333. if (this._cameras.indexOf(camera) === -1) {
  26334. this._cameras[cameraName] = camera;
  26335. }
  26336. for (var passName in this._renderPasses) {
  26337. this._renderPasses[passName]._incRefCount();
  26338. }
  26339. }
  26340. this._linkParameters();
  26341. };
  26342. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26343. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26344. for (var i = 0; i < _cam.length; i++) {
  26345. var camera = _cam[i];
  26346. var cameraName = camera.name;
  26347. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26348. var index = this._cameras.indexOf(cameraName);
  26349. this._indicesForCamera.splice(index, 1);
  26350. this._cameras.splice(index, 1);
  26351. for (var passName in this._renderPasses) {
  26352. this._renderPasses[passName]._decRefCount();
  26353. }
  26354. }
  26355. };
  26356. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26357. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26358. for (var i = 0; i < _cam.length; i++) {
  26359. var camera = _cam[i];
  26360. var cameraName = camera.name;
  26361. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26362. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26363. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26364. }
  26365. }
  26366. for (var passName in this._renderPasses) {
  26367. this._renderPasses[passName]._incRefCount();
  26368. }
  26369. }
  26370. };
  26371. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26372. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26373. for (var i = 0; i < _cam.length; i++) {
  26374. var camera = _cam[i];
  26375. var cameraName = camera.Name;
  26376. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26377. for (var passName in this._renderPasses) {
  26378. this._renderPasses[passName]._decRefCount();
  26379. }
  26380. }
  26381. };
  26382. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26383. if (this._singleInstance) {
  26384. return this._postProcesses[0];
  26385. }
  26386. else {
  26387. return this._postProcesses[camera.name];
  26388. }
  26389. };
  26390. PostProcessRenderEffect.prototype._linkParameters = function () {
  26391. var _this = this;
  26392. for (var index in this._postProcesses) {
  26393. if (this.applyParameters) {
  26394. this.applyParameters(this._postProcesses[index]);
  26395. }
  26396. this._postProcesses[index].onBeforeRender = function (effect) {
  26397. _this._linkTextures(effect);
  26398. };
  26399. }
  26400. };
  26401. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26402. for (var renderPassName in this._renderPasses) {
  26403. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26404. }
  26405. for (var renderEffectName in this._renderEffectAsPasses) {
  26406. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26407. }
  26408. };
  26409. return PostProcessRenderEffect;
  26410. })();
  26411. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26412. })(BABYLON || (BABYLON = {}));
  26413. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26414. var BABYLON;
  26415. (function (BABYLON) {
  26416. var PostProcessRenderPipeline = (function () {
  26417. function PostProcessRenderPipeline(engine, name) {
  26418. this._engine = engine;
  26419. this._name = name;
  26420. this._renderEffects = {};
  26421. this._renderEffectsForIsolatedPass = {};
  26422. this._cameras = [];
  26423. }
  26424. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26425. this._renderEffects[renderEffect._name] = renderEffect;
  26426. };
  26427. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26428. var renderEffects = this._renderEffects[renderEffectName];
  26429. if (!renderEffects) {
  26430. return;
  26431. }
  26432. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26433. };
  26434. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26435. var renderEffects = this._renderEffects[renderEffectName];
  26436. if (!renderEffects) {
  26437. return;
  26438. }
  26439. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26440. };
  26441. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26442. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26443. var indicesToDelete = [];
  26444. for (var i = 0; i < _cam.length; i++) {
  26445. var camera = _cam[i];
  26446. var cameraName = camera.name;
  26447. if (this._cameras.indexOf(camera) === -1) {
  26448. this._cameras[cameraName] = camera;
  26449. }
  26450. else if (unique) {
  26451. indicesToDelete.push(i);
  26452. }
  26453. }
  26454. for (var i = 0; i < indicesToDelete.length; i++) {
  26455. cameras.splice(indicesToDelete[i], 1);
  26456. }
  26457. for (var renderEffectName in this._renderEffects) {
  26458. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26459. }
  26460. };
  26461. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26462. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26463. for (var renderEffectName in this._renderEffects) {
  26464. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26465. }
  26466. for (var i = 0; i < _cam.length; i++) {
  26467. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26468. }
  26469. };
  26470. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26471. var _this = this;
  26472. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26473. var pass = null;
  26474. for (var renderEffectName in this._renderEffects) {
  26475. pass = this._renderEffects[renderEffectName].getPass(passName);
  26476. if (pass != null) {
  26477. break;
  26478. }
  26479. }
  26480. if (pass === null) {
  26481. return;
  26482. }
  26483. for (var renderEffectName in this._renderEffects) {
  26484. this._renderEffects[renderEffectName]._disable(_cam);
  26485. }
  26486. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26487. for (var i = 0; i < _cam.length; i++) {
  26488. var camera = _cam[i];
  26489. var cameraName = camera.name;
  26490. 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); });
  26491. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26492. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26493. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26494. }
  26495. };
  26496. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26497. var _this = this;
  26498. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26499. for (var i = 0; i < _cam.length; i++) {
  26500. var camera = _cam[i];
  26501. var cameraName = camera.name;
  26502. 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); });
  26503. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26504. }
  26505. for (var renderEffectName in this._renderEffects) {
  26506. this._renderEffects[renderEffectName]._enable(_cam);
  26507. }
  26508. };
  26509. PostProcessRenderPipeline.prototype._update = function () {
  26510. for (var renderEffectName in this._renderEffects) {
  26511. this._renderEffects[renderEffectName]._update();
  26512. }
  26513. for (var i = 0; i < this._cameras.length; i++) {
  26514. var cameraName = this._cameras[i].name;
  26515. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26516. this._renderEffectsForIsolatedPass[cameraName]._update();
  26517. }
  26518. }
  26519. };
  26520. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26521. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26522. return PostProcessRenderPipeline;
  26523. })();
  26524. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26525. })(BABYLON || (BABYLON = {}));
  26526. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26527. var BABYLON;
  26528. (function (BABYLON) {
  26529. var PostProcessRenderPipelineManager = (function () {
  26530. function PostProcessRenderPipelineManager() {
  26531. this._renderPipelines = {};
  26532. }
  26533. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26534. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26535. };
  26536. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26537. var renderPipeline = this._renderPipelines[renderPipelineName];
  26538. if (!renderPipeline) {
  26539. return;
  26540. }
  26541. renderPipeline._attachCameras(cameras, unique);
  26542. };
  26543. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26544. var renderPipeline = this._renderPipelines[renderPipelineName];
  26545. if (!renderPipeline) {
  26546. return;
  26547. }
  26548. renderPipeline._detachCameras(cameras);
  26549. };
  26550. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26551. var renderPipeline = this._renderPipelines[renderPipelineName];
  26552. if (!renderPipeline) {
  26553. return;
  26554. }
  26555. renderPipeline._enableEffect(renderEffectName, cameras);
  26556. };
  26557. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26558. var renderPipeline = this._renderPipelines[renderPipelineName];
  26559. if (!renderPipeline) {
  26560. return;
  26561. }
  26562. renderPipeline._disableEffect(renderEffectName, cameras);
  26563. };
  26564. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26565. var renderPipeline = this._renderPipelines[renderPipelineName];
  26566. if (!renderPipeline) {
  26567. return;
  26568. }
  26569. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26570. };
  26571. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26572. var renderPipeline = this._renderPipelines[renderPipelineName];
  26573. if (!renderPipeline) {
  26574. return;
  26575. }
  26576. renderPipeline._disableDisplayOnlyPass(cameras);
  26577. };
  26578. PostProcessRenderPipelineManager.prototype.update = function () {
  26579. for (var renderPipelineName in this._renderPipelines) {
  26580. this._renderPipelines[renderPipelineName]._update();
  26581. }
  26582. };
  26583. return PostProcessRenderPipelineManager;
  26584. })();
  26585. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26586. })(BABYLON || (BABYLON = {}));
  26587. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26588. var __extends = this.__extends || function (d, b) {
  26589. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26590. function __() { this.constructor = d; }
  26591. __.prototype = b.prototype;
  26592. d.prototype = new __();
  26593. };
  26594. var BABYLON;
  26595. (function (BABYLON) {
  26596. var DisplayPassPostProcess = (function (_super) {
  26597. __extends(DisplayPassPostProcess, _super);
  26598. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26599. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26600. }
  26601. return DisplayPassPostProcess;
  26602. })(BABYLON.PostProcess);
  26603. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26604. })(BABYLON || (BABYLON = {}));
  26605. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26606. var BABYLON;
  26607. (function (BABYLON) {
  26608. var BoundingBoxRenderer = (function () {
  26609. function BoundingBoxRenderer(scene) {
  26610. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26611. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26612. this.showBackLines = true;
  26613. this.renderList = new BABYLON.SmartArray(32);
  26614. this._scene = scene;
  26615. }
  26616. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26617. if (this._colorShader) {
  26618. return;
  26619. }
  26620. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26621. attributes: ["position"],
  26622. uniforms: ["worldViewProjection", "color"]
  26623. });
  26624. var engine = this._scene.getEngine();
  26625. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26626. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26627. 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]);
  26628. };
  26629. BoundingBoxRenderer.prototype.reset = function () {
  26630. this.renderList.reset();
  26631. };
  26632. BoundingBoxRenderer.prototype.render = function () {
  26633. if (this.renderList.length === 0) {
  26634. return;
  26635. }
  26636. this._prepareRessources();
  26637. if (!this._colorShader.isReady()) {
  26638. return;
  26639. }
  26640. var engine = this._scene.getEngine();
  26641. engine.setDepthWrite(false);
  26642. this._colorShader._preBind();
  26643. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26644. var boundingBox = this.renderList.data[boundingBoxIndex];
  26645. var min = boundingBox.minimum;
  26646. var max = boundingBox.maximum;
  26647. var diff = max.subtract(min);
  26648. var median = min.add(diff.scale(0.5));
  26649. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26650. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26651. .multiply(boundingBox.getWorldMatrix());
  26652. // VBOs
  26653. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26654. if (this.showBackLines) {
  26655. // Back
  26656. engine.setDepthFunctionToGreaterOrEqual();
  26657. this._scene.resetCachedMaterial();
  26658. this._colorShader.setColor4("color", this.backColor.toColor4());
  26659. this._colorShader.bind(worldMatrix);
  26660. // Draw order
  26661. engine.draw(false, 0, 24);
  26662. }
  26663. // Front
  26664. engine.setDepthFunctionToLess();
  26665. this._scene.resetCachedMaterial();
  26666. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26667. this._colorShader.bind(worldMatrix);
  26668. // Draw order
  26669. engine.draw(false, 0, 24);
  26670. }
  26671. this._colorShader.unbind();
  26672. engine.setDepthFunctionToLessOrEqual();
  26673. engine.setDepthWrite(true);
  26674. };
  26675. BoundingBoxRenderer.prototype.dispose = function () {
  26676. if (!this._colorShader) {
  26677. return;
  26678. }
  26679. this._colorShader.dispose();
  26680. this._vb.dispose();
  26681. this._scene.getEngine()._releaseBuffer(this._ib);
  26682. };
  26683. return BoundingBoxRenderer;
  26684. })();
  26685. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26686. })(BABYLON || (BABYLON = {}));
  26687. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26688. var __extends = this.__extends || function (d, b) {
  26689. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26690. function __() { this.constructor = d; }
  26691. __.prototype = b.prototype;
  26692. d.prototype = new __();
  26693. };
  26694. var BABYLON;
  26695. (function (BABYLON) {
  26696. var Condition = (function () {
  26697. function Condition(actionManager) {
  26698. this._actionManager = actionManager;
  26699. }
  26700. Condition.prototype.isValid = function () {
  26701. return true;
  26702. };
  26703. Condition.prototype._getProperty = function (propertyPath) {
  26704. return this._actionManager._getProperty(propertyPath);
  26705. };
  26706. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26707. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26708. };
  26709. return Condition;
  26710. })();
  26711. BABYLON.Condition = Condition;
  26712. var ValueCondition = (function (_super) {
  26713. __extends(ValueCondition, _super);
  26714. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26715. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26716. _super.call(this, actionManager);
  26717. this.propertyPath = propertyPath;
  26718. this.value = value;
  26719. this.operator = operator;
  26720. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26721. this._property = this._getProperty(this.propertyPath);
  26722. }
  26723. Object.defineProperty(ValueCondition, "IsEqual", {
  26724. get: function () {
  26725. return ValueCondition._IsEqual;
  26726. },
  26727. enumerable: true,
  26728. configurable: true
  26729. });
  26730. Object.defineProperty(ValueCondition, "IsDifferent", {
  26731. get: function () {
  26732. return ValueCondition._IsDifferent;
  26733. },
  26734. enumerable: true,
  26735. configurable: true
  26736. });
  26737. Object.defineProperty(ValueCondition, "IsGreater", {
  26738. get: function () {
  26739. return ValueCondition._IsGreater;
  26740. },
  26741. enumerable: true,
  26742. configurable: true
  26743. });
  26744. Object.defineProperty(ValueCondition, "IsLesser", {
  26745. get: function () {
  26746. return ValueCondition._IsLesser;
  26747. },
  26748. enumerable: true,
  26749. configurable: true
  26750. });
  26751. // Methods
  26752. ValueCondition.prototype.isValid = function () {
  26753. switch (this.operator) {
  26754. case ValueCondition.IsGreater:
  26755. return this._target[this._property] > this.value;
  26756. case ValueCondition.IsLesser:
  26757. return this._target[this._property] < this.value;
  26758. case ValueCondition.IsEqual:
  26759. case ValueCondition.IsDifferent:
  26760. var check;
  26761. if (this.value.equals) {
  26762. check = this.value.equals(this._target[this._property]);
  26763. }
  26764. else {
  26765. check = this.value === this._target[this._property];
  26766. }
  26767. return this.operator === ValueCondition.IsEqual ? check : !check;
  26768. }
  26769. return false;
  26770. };
  26771. // Statics
  26772. ValueCondition._IsEqual = 0;
  26773. ValueCondition._IsDifferent = 1;
  26774. ValueCondition._IsGreater = 2;
  26775. ValueCondition._IsLesser = 3;
  26776. return ValueCondition;
  26777. })(Condition);
  26778. BABYLON.ValueCondition = ValueCondition;
  26779. var PredicateCondition = (function (_super) {
  26780. __extends(PredicateCondition, _super);
  26781. function PredicateCondition(actionManager, predicate) {
  26782. _super.call(this, actionManager);
  26783. this.predicate = predicate;
  26784. }
  26785. PredicateCondition.prototype.isValid = function () {
  26786. return this.predicate();
  26787. };
  26788. return PredicateCondition;
  26789. })(Condition);
  26790. BABYLON.PredicateCondition = PredicateCondition;
  26791. var StateCondition = (function (_super) {
  26792. __extends(StateCondition, _super);
  26793. function StateCondition(actionManager, target, value) {
  26794. _super.call(this, actionManager);
  26795. this.value = value;
  26796. this._target = target;
  26797. }
  26798. // Methods
  26799. StateCondition.prototype.isValid = function () {
  26800. return this._target.state === this.value;
  26801. };
  26802. return StateCondition;
  26803. })(Condition);
  26804. BABYLON.StateCondition = StateCondition;
  26805. })(BABYLON || (BABYLON = {}));
  26806. //# sourceMappingURL=babylon.condition.js.map
  26807. var BABYLON;
  26808. (function (BABYLON) {
  26809. var Action = (function () {
  26810. function Action(triggerOptions, condition) {
  26811. this.triggerOptions = triggerOptions;
  26812. if (triggerOptions.parameter) {
  26813. this.trigger = triggerOptions.trigger;
  26814. this._triggerParameter = triggerOptions.parameter;
  26815. }
  26816. else {
  26817. this.trigger = triggerOptions;
  26818. }
  26819. this._nextActiveAction = this;
  26820. this._condition = condition;
  26821. }
  26822. // Methods
  26823. Action.prototype._prepare = function () {
  26824. };
  26825. Action.prototype.getTriggerParameter = function () {
  26826. return this._triggerParameter;
  26827. };
  26828. Action.prototype._executeCurrent = function (evt) {
  26829. if (this._nextActiveAction._condition) {
  26830. var condition = this._nextActiveAction._condition;
  26831. var currentRenderId = this._actionManager.getScene().getRenderId();
  26832. // We cache the current evaluation for the current frame
  26833. if (condition._evaluationId === currentRenderId) {
  26834. if (!condition._currentResult) {
  26835. return;
  26836. }
  26837. }
  26838. else {
  26839. condition._evaluationId = currentRenderId;
  26840. if (!condition.isValid()) {
  26841. condition._currentResult = false;
  26842. return;
  26843. }
  26844. condition._currentResult = true;
  26845. }
  26846. }
  26847. this._nextActiveAction.execute(evt);
  26848. if (this._nextActiveAction._child) {
  26849. if (!this._nextActiveAction._child._actionManager) {
  26850. this._nextActiveAction._child._actionManager = this._actionManager;
  26851. }
  26852. this._nextActiveAction = this._nextActiveAction._child;
  26853. }
  26854. else {
  26855. this._nextActiveAction = this;
  26856. }
  26857. };
  26858. Action.prototype.execute = function (evt) {
  26859. };
  26860. Action.prototype.then = function (action) {
  26861. this._child = action;
  26862. action._actionManager = this._actionManager;
  26863. action._prepare();
  26864. return action;
  26865. };
  26866. Action.prototype._getProperty = function (propertyPath) {
  26867. return this._actionManager._getProperty(propertyPath);
  26868. };
  26869. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26870. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26871. };
  26872. return Action;
  26873. })();
  26874. BABYLON.Action = Action;
  26875. })(BABYLON || (BABYLON = {}));
  26876. //# sourceMappingURL=babylon.action.js.map
  26877. var BABYLON;
  26878. (function (BABYLON) {
  26879. /**
  26880. * ActionEvent is the event beint sent when an action is triggered.
  26881. */
  26882. var ActionEvent = (function () {
  26883. /**
  26884. * @constructor
  26885. * @param source The mesh that triggered the action.
  26886. * @param pointerX the X mouse cursor position at the time of the event
  26887. * @param pointerY the Y mouse cursor position at the time of the event
  26888. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26889. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26890. */
  26891. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26892. this.source = source;
  26893. this.pointerX = pointerX;
  26894. this.pointerY = pointerY;
  26895. this.meshUnderPointer = meshUnderPointer;
  26896. this.sourceEvent = sourceEvent;
  26897. }
  26898. /**
  26899. * Helper function to auto-create an ActionEvent from a source mesh.
  26900. * @param source the source mesh that triggered the event
  26901. * @param evt {Event} The original (browser) event
  26902. */
  26903. ActionEvent.CreateNew = function (source, evt) {
  26904. var scene = source.getScene();
  26905. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26906. };
  26907. /**
  26908. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26909. * @param scene the scene where the event occurred
  26910. * @param evt {Event} The original (browser) event
  26911. */
  26912. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26913. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26914. };
  26915. return ActionEvent;
  26916. })();
  26917. BABYLON.ActionEvent = ActionEvent;
  26918. /**
  26919. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26920. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26921. */
  26922. var ActionManager = (function () {
  26923. function ActionManager(scene) {
  26924. // Members
  26925. this.actions = new Array();
  26926. this._scene = scene;
  26927. scene._actionManagers.push(this);
  26928. }
  26929. Object.defineProperty(ActionManager, "NothingTrigger", {
  26930. get: function () {
  26931. return ActionManager._NothingTrigger;
  26932. },
  26933. enumerable: true,
  26934. configurable: true
  26935. });
  26936. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26937. get: function () {
  26938. return ActionManager._OnPickTrigger;
  26939. },
  26940. enumerable: true,
  26941. configurable: true
  26942. });
  26943. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26944. get: function () {
  26945. return ActionManager._OnLeftPickTrigger;
  26946. },
  26947. enumerable: true,
  26948. configurable: true
  26949. });
  26950. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26951. get: function () {
  26952. return ActionManager._OnRightPickTrigger;
  26953. },
  26954. enumerable: true,
  26955. configurable: true
  26956. });
  26957. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26958. get: function () {
  26959. return ActionManager._OnCenterPickTrigger;
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26965. get: function () {
  26966. return ActionManager._OnPointerOverTrigger;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26972. get: function () {
  26973. return ActionManager._OnPointerOutTrigger;
  26974. },
  26975. enumerable: true,
  26976. configurable: true
  26977. });
  26978. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26979. get: function () {
  26980. return ActionManager._OnEveryFrameTrigger;
  26981. },
  26982. enumerable: true,
  26983. configurable: true
  26984. });
  26985. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26986. get: function () {
  26987. return ActionManager._OnIntersectionEnterTrigger;
  26988. },
  26989. enumerable: true,
  26990. configurable: true
  26991. });
  26992. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26993. get: function () {
  26994. return ActionManager._OnIntersectionExitTrigger;
  26995. },
  26996. enumerable: true,
  26997. configurable: true
  26998. });
  26999. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27000. get: function () {
  27001. return ActionManager._OnKeyDownTrigger;
  27002. },
  27003. enumerable: true,
  27004. configurable: true
  27005. });
  27006. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27007. get: function () {
  27008. return ActionManager._OnKeyUpTrigger;
  27009. },
  27010. enumerable: true,
  27011. configurable: true
  27012. });
  27013. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27014. get: function () {
  27015. return ActionManager._OnPickUpTrigger;
  27016. },
  27017. enumerable: true,
  27018. configurable: true
  27019. });
  27020. // Methods
  27021. ActionManager.prototype.dispose = function () {
  27022. var index = this._scene._actionManagers.indexOf(this);
  27023. if (index > -1) {
  27024. this._scene._actionManagers.splice(index, 1);
  27025. }
  27026. };
  27027. ActionManager.prototype.getScene = function () {
  27028. return this._scene;
  27029. };
  27030. /**
  27031. * Does this action manager handles actions of any of the given triggers
  27032. * @param {number[]} triggers - the triggers to be tested
  27033. * @return {boolean} whether one (or more) of the triggers is handeled
  27034. */
  27035. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27036. for (var index = 0; index < this.actions.length; index++) {
  27037. var action = this.actions[index];
  27038. if (triggers.indexOf(action.trigger) > -1) {
  27039. return true;
  27040. }
  27041. }
  27042. return false;
  27043. };
  27044. /**
  27045. * Does this action manager handles actions of a given trigger
  27046. * @param {number} trigger - the trigger to be tested
  27047. * @return {boolean} whether the trigger is handeled
  27048. */
  27049. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27050. for (var index = 0; index < this.actions.length; index++) {
  27051. var action = this.actions[index];
  27052. if (action.trigger === trigger) {
  27053. return true;
  27054. }
  27055. }
  27056. return false;
  27057. };
  27058. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27059. /**
  27060. * Does this action manager has pointer triggers
  27061. * @return {boolean} whether or not it has pointer triggers
  27062. */
  27063. get: function () {
  27064. for (var index = 0; index < this.actions.length; index++) {
  27065. var action = this.actions[index];
  27066. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27067. return true;
  27068. }
  27069. if (action.trigger == ActionManager._OnPickUpTrigger) {
  27070. return true;
  27071. }
  27072. }
  27073. return false;
  27074. },
  27075. enumerable: true,
  27076. configurable: true
  27077. });
  27078. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27079. /**
  27080. * Does this action manager has pick triggers
  27081. * @return {boolean} whether or not it has pick triggers
  27082. */
  27083. get: function () {
  27084. for (var index = 0; index < this.actions.length; index++) {
  27085. var action = this.actions[index];
  27086. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  27087. return true;
  27088. }
  27089. }
  27090. return false;
  27091. },
  27092. enumerable: true,
  27093. configurable: true
  27094. });
  27095. /**
  27096. * Registers an action to this action manager
  27097. * @param {BABYLON.Action} action - the action to be registered
  27098. * @return {BABYLON.Action} the action amended (prepared) after registration
  27099. */
  27100. ActionManager.prototype.registerAction = function (action) {
  27101. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27102. if (this.getScene().actionManager !== this) {
  27103. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27104. return null;
  27105. }
  27106. }
  27107. this.actions.push(action);
  27108. action._actionManager = this;
  27109. action._prepare();
  27110. return action;
  27111. };
  27112. /**
  27113. * Process a specific trigger
  27114. * @param {number} trigger - the trigger to process
  27115. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27116. */
  27117. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27118. for (var index = 0; index < this.actions.length; index++) {
  27119. var action = this.actions[index];
  27120. if (action.trigger === trigger) {
  27121. if (trigger === ActionManager.OnKeyUpTrigger
  27122. || trigger === ActionManager.OnKeyDownTrigger) {
  27123. var parameter = action.getTriggerParameter();
  27124. if (parameter) {
  27125. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27126. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27127. if (actualkey !== parameter.toLowerCase()) {
  27128. continue;
  27129. }
  27130. }
  27131. }
  27132. action._executeCurrent(evt);
  27133. }
  27134. }
  27135. };
  27136. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27137. var properties = propertyPath.split(".");
  27138. for (var index = 0; index < properties.length - 1; index++) {
  27139. target = target[properties[index]];
  27140. }
  27141. return target;
  27142. };
  27143. ActionManager.prototype._getProperty = function (propertyPath) {
  27144. var properties = propertyPath.split(".");
  27145. return properties[properties.length - 1];
  27146. };
  27147. // Statics
  27148. ActionManager._NothingTrigger = 0;
  27149. ActionManager._OnPickTrigger = 1;
  27150. ActionManager._OnLeftPickTrigger = 2;
  27151. ActionManager._OnRightPickTrigger = 3;
  27152. ActionManager._OnCenterPickTrigger = 4;
  27153. ActionManager._OnPointerOverTrigger = 5;
  27154. ActionManager._OnPointerOutTrigger = 6;
  27155. ActionManager._OnEveryFrameTrigger = 7;
  27156. ActionManager._OnIntersectionEnterTrigger = 8;
  27157. ActionManager._OnIntersectionExitTrigger = 9;
  27158. ActionManager._OnKeyDownTrigger = 10;
  27159. ActionManager._OnKeyUpTrigger = 11;
  27160. ActionManager._OnPickUpTrigger = 12;
  27161. return ActionManager;
  27162. })();
  27163. BABYLON.ActionManager = ActionManager;
  27164. })(BABYLON || (BABYLON = {}));
  27165. //# sourceMappingURL=babylon.actionManager.js.map
  27166. var __extends = this.__extends || function (d, b) {
  27167. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27168. function __() { this.constructor = d; }
  27169. __.prototype = b.prototype;
  27170. d.prototype = new __();
  27171. };
  27172. var BABYLON;
  27173. (function (BABYLON) {
  27174. var InterpolateValueAction = (function (_super) {
  27175. __extends(InterpolateValueAction, _super);
  27176. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  27177. if (duration === void 0) { duration = 1000; }
  27178. _super.call(this, triggerOptions, condition);
  27179. this.propertyPath = propertyPath;
  27180. this.value = value;
  27181. this.duration = duration;
  27182. this.stopOtherAnimations = stopOtherAnimations;
  27183. this._target = target;
  27184. }
  27185. InterpolateValueAction.prototype._prepare = function () {
  27186. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27187. this._property = this._getProperty(this.propertyPath);
  27188. };
  27189. InterpolateValueAction.prototype.execute = function () {
  27190. var scene = this._actionManager.getScene();
  27191. var keys = [
  27192. {
  27193. frame: 0,
  27194. value: this._target[this._property]
  27195. }, {
  27196. frame: 100,
  27197. value: this.value
  27198. }
  27199. ];
  27200. var dataType;
  27201. if (typeof this.value === "number") {
  27202. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27203. }
  27204. else if (this.value instanceof BABYLON.Color3) {
  27205. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27206. }
  27207. else if (this.value instanceof BABYLON.Vector3) {
  27208. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27209. }
  27210. else if (this.value instanceof BABYLON.Matrix) {
  27211. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27212. }
  27213. else if (this.value instanceof BABYLON.Quaternion) {
  27214. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27215. }
  27216. else {
  27217. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27218. return;
  27219. }
  27220. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27221. animation.setKeys(keys);
  27222. if (this.stopOtherAnimations) {
  27223. scene.stopAnimation(this._target);
  27224. }
  27225. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  27226. };
  27227. return InterpolateValueAction;
  27228. })(BABYLON.Action);
  27229. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27230. })(BABYLON || (BABYLON = {}));
  27231. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  27232. var __extends = this.__extends || function (d, b) {
  27233. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27234. function __() { this.constructor = d; }
  27235. __.prototype = b.prototype;
  27236. d.prototype = new __();
  27237. };
  27238. var BABYLON;
  27239. (function (BABYLON) {
  27240. var SwitchBooleanAction = (function (_super) {
  27241. __extends(SwitchBooleanAction, _super);
  27242. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27243. _super.call(this, triggerOptions, condition);
  27244. this.propertyPath = propertyPath;
  27245. this._target = target;
  27246. }
  27247. SwitchBooleanAction.prototype._prepare = function () {
  27248. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27249. this._property = this._getProperty(this.propertyPath);
  27250. };
  27251. SwitchBooleanAction.prototype.execute = function () {
  27252. this._target[this._property] = !this._target[this._property];
  27253. };
  27254. return SwitchBooleanAction;
  27255. })(BABYLON.Action);
  27256. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27257. var SetStateAction = (function (_super) {
  27258. __extends(SetStateAction, _super);
  27259. function SetStateAction(triggerOptions, target, value, condition) {
  27260. _super.call(this, triggerOptions, condition);
  27261. this.value = value;
  27262. this._target = target;
  27263. }
  27264. SetStateAction.prototype.execute = function () {
  27265. this._target.state = this.value;
  27266. };
  27267. return SetStateAction;
  27268. })(BABYLON.Action);
  27269. BABYLON.SetStateAction = SetStateAction;
  27270. var SetValueAction = (function (_super) {
  27271. __extends(SetValueAction, _super);
  27272. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27273. _super.call(this, triggerOptions, condition);
  27274. this.propertyPath = propertyPath;
  27275. this.value = value;
  27276. this._target = target;
  27277. }
  27278. SetValueAction.prototype._prepare = function () {
  27279. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27280. this._property = this._getProperty(this.propertyPath);
  27281. };
  27282. SetValueAction.prototype.execute = function () {
  27283. this._target[this._property] = this.value;
  27284. };
  27285. return SetValueAction;
  27286. })(BABYLON.Action);
  27287. BABYLON.SetValueAction = SetValueAction;
  27288. var IncrementValueAction = (function (_super) {
  27289. __extends(IncrementValueAction, _super);
  27290. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27291. _super.call(this, triggerOptions, condition);
  27292. this.propertyPath = propertyPath;
  27293. this.value = value;
  27294. this._target = target;
  27295. }
  27296. IncrementValueAction.prototype._prepare = function () {
  27297. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27298. this._property = this._getProperty(this.propertyPath);
  27299. if (typeof this._target[this._property] !== "number") {
  27300. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27301. }
  27302. };
  27303. IncrementValueAction.prototype.execute = function () {
  27304. this._target[this._property] += this.value;
  27305. };
  27306. return IncrementValueAction;
  27307. })(BABYLON.Action);
  27308. BABYLON.IncrementValueAction = IncrementValueAction;
  27309. var PlayAnimationAction = (function (_super) {
  27310. __extends(PlayAnimationAction, _super);
  27311. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27312. _super.call(this, triggerOptions, condition);
  27313. this.from = from;
  27314. this.to = to;
  27315. this.loop = loop;
  27316. this._target = target;
  27317. }
  27318. PlayAnimationAction.prototype._prepare = function () {
  27319. };
  27320. PlayAnimationAction.prototype.execute = function () {
  27321. var scene = this._actionManager.getScene();
  27322. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27323. };
  27324. return PlayAnimationAction;
  27325. })(BABYLON.Action);
  27326. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27327. var StopAnimationAction = (function (_super) {
  27328. __extends(StopAnimationAction, _super);
  27329. function StopAnimationAction(triggerOptions, target, condition) {
  27330. _super.call(this, triggerOptions, condition);
  27331. this._target = target;
  27332. }
  27333. StopAnimationAction.prototype._prepare = function () {
  27334. };
  27335. StopAnimationAction.prototype.execute = function () {
  27336. var scene = this._actionManager.getScene();
  27337. scene.stopAnimation(this._target);
  27338. };
  27339. return StopAnimationAction;
  27340. })(BABYLON.Action);
  27341. BABYLON.StopAnimationAction = StopAnimationAction;
  27342. var DoNothingAction = (function (_super) {
  27343. __extends(DoNothingAction, _super);
  27344. function DoNothingAction(triggerOptions, condition) {
  27345. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27346. _super.call(this, triggerOptions, condition);
  27347. }
  27348. DoNothingAction.prototype.execute = function () {
  27349. };
  27350. return DoNothingAction;
  27351. })(BABYLON.Action);
  27352. BABYLON.DoNothingAction = DoNothingAction;
  27353. var CombineAction = (function (_super) {
  27354. __extends(CombineAction, _super);
  27355. function CombineAction(triggerOptions, children, condition) {
  27356. _super.call(this, triggerOptions, condition);
  27357. this.children = children;
  27358. }
  27359. CombineAction.prototype._prepare = function () {
  27360. for (var index = 0; index < this.children.length; index++) {
  27361. this.children[index]._actionManager = this._actionManager;
  27362. this.children[index]._prepare();
  27363. }
  27364. };
  27365. CombineAction.prototype.execute = function (evt) {
  27366. for (var index = 0; index < this.children.length; index++) {
  27367. this.children[index].execute(evt);
  27368. }
  27369. };
  27370. return CombineAction;
  27371. })(BABYLON.Action);
  27372. BABYLON.CombineAction = CombineAction;
  27373. var ExecuteCodeAction = (function (_super) {
  27374. __extends(ExecuteCodeAction, _super);
  27375. function ExecuteCodeAction(triggerOptions, func, condition) {
  27376. _super.call(this, triggerOptions, condition);
  27377. this.func = func;
  27378. }
  27379. ExecuteCodeAction.prototype.execute = function (evt) {
  27380. this.func(evt);
  27381. };
  27382. return ExecuteCodeAction;
  27383. })(BABYLON.Action);
  27384. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27385. var SetParentAction = (function (_super) {
  27386. __extends(SetParentAction, _super);
  27387. function SetParentAction(triggerOptions, target, parent, condition) {
  27388. _super.call(this, triggerOptions, condition);
  27389. this._target = target;
  27390. this._parent = parent;
  27391. }
  27392. SetParentAction.prototype._prepare = function () {
  27393. };
  27394. SetParentAction.prototype.execute = function () {
  27395. if (this._target.parent === this._parent) {
  27396. return;
  27397. }
  27398. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27399. invertParentWorldMatrix.invert();
  27400. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27401. this._target.parent = this._parent;
  27402. };
  27403. return SetParentAction;
  27404. })(BABYLON.Action);
  27405. BABYLON.SetParentAction = SetParentAction;
  27406. var PlaySoundAction = (function (_super) {
  27407. __extends(PlaySoundAction, _super);
  27408. function PlaySoundAction(triggerOptions, sound, condition) {
  27409. _super.call(this, triggerOptions, condition);
  27410. this._sound = sound;
  27411. }
  27412. PlaySoundAction.prototype._prepare = function () {
  27413. };
  27414. PlaySoundAction.prototype.execute = function () {
  27415. if (this._sound !== undefined)
  27416. this._sound.play();
  27417. };
  27418. return PlaySoundAction;
  27419. })(BABYLON.Action);
  27420. BABYLON.PlaySoundAction = PlaySoundAction;
  27421. var StopSoundAction = (function (_super) {
  27422. __extends(StopSoundAction, _super);
  27423. function StopSoundAction(triggerOptions, sound, condition) {
  27424. _super.call(this, triggerOptions, condition);
  27425. this._sound = sound;
  27426. }
  27427. StopSoundAction.prototype._prepare = function () {
  27428. };
  27429. StopSoundAction.prototype.execute = function () {
  27430. if (this._sound !== undefined)
  27431. this._sound.stop();
  27432. };
  27433. return StopSoundAction;
  27434. })(BABYLON.Action);
  27435. BABYLON.StopSoundAction = StopSoundAction;
  27436. })(BABYLON || (BABYLON = {}));
  27437. //# sourceMappingURL=babylon.directActions.js.map
  27438. var __extends = this.__extends || function (d, b) {
  27439. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27440. function __() { this.constructor = d; }
  27441. __.prototype = b.prototype;
  27442. d.prototype = new __();
  27443. };
  27444. var BABYLON;
  27445. (function (BABYLON) {
  27446. var Geometry = (function () {
  27447. function Geometry(id, scene, vertexData, updatable, mesh) {
  27448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27449. this._totalVertices = 0;
  27450. this._indices = [];
  27451. this._isDisposed = false;
  27452. this.id = id;
  27453. this._engine = scene.getEngine();
  27454. this._meshes = [];
  27455. this._scene = scene;
  27456. // vertexData
  27457. if (vertexData) {
  27458. this.setAllVerticesData(vertexData, updatable);
  27459. }
  27460. else {
  27461. this._totalVertices = 0;
  27462. this._indices = [];
  27463. }
  27464. // applyToMesh
  27465. if (mesh) {
  27466. this.applyToMesh(mesh);
  27467. mesh.computeWorldMatrix(true);
  27468. }
  27469. }
  27470. Geometry.prototype.getScene = function () {
  27471. return this._scene;
  27472. };
  27473. Geometry.prototype.getEngine = function () {
  27474. return this._engine;
  27475. };
  27476. Geometry.prototype.isReady = function () {
  27477. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27478. };
  27479. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27480. vertexData.applyToGeometry(this, updatable);
  27481. this.notifyUpdate();
  27482. };
  27483. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27484. this._vertexBuffers = this._vertexBuffers || {};
  27485. if (this._vertexBuffers[kind]) {
  27486. this._vertexBuffers[kind].dispose();
  27487. }
  27488. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27489. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27490. stride = this._vertexBuffers[kind].getStrideSize();
  27491. this._totalVertices = data.length / stride;
  27492. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27493. var meshes = this._meshes;
  27494. var numOfMeshes = meshes.length;
  27495. for (var index = 0; index < numOfMeshes; index++) {
  27496. var mesh = meshes[index];
  27497. mesh._resetPointsArrayCache();
  27498. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27499. mesh._createGlobalSubMesh();
  27500. mesh.computeWorldMatrix(true);
  27501. }
  27502. }
  27503. this.notifyUpdate(kind);
  27504. };
  27505. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27506. var vertexBuffer = this.getVertexBuffer(kind);
  27507. if (!vertexBuffer) {
  27508. return;
  27509. }
  27510. vertexBuffer.updateDirectly(data, offset);
  27511. this.notifyUpdate(kind);
  27512. };
  27513. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27514. var vertexBuffer = this.getVertexBuffer(kind);
  27515. if (!vertexBuffer) {
  27516. return;
  27517. }
  27518. vertexBuffer.update(data);
  27519. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27520. var extend;
  27521. var stride = vertexBuffer.getStrideSize();
  27522. this._totalVertices = data.length / stride;
  27523. if (updateExtends) {
  27524. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27525. }
  27526. var meshes = this._meshes;
  27527. var numOfMeshes = meshes.length;
  27528. for (var index = 0; index < numOfMeshes; index++) {
  27529. var mesh = meshes[index];
  27530. mesh._resetPointsArrayCache();
  27531. if (updateExtends) {
  27532. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27533. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27534. var subMesh = mesh.subMeshes[subIndex];
  27535. subMesh.refreshBoundingInfo();
  27536. }
  27537. }
  27538. }
  27539. }
  27540. this.notifyUpdate(kind);
  27541. };
  27542. Geometry.prototype.getTotalVertices = function () {
  27543. if (!this.isReady()) {
  27544. return 0;
  27545. }
  27546. return this._totalVertices;
  27547. };
  27548. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27549. var vertexBuffer = this.getVertexBuffer(kind);
  27550. if (!vertexBuffer) {
  27551. return null;
  27552. }
  27553. var orig = vertexBuffer.getData();
  27554. if (!copyWhenShared || this._meshes.length === 1) {
  27555. return orig;
  27556. }
  27557. else {
  27558. var len = orig.length;
  27559. var copy = [];
  27560. for (var i = 0; i < len; i++) {
  27561. copy.push(orig[i]);
  27562. }
  27563. return copy;
  27564. }
  27565. };
  27566. Geometry.prototype.getVertexBuffer = function (kind) {
  27567. if (!this.isReady()) {
  27568. return null;
  27569. }
  27570. return this._vertexBuffers[kind];
  27571. };
  27572. Geometry.prototype.getVertexBuffers = function () {
  27573. if (!this.isReady()) {
  27574. return null;
  27575. }
  27576. return this._vertexBuffers;
  27577. };
  27578. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27579. if (!this._vertexBuffers) {
  27580. if (this._delayInfo) {
  27581. return this._delayInfo.indexOf(kind) !== -1;
  27582. }
  27583. return false;
  27584. }
  27585. return this._vertexBuffers[kind] !== undefined;
  27586. };
  27587. Geometry.prototype.getVerticesDataKinds = function () {
  27588. var result = [];
  27589. if (!this._vertexBuffers && this._delayInfo) {
  27590. for (var kind in this._delayInfo) {
  27591. result.push(kind);
  27592. }
  27593. }
  27594. else {
  27595. for (kind in this._vertexBuffers) {
  27596. result.push(kind);
  27597. }
  27598. }
  27599. return result;
  27600. };
  27601. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27602. if (this._indexBuffer) {
  27603. this._engine._releaseBuffer(this._indexBuffer);
  27604. }
  27605. this._indices = indices;
  27606. if (this._meshes.length !== 0 && this._indices) {
  27607. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27608. }
  27609. if (totalVertices !== undefined) {
  27610. this._totalVertices = totalVertices;
  27611. }
  27612. var meshes = this._meshes;
  27613. var numOfMeshes = meshes.length;
  27614. for (var index = 0; index < numOfMeshes; index++) {
  27615. meshes[index]._createGlobalSubMesh();
  27616. }
  27617. this.notifyUpdate();
  27618. };
  27619. Geometry.prototype.getTotalIndices = function () {
  27620. if (!this.isReady()) {
  27621. return 0;
  27622. }
  27623. return this._indices.length;
  27624. };
  27625. Geometry.prototype.getIndices = function (copyWhenShared) {
  27626. if (!this.isReady()) {
  27627. return null;
  27628. }
  27629. var orig = this._indices;
  27630. if (!copyWhenShared || this._meshes.length === 1) {
  27631. return orig;
  27632. }
  27633. else {
  27634. var len = orig.length;
  27635. var copy = [];
  27636. for (var i = 0; i < len; i++) {
  27637. copy.push(orig[i]);
  27638. }
  27639. return copy;
  27640. }
  27641. };
  27642. Geometry.prototype.getIndexBuffer = function () {
  27643. if (!this.isReady()) {
  27644. return null;
  27645. }
  27646. return this._indexBuffer;
  27647. };
  27648. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27649. var meshes = this._meshes;
  27650. var index = meshes.indexOf(mesh);
  27651. if (index === -1) {
  27652. return;
  27653. }
  27654. for (var kind in this._vertexBuffers) {
  27655. this._vertexBuffers[kind].dispose();
  27656. }
  27657. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27658. this._indexBuffer = null;
  27659. }
  27660. meshes.splice(index, 1);
  27661. mesh._geometry = null;
  27662. if (meshes.length === 0 && shouldDispose) {
  27663. this.dispose();
  27664. }
  27665. };
  27666. Geometry.prototype.applyToMesh = function (mesh) {
  27667. if (mesh._geometry === this) {
  27668. return;
  27669. }
  27670. var previousGeometry = mesh._geometry;
  27671. if (previousGeometry) {
  27672. previousGeometry.releaseForMesh(mesh);
  27673. }
  27674. var meshes = this._meshes;
  27675. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27676. mesh._geometry = this;
  27677. this._scene.pushGeometry(this);
  27678. meshes.push(mesh);
  27679. if (this.isReady()) {
  27680. this._applyToMesh(mesh);
  27681. }
  27682. else {
  27683. mesh._boundingInfo = this._boundingInfo;
  27684. }
  27685. };
  27686. Geometry.prototype._applyToMesh = function (mesh) {
  27687. var numOfMeshes = this._meshes.length;
  27688. // vertexBuffers
  27689. for (var kind in this._vertexBuffers) {
  27690. if (numOfMeshes === 1) {
  27691. this._vertexBuffers[kind].create();
  27692. }
  27693. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27694. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27695. mesh._resetPointsArrayCache();
  27696. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27697. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27698. mesh._createGlobalSubMesh();
  27699. //bounding info was just created again, world matrix should be applied again.
  27700. mesh._updateBoundingInfo();
  27701. }
  27702. }
  27703. // indexBuffer
  27704. if (numOfMeshes === 1 && this._indices) {
  27705. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27706. }
  27707. if (this._indexBuffer) {
  27708. this._indexBuffer.references = numOfMeshes;
  27709. }
  27710. };
  27711. Geometry.prototype.notifyUpdate = function (kind) {
  27712. if (this.onGeometryUpdated) {
  27713. this.onGeometryUpdated(this, kind);
  27714. }
  27715. };
  27716. Geometry.prototype.load = function (scene, onLoaded) {
  27717. var _this = this;
  27718. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27719. return;
  27720. }
  27721. if (this.isReady()) {
  27722. if (onLoaded) {
  27723. onLoaded();
  27724. }
  27725. return;
  27726. }
  27727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27728. scene._addPendingData(this);
  27729. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27730. _this._delayLoadingFunction(JSON.parse(data), _this);
  27731. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27732. _this._delayInfo = [];
  27733. scene._removePendingData(_this);
  27734. var meshes = _this._meshes;
  27735. var numOfMeshes = meshes.length;
  27736. for (var index = 0; index < numOfMeshes; index++) {
  27737. _this._applyToMesh(meshes[index]);
  27738. }
  27739. if (onLoaded) {
  27740. onLoaded();
  27741. }
  27742. }, function () { }, scene.database);
  27743. };
  27744. Geometry.prototype.isDisposed = function () {
  27745. return this._isDisposed;
  27746. };
  27747. Geometry.prototype.dispose = function () {
  27748. var meshes = this._meshes;
  27749. var numOfMeshes = meshes.length;
  27750. var index;
  27751. for (index = 0; index < numOfMeshes; index++) {
  27752. this.releaseForMesh(meshes[index]);
  27753. }
  27754. this._meshes = [];
  27755. for (var kind in this._vertexBuffers) {
  27756. this._vertexBuffers[kind].dispose();
  27757. }
  27758. this._vertexBuffers = [];
  27759. this._totalVertices = 0;
  27760. if (this._indexBuffer) {
  27761. this._engine._releaseBuffer(this._indexBuffer);
  27762. }
  27763. this._indexBuffer = null;
  27764. this._indices = [];
  27765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27766. this.delayLoadingFile = null;
  27767. this._delayLoadingFunction = null;
  27768. this._delayInfo = [];
  27769. this._boundingInfo = null; // todo: .dispose()
  27770. this._scene.removeGeometry(this);
  27771. this._isDisposed = true;
  27772. };
  27773. Geometry.prototype.copy = function (id) {
  27774. var vertexData = new BABYLON.VertexData();
  27775. vertexData.indices = [];
  27776. var indices = this.getIndices();
  27777. for (var index = 0; index < indices.length; index++) {
  27778. vertexData.indices.push(indices[index]);
  27779. }
  27780. var updatable = false;
  27781. var stopChecking = false;
  27782. for (var kind in this._vertexBuffers) {
  27783. // using slice() to make a copy of the array and not just reference it
  27784. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27785. if (!stopChecking) {
  27786. updatable = this.getVertexBuffer(kind).isUpdatable();
  27787. stopChecking = !updatable;
  27788. }
  27789. }
  27790. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27791. geometry.delayLoadState = this.delayLoadState;
  27792. geometry.delayLoadingFile = this.delayLoadingFile;
  27793. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27794. for (kind in this._delayInfo) {
  27795. geometry._delayInfo = geometry._delayInfo || [];
  27796. geometry._delayInfo.push(kind);
  27797. }
  27798. // Bounding info
  27799. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27800. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27801. return geometry;
  27802. };
  27803. // Statics
  27804. Geometry.ExtractFromMesh = function (mesh, id) {
  27805. var geometry = mesh._geometry;
  27806. if (!geometry) {
  27807. return null;
  27808. }
  27809. return geometry.copy(id);
  27810. };
  27811. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27812. // be aware Math.random() could cause collisions
  27813. Geometry.RandomId = function () {
  27814. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27815. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27816. return v.toString(16);
  27817. });
  27818. };
  27819. return Geometry;
  27820. })();
  27821. BABYLON.Geometry = Geometry;
  27822. /////// Primitives //////////////////////////////////////////////
  27823. var Geometry;
  27824. (function (Geometry) {
  27825. var Primitives;
  27826. (function (Primitives) {
  27827. /// Abstract class
  27828. var _Primitive = (function (_super) {
  27829. __extends(_Primitive, _super);
  27830. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27831. this._beingRegenerated = true;
  27832. this._canBeRegenerated = canBeRegenerated;
  27833. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27834. this._beingRegenerated = false;
  27835. }
  27836. _Primitive.prototype.canBeRegenerated = function () {
  27837. return this._canBeRegenerated;
  27838. };
  27839. _Primitive.prototype.regenerate = function () {
  27840. if (!this._canBeRegenerated) {
  27841. return;
  27842. }
  27843. this._beingRegenerated = true;
  27844. this.setAllVerticesData(this._regenerateVertexData(), false);
  27845. this._beingRegenerated = false;
  27846. };
  27847. _Primitive.prototype.asNewGeometry = function (id) {
  27848. return _super.prototype.copy.call(this, id);
  27849. };
  27850. // overrides
  27851. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27852. if (!this._beingRegenerated) {
  27853. return;
  27854. }
  27855. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27856. };
  27857. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27858. if (!this._beingRegenerated) {
  27859. return;
  27860. }
  27861. _super.prototype.setVerticesData.call(this, kind, data, false);
  27862. };
  27863. // to override
  27864. // protected
  27865. _Primitive.prototype._regenerateVertexData = function () {
  27866. throw new Error("Abstract method");
  27867. };
  27868. _Primitive.prototype.copy = function (id) {
  27869. throw new Error("Must be overriden in sub-classes.");
  27870. };
  27871. return _Primitive;
  27872. })(Geometry);
  27873. Primitives._Primitive = _Primitive;
  27874. var Ribbon = (function (_super) {
  27875. __extends(Ribbon, _super);
  27876. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27878. this.pathArray = pathArray;
  27879. this.closeArray = closeArray;
  27880. this.closePath = closePath;
  27881. this.offset = offset;
  27882. this.side = side;
  27883. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27884. }
  27885. Ribbon.prototype._regenerateVertexData = function () {
  27886. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27887. };
  27888. Ribbon.prototype.copy = function (id) {
  27889. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27890. };
  27891. return Ribbon;
  27892. })(_Primitive);
  27893. Primitives.Ribbon = Ribbon;
  27894. var Box = (function (_super) {
  27895. __extends(Box, _super);
  27896. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27897. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27898. this.size = size;
  27899. this.side = side;
  27900. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27901. }
  27902. Box.prototype._regenerateVertexData = function () {
  27903. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27904. };
  27905. Box.prototype.copy = function (id) {
  27906. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27907. };
  27908. return Box;
  27909. })(_Primitive);
  27910. Primitives.Box = Box;
  27911. var Sphere = (function (_super) {
  27912. __extends(Sphere, _super);
  27913. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27914. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27915. this.segments = segments;
  27916. this.diameter = diameter;
  27917. this.side = side;
  27918. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27919. }
  27920. Sphere.prototype._regenerateVertexData = function () {
  27921. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27922. };
  27923. Sphere.prototype.copy = function (id) {
  27924. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27925. };
  27926. return Sphere;
  27927. })(_Primitive);
  27928. Primitives.Sphere = Sphere;
  27929. var Cylinder = (function (_super) {
  27930. __extends(Cylinder, _super);
  27931. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27932. if (subdivisions === void 0) { subdivisions = 1; }
  27933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27934. this.height = height;
  27935. this.diameterTop = diameterTop;
  27936. this.diameterBottom = diameterBottom;
  27937. this.tessellation = tessellation;
  27938. this.subdivisions = subdivisions;
  27939. this.side = side;
  27940. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27941. }
  27942. Cylinder.prototype._regenerateVertexData = function () {
  27943. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27944. };
  27945. Cylinder.prototype.copy = function (id) {
  27946. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27947. };
  27948. return Cylinder;
  27949. })(_Primitive);
  27950. Primitives.Cylinder = Cylinder;
  27951. var Torus = (function (_super) {
  27952. __extends(Torus, _super);
  27953. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27954. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27955. this.diameter = diameter;
  27956. this.thickness = thickness;
  27957. this.tessellation = tessellation;
  27958. this.side = side;
  27959. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27960. }
  27961. Torus.prototype._regenerateVertexData = function () {
  27962. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27963. };
  27964. Torus.prototype.copy = function (id) {
  27965. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27966. };
  27967. return Torus;
  27968. })(_Primitive);
  27969. Primitives.Torus = Torus;
  27970. var Ground = (function (_super) {
  27971. __extends(Ground, _super);
  27972. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27973. this.width = width;
  27974. this.height = height;
  27975. this.subdivisions = subdivisions;
  27976. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27977. }
  27978. Ground.prototype._regenerateVertexData = function () {
  27979. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27980. };
  27981. Ground.prototype.copy = function (id) {
  27982. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27983. };
  27984. return Ground;
  27985. })(_Primitive);
  27986. Primitives.Ground = Ground;
  27987. var TiledGround = (function (_super) {
  27988. __extends(TiledGround, _super);
  27989. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27990. this.xmin = xmin;
  27991. this.zmin = zmin;
  27992. this.xmax = xmax;
  27993. this.zmax = zmax;
  27994. this.subdivisions = subdivisions;
  27995. this.precision = precision;
  27996. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27997. }
  27998. TiledGround.prototype._regenerateVertexData = function () {
  27999. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  28000. };
  28001. TiledGround.prototype.copy = function (id) {
  28002. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28003. };
  28004. return TiledGround;
  28005. })(_Primitive);
  28006. Primitives.TiledGround = TiledGround;
  28007. var Plane = (function (_super) {
  28008. __extends(Plane, _super);
  28009. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28010. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28011. this.size = size;
  28012. this.side = side;
  28013. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28014. }
  28015. Plane.prototype._regenerateVertexData = function () {
  28016. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  28017. };
  28018. Plane.prototype.copy = function (id) {
  28019. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28020. };
  28021. return Plane;
  28022. })(_Primitive);
  28023. Primitives.Plane = Plane;
  28024. var TorusKnot = (function (_super) {
  28025. __extends(TorusKnot, _super);
  28026. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28027. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28028. this.radius = radius;
  28029. this.tube = tube;
  28030. this.radialSegments = radialSegments;
  28031. this.tubularSegments = tubularSegments;
  28032. this.p = p;
  28033. this.q = q;
  28034. this.side = side;
  28035. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28036. }
  28037. TorusKnot.prototype._regenerateVertexData = function () {
  28038. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  28039. };
  28040. TorusKnot.prototype.copy = function (id) {
  28041. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28042. };
  28043. return TorusKnot;
  28044. })(_Primitive);
  28045. Primitives.TorusKnot = TorusKnot;
  28046. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28047. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28048. })(BABYLON || (BABYLON = {}));
  28049. //# sourceMappingURL=babylon.geometry.js.map
  28050. var __extends = this.__extends || function (d, b) {
  28051. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28052. function __() { this.constructor = d; }
  28053. __.prototype = b.prototype;
  28054. d.prototype = new __();
  28055. };
  28056. var BABYLON;
  28057. (function (BABYLON) {
  28058. var GroundMesh = (function (_super) {
  28059. __extends(GroundMesh, _super);
  28060. function GroundMesh(name, scene) {
  28061. _super.call(this, name, scene);
  28062. this.generateOctree = false;
  28063. this._worldInverse = new BABYLON.Matrix();
  28064. }
  28065. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28066. get: function () {
  28067. return this._subdivisions;
  28068. },
  28069. enumerable: true,
  28070. configurable: true
  28071. });
  28072. GroundMesh.prototype.optimize = function (chunksCount) {
  28073. this.subdivide(this._subdivisions);
  28074. this.createOrUpdateSubmeshesOctree(32);
  28075. };
  28076. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28077. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  28078. this.getWorldMatrix().invertToRef(this._worldInverse);
  28079. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  28080. var pickInfo = this.intersects(ray);
  28081. if (pickInfo.hit) {
  28082. return pickInfo.pickedPoint.y;
  28083. }
  28084. return 0;
  28085. };
  28086. return GroundMesh;
  28087. })(BABYLON.Mesh);
  28088. BABYLON.GroundMesh = GroundMesh;
  28089. })(BABYLON || (BABYLON = {}));
  28090. //# sourceMappingURL=babylon.groundMesh.js.map
  28091. var __extends = this.__extends || function (d, b) {
  28092. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28093. function __() { this.constructor = d; }
  28094. __.prototype = b.prototype;
  28095. d.prototype = new __();
  28096. };
  28097. var BABYLON;
  28098. (function (BABYLON) {
  28099. var LinesMesh = (function (_super) {
  28100. __extends(LinesMesh, _super);
  28101. function LinesMesh(name, scene, updatable) {
  28102. if (updatable === void 0) { updatable = false; }
  28103. _super.call(this, name, scene);
  28104. this.color = new BABYLON.Color3(1, 1, 1);
  28105. this.alpha = 1;
  28106. this._indices = new Array();
  28107. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28108. attributes: ["position"],
  28109. uniforms: ["worldViewProjection", "color"],
  28110. needAlphaBlending: true
  28111. });
  28112. }
  28113. Object.defineProperty(LinesMesh.prototype, "material", {
  28114. get: function () {
  28115. return this._colorShader;
  28116. },
  28117. enumerable: true,
  28118. configurable: true
  28119. });
  28120. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28121. get: function () {
  28122. return false;
  28123. },
  28124. enumerable: true,
  28125. configurable: true
  28126. });
  28127. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28128. get: function () {
  28129. return false;
  28130. },
  28131. enumerable: true,
  28132. configurable: true
  28133. });
  28134. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28135. var engine = this.getScene().getEngine();
  28136. var indexToBind = this._geometry.getIndexBuffer();
  28137. // VBOs
  28138. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28139. // Color
  28140. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28141. };
  28142. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28143. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28144. return;
  28145. }
  28146. var engine = this.getScene().getEngine();
  28147. // Draw order
  28148. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28149. };
  28150. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28151. return null;
  28152. };
  28153. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28154. this._colorShader.dispose();
  28155. _super.prototype.dispose.call(this, doNotRecurse);
  28156. };
  28157. return LinesMesh;
  28158. })(BABYLON.Mesh);
  28159. BABYLON.LinesMesh = LinesMesh;
  28160. })(BABYLON || (BABYLON = {}));
  28161. //# sourceMappingURL=babylon.linesMesh.js.map
  28162. var BABYLON;
  28163. (function (BABYLON) {
  28164. var OutlineRenderer = (function () {
  28165. function OutlineRenderer(scene) {
  28166. this._scene = scene;
  28167. }
  28168. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  28169. var _this = this;
  28170. if (useOverlay === void 0) { useOverlay = false; }
  28171. var scene = this._scene;
  28172. var engine = this._scene.getEngine();
  28173. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28174. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  28175. return;
  28176. }
  28177. var mesh = subMesh.getRenderingMesh();
  28178. var material = subMesh.getMaterial();
  28179. engine.enableEffect(this._effect);
  28180. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  28181. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  28182. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28183. // Bones
  28184. if (mesh.useBones) {
  28185. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28186. }
  28187. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  28188. // Alpha test
  28189. if (material && material.needAlphaTesting()) {
  28190. var alphaTexture = material.getAlphaTestTexture();
  28191. this._effect.setTexture("diffuseSampler", alphaTexture);
  28192. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28193. }
  28194. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  28195. };
  28196. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  28197. var defines = [];
  28198. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  28199. var mesh = subMesh.getMesh();
  28200. var material = subMesh.getMaterial();
  28201. // Alpha test
  28202. if (material && material.needAlphaTesting()) {
  28203. defines.push("#define ALPHATEST");
  28204. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28205. attribs.push(BABYLON.VertexBuffer.UVKind);
  28206. defines.push("#define UV1");
  28207. }
  28208. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28209. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28210. defines.push("#define UV2");
  28211. }
  28212. }
  28213. // Bones
  28214. if (mesh.useBones) {
  28215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28217. defines.push("#define BONES");
  28218. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28219. }
  28220. // Instances
  28221. if (useInstances) {
  28222. defines.push("#define INSTANCES");
  28223. attribs.push("world0");
  28224. attribs.push("world1");
  28225. attribs.push("world2");
  28226. attribs.push("world3");
  28227. }
  28228. // Get correct effect
  28229. var join = defines.join("\n");
  28230. if (this._cachedDefines !== join) {
  28231. this._cachedDefines = join;
  28232. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  28233. }
  28234. return this._effect.isReady();
  28235. };
  28236. return OutlineRenderer;
  28237. })();
  28238. BABYLON.OutlineRenderer = OutlineRenderer;
  28239. })(BABYLON || (BABYLON = {}));
  28240. //# sourceMappingURL=babylon.outlineRenderer.js.map
  28241. var BABYLON;
  28242. (function (BABYLON) {
  28243. var MeshAssetTask = (function () {
  28244. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  28245. this.name = name;
  28246. this.meshesNames = meshesNames;
  28247. this.rootUrl = rootUrl;
  28248. this.sceneFilename = sceneFilename;
  28249. this.isCompleted = false;
  28250. }
  28251. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28252. var _this = this;
  28253. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  28254. _this.loadedMeshes = meshes;
  28255. _this.loadedParticleSystems = particleSystems;
  28256. _this.loadedSkeletons = skeletons;
  28257. _this.isCompleted = true;
  28258. if (_this.onSuccess) {
  28259. _this.onSuccess(_this);
  28260. }
  28261. onSuccess();
  28262. }, null, function () {
  28263. if (_this.onError) {
  28264. _this.onError(_this);
  28265. }
  28266. onError();
  28267. });
  28268. };
  28269. return MeshAssetTask;
  28270. })();
  28271. BABYLON.MeshAssetTask = MeshAssetTask;
  28272. var TextFileAssetTask = (function () {
  28273. function TextFileAssetTask(name, url) {
  28274. this.name = name;
  28275. this.url = url;
  28276. this.isCompleted = false;
  28277. }
  28278. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28279. var _this = this;
  28280. BABYLON.Tools.LoadFile(this.url, function (data) {
  28281. _this.text = data;
  28282. _this.isCompleted = true;
  28283. if (_this.onSuccess) {
  28284. _this.onSuccess(_this);
  28285. }
  28286. onSuccess();
  28287. }, null, scene.database, false, function () {
  28288. if (_this.onError) {
  28289. _this.onError(_this);
  28290. }
  28291. onError();
  28292. });
  28293. };
  28294. return TextFileAssetTask;
  28295. })();
  28296. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28297. var BinaryFileAssetTask = (function () {
  28298. function BinaryFileAssetTask(name, url) {
  28299. this.name = name;
  28300. this.url = url;
  28301. this.isCompleted = false;
  28302. }
  28303. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28304. var _this = this;
  28305. BABYLON.Tools.LoadFile(this.url, function (data) {
  28306. _this.data = data;
  28307. _this.isCompleted = true;
  28308. if (_this.onSuccess) {
  28309. _this.onSuccess(_this);
  28310. }
  28311. onSuccess();
  28312. }, null, scene.database, true, function () {
  28313. if (_this.onError) {
  28314. _this.onError(_this);
  28315. }
  28316. onError();
  28317. });
  28318. };
  28319. return BinaryFileAssetTask;
  28320. })();
  28321. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28322. var ImageAssetTask = (function () {
  28323. function ImageAssetTask(name, url) {
  28324. this.name = name;
  28325. this.url = url;
  28326. this.isCompleted = false;
  28327. }
  28328. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28329. var _this = this;
  28330. var img = new Image();
  28331. img.onload = function () {
  28332. _this.image = img;
  28333. _this.isCompleted = true;
  28334. if (_this.onSuccess) {
  28335. _this.onSuccess(_this);
  28336. }
  28337. onSuccess();
  28338. };
  28339. img.onerror = function () {
  28340. if (_this.onError) {
  28341. _this.onError(_this);
  28342. }
  28343. onError();
  28344. };
  28345. img.src = this.url;
  28346. };
  28347. return ImageAssetTask;
  28348. })();
  28349. BABYLON.ImageAssetTask = ImageAssetTask;
  28350. var TextureAssetTask = (function () {
  28351. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28353. this.name = name;
  28354. this.url = url;
  28355. this.noMipmap = noMipmap;
  28356. this.invertY = invertY;
  28357. this.samplingMode = samplingMode;
  28358. this.isCompleted = false;
  28359. }
  28360. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28361. var _this = this;
  28362. var onload = function () {
  28363. _this.isCompleted = true;
  28364. if (_this.onSuccess) {
  28365. _this.onSuccess(_this);
  28366. }
  28367. onSuccess();
  28368. };
  28369. var onerror = function () {
  28370. if (_this.onError) {
  28371. _this.onError(_this);
  28372. }
  28373. onError();
  28374. };
  28375. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28376. };
  28377. return TextureAssetTask;
  28378. })();
  28379. BABYLON.TextureAssetTask = TextureAssetTask;
  28380. var AssetsManager = (function () {
  28381. function AssetsManager(scene) {
  28382. this._tasks = new Array();
  28383. this._waitingTasksCount = 0;
  28384. this.useDefaultLoadingScreen = true;
  28385. this._scene = scene;
  28386. }
  28387. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28388. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28389. this._tasks.push(task);
  28390. return task;
  28391. };
  28392. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28393. var task = new TextFileAssetTask(taskName, url);
  28394. this._tasks.push(task);
  28395. return task;
  28396. };
  28397. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28398. var task = new BinaryFileAssetTask(taskName, url);
  28399. this._tasks.push(task);
  28400. return task;
  28401. };
  28402. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28403. var task = new ImageAssetTask(taskName, url);
  28404. this._tasks.push(task);
  28405. return task;
  28406. };
  28407. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28409. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28410. this._tasks.push(task);
  28411. return task;
  28412. };
  28413. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28414. this._waitingTasksCount--;
  28415. if (this._waitingTasksCount === 0) {
  28416. if (this.onFinish) {
  28417. this.onFinish(this._tasks);
  28418. }
  28419. this._scene.getEngine().hideLoadingUI();
  28420. }
  28421. };
  28422. AssetsManager.prototype._runTask = function (task) {
  28423. var _this = this;
  28424. task.run(this._scene, function () {
  28425. if (_this.onTaskSuccess) {
  28426. _this.onTaskSuccess(task);
  28427. }
  28428. _this._decreaseWaitingTasksCount();
  28429. }, function () {
  28430. if (_this.onTaskError) {
  28431. _this.onTaskError(task);
  28432. }
  28433. _this._decreaseWaitingTasksCount();
  28434. });
  28435. };
  28436. AssetsManager.prototype.reset = function () {
  28437. this._tasks = new Array();
  28438. return this;
  28439. };
  28440. AssetsManager.prototype.load = function () {
  28441. this._waitingTasksCount = this._tasks.length;
  28442. if (this._waitingTasksCount === 0) {
  28443. if (this.onFinish) {
  28444. this.onFinish(this._tasks);
  28445. }
  28446. return this;
  28447. }
  28448. if (this.useDefaultLoadingScreen) {
  28449. this._scene.getEngine().displayLoadingUI();
  28450. }
  28451. for (var index = 0; index < this._tasks.length; index++) {
  28452. var task = this._tasks[index];
  28453. this._runTask(task);
  28454. }
  28455. return this;
  28456. };
  28457. return AssetsManager;
  28458. })();
  28459. BABYLON.AssetsManager = AssetsManager;
  28460. })(BABYLON || (BABYLON = {}));
  28461. //# sourceMappingURL=babylon.assetsManager.js.map
  28462. var __extends = this.__extends || function (d, b) {
  28463. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28464. function __() { this.constructor = d; }
  28465. __.prototype = b.prototype;
  28466. d.prototype = new __();
  28467. };
  28468. var BABYLON;
  28469. (function (BABYLON) {
  28470. var VRDeviceOrientationFreeCamera = (function (_super) {
  28471. __extends(VRDeviceOrientationFreeCamera, _super);
  28472. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  28473. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28474. _super.call(this, name, position, scene);
  28475. this._alpha = 0;
  28476. this._beta = 0;
  28477. this._gamma = 0;
  28478. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28479. metrics.compensateDistorsion = compensateDistorsion;
  28480. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28481. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28482. }
  28483. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28484. this._alpha = +evt.alpha | 0;
  28485. this._beta = +evt.beta | 0;
  28486. this._gamma = +evt.gamma | 0;
  28487. if (this._gamma < 0) {
  28488. this._gamma = 90 + this._gamma;
  28489. }
  28490. else {
  28491. // Incline it in the correct angle.
  28492. this._gamma = 270 - this._gamma;
  28493. }
  28494. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28495. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28496. this.rotation.z = this._beta / 180.0 * Math.PI;
  28497. };
  28498. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28499. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28500. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28501. };
  28502. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28503. _super.prototype.detachControl.call(this, element);
  28504. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28505. };
  28506. return VRDeviceOrientationFreeCamera;
  28507. })(BABYLON.FreeCamera);
  28508. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28509. })(BABYLON || (BABYLON = {}));
  28510. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28511. var __extends = this.__extends || function (d, b) {
  28512. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28513. function __() { this.constructor = d; }
  28514. __.prototype = b.prototype;
  28515. d.prototype = new __();
  28516. };
  28517. var BABYLON;
  28518. (function (BABYLON) {
  28519. var WebVRFreeCamera = (function (_super) {
  28520. __extends(WebVRFreeCamera, _super);
  28521. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  28522. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28523. _super.call(this, name, position, scene);
  28524. this._hmdDevice = null;
  28525. this._sensorDevice = null;
  28526. this._cacheState = null;
  28527. this._cacheQuaternion = new BABYLON.Quaternion();
  28528. this._cacheRotation = BABYLON.Vector3.Zero();
  28529. this._vrEnabled = false;
  28530. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28531. metrics.compensateDistorsion = compensateDistorsion;
  28532. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28533. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28534. }
  28535. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28536. var size = devices.length;
  28537. var i = 0;
  28538. // Reset devices.
  28539. this._sensorDevice = null;
  28540. this._hmdDevice = null;
  28541. // Search for a HmdDevice.
  28542. while (i < size && this._hmdDevice === null) {
  28543. if (devices[i] instanceof HMDVRDevice) {
  28544. this._hmdDevice = devices[i];
  28545. }
  28546. i++;
  28547. }
  28548. i = 0;
  28549. while (i < size && this._sensorDevice === null) {
  28550. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28551. this._sensorDevice = devices[i];
  28552. }
  28553. i++;
  28554. }
  28555. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28556. };
  28557. WebVRFreeCamera.prototype._checkInputs = function () {
  28558. if (this._vrEnabled) {
  28559. this._cacheState = this._sensorDevice.getState();
  28560. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28561. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28562. this.rotation.x = -this._cacheRotation.z;
  28563. this.rotation.y = -this._cacheRotation.y;
  28564. this.rotation.z = this._cacheRotation.x;
  28565. }
  28566. _super.prototype._checkInputs.call(this);
  28567. };
  28568. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28569. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28570. if (navigator.getVRDevices) {
  28571. navigator.getVRDevices().then(this._getWebVRDevices);
  28572. }
  28573. else if (navigator.mozGetVRDevices) {
  28574. navigator.mozGetVRDevices(this._getWebVRDevices);
  28575. }
  28576. };
  28577. WebVRFreeCamera.prototype.detachControl = function (element) {
  28578. _super.prototype.detachControl.call(this, element);
  28579. this._vrEnabled = false;
  28580. };
  28581. return WebVRFreeCamera;
  28582. })(BABYLON.FreeCamera);
  28583. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28584. })(BABYLON || (BABYLON = {}));
  28585. //# sourceMappingURL=babylon.webVRCamera.js.map
  28586. var __extends = this.__extends || function (d, b) {
  28587. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28588. function __() { this.constructor = d; }
  28589. __.prototype = b.prototype;
  28590. d.prototype = new __();
  28591. };
  28592. var BABYLON;
  28593. (function (BABYLON) {
  28594. // Standard optimizations
  28595. var SceneOptimization = (function () {
  28596. function SceneOptimization(priority) {
  28597. if (priority === void 0) { priority = 0; }
  28598. this.priority = priority;
  28599. this.apply = function (scene) {
  28600. return true; // Return true if everything that can be done was applied
  28601. };
  28602. }
  28603. return SceneOptimization;
  28604. })();
  28605. BABYLON.SceneOptimization = SceneOptimization;
  28606. var TextureOptimization = (function (_super) {
  28607. __extends(TextureOptimization, _super);
  28608. function TextureOptimization(priority, maximumSize) {
  28609. var _this = this;
  28610. if (priority === void 0) { priority = 0; }
  28611. if (maximumSize === void 0) { maximumSize = 1024; }
  28612. _super.call(this, priority);
  28613. this.priority = priority;
  28614. this.maximumSize = maximumSize;
  28615. this.apply = function (scene) {
  28616. var allDone = true;
  28617. for (var index = 0; index < scene.textures.length; index++) {
  28618. var texture = scene.textures[index];
  28619. if (!texture.canRescale) {
  28620. continue;
  28621. }
  28622. var currentSize = texture.getSize();
  28623. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28624. if (maxDimension > _this.maximumSize) {
  28625. texture.scale(0.5);
  28626. allDone = false;
  28627. }
  28628. }
  28629. return allDone;
  28630. };
  28631. }
  28632. return TextureOptimization;
  28633. })(SceneOptimization);
  28634. BABYLON.TextureOptimization = TextureOptimization;
  28635. var HardwareScalingOptimization = (function (_super) {
  28636. __extends(HardwareScalingOptimization, _super);
  28637. function HardwareScalingOptimization(priority, maximumScale) {
  28638. var _this = this;
  28639. if (priority === void 0) { priority = 0; }
  28640. if (maximumScale === void 0) { maximumScale = 2; }
  28641. _super.call(this, priority);
  28642. this.priority = priority;
  28643. this.maximumScale = maximumScale;
  28644. this._currentScale = 1;
  28645. this.apply = function (scene) {
  28646. _this._currentScale++;
  28647. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28648. return _this._currentScale >= _this.maximumScale;
  28649. };
  28650. }
  28651. return HardwareScalingOptimization;
  28652. })(SceneOptimization);
  28653. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28654. var ShadowsOptimization = (function (_super) {
  28655. __extends(ShadowsOptimization, _super);
  28656. function ShadowsOptimization() {
  28657. _super.apply(this, arguments);
  28658. this.apply = function (scene) {
  28659. scene.shadowsEnabled = false;
  28660. return true;
  28661. };
  28662. }
  28663. return ShadowsOptimization;
  28664. })(SceneOptimization);
  28665. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28666. var PostProcessesOptimization = (function (_super) {
  28667. __extends(PostProcessesOptimization, _super);
  28668. function PostProcessesOptimization() {
  28669. _super.apply(this, arguments);
  28670. this.apply = function (scene) {
  28671. scene.postProcessesEnabled = false;
  28672. return true;
  28673. };
  28674. }
  28675. return PostProcessesOptimization;
  28676. })(SceneOptimization);
  28677. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28678. var LensFlaresOptimization = (function (_super) {
  28679. __extends(LensFlaresOptimization, _super);
  28680. function LensFlaresOptimization() {
  28681. _super.apply(this, arguments);
  28682. this.apply = function (scene) {
  28683. scene.lensFlaresEnabled = false;
  28684. return true;
  28685. };
  28686. }
  28687. return LensFlaresOptimization;
  28688. })(SceneOptimization);
  28689. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28690. var ParticlesOptimization = (function (_super) {
  28691. __extends(ParticlesOptimization, _super);
  28692. function ParticlesOptimization() {
  28693. _super.apply(this, arguments);
  28694. this.apply = function (scene) {
  28695. scene.particlesEnabled = false;
  28696. return true;
  28697. };
  28698. }
  28699. return ParticlesOptimization;
  28700. })(SceneOptimization);
  28701. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28702. var RenderTargetsOptimization = (function (_super) {
  28703. __extends(RenderTargetsOptimization, _super);
  28704. function RenderTargetsOptimization() {
  28705. _super.apply(this, arguments);
  28706. this.apply = function (scene) {
  28707. scene.renderTargetsEnabled = false;
  28708. return true;
  28709. };
  28710. }
  28711. return RenderTargetsOptimization;
  28712. })(SceneOptimization);
  28713. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28714. var MergeMeshesOptimization = (function (_super) {
  28715. __extends(MergeMeshesOptimization, _super);
  28716. function MergeMeshesOptimization() {
  28717. var _this = this;
  28718. _super.apply(this, arguments);
  28719. this._canBeMerged = function (abstractMesh) {
  28720. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28721. return false;
  28722. }
  28723. var mesh = abstractMesh;
  28724. if (!mesh.isVisible || !mesh.isEnabled()) {
  28725. return false;
  28726. }
  28727. if (mesh.instances.length > 0) {
  28728. return false;
  28729. }
  28730. if (mesh.skeleton || mesh.hasLODLevels) {
  28731. return false;
  28732. }
  28733. return true;
  28734. };
  28735. this.apply = function (scene) {
  28736. var globalPool = scene.meshes.slice(0);
  28737. var globalLength = globalPool.length;
  28738. for (var index = 0; index < globalLength; index++) {
  28739. var currentPool = new Array();
  28740. var current = globalPool[index];
  28741. // Checks
  28742. if (!_this._canBeMerged(current)) {
  28743. continue;
  28744. }
  28745. currentPool.push(current);
  28746. // Find compatible meshes
  28747. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28748. var otherMesh = globalPool[subIndex];
  28749. if (!_this._canBeMerged(otherMesh)) {
  28750. continue;
  28751. }
  28752. if (otherMesh.material !== current.material) {
  28753. continue;
  28754. }
  28755. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28756. continue;
  28757. }
  28758. currentPool.push(otherMesh);
  28759. globalLength--;
  28760. globalPool.splice(subIndex, 1);
  28761. subIndex--;
  28762. }
  28763. if (currentPool.length < 2) {
  28764. continue;
  28765. }
  28766. // Merge meshes
  28767. BABYLON.Mesh.MergeMeshes(currentPool);
  28768. }
  28769. return true;
  28770. };
  28771. }
  28772. return MergeMeshesOptimization;
  28773. })(SceneOptimization);
  28774. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28775. // Options
  28776. var SceneOptimizerOptions = (function () {
  28777. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28778. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28779. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28780. this.targetFrameRate = targetFrameRate;
  28781. this.trackerDuration = trackerDuration;
  28782. this.optimizations = new Array();
  28783. }
  28784. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28785. var result = new SceneOptimizerOptions(targetFrameRate);
  28786. var priority = 0;
  28787. result.optimizations.push(new MergeMeshesOptimization(priority));
  28788. result.optimizations.push(new ShadowsOptimization(priority));
  28789. result.optimizations.push(new LensFlaresOptimization(priority));
  28790. // Next priority
  28791. priority++;
  28792. result.optimizations.push(new PostProcessesOptimization(priority));
  28793. result.optimizations.push(new ParticlesOptimization(priority));
  28794. // Next priority
  28795. priority++;
  28796. result.optimizations.push(new TextureOptimization(priority, 1024));
  28797. return result;
  28798. };
  28799. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28800. var result = new SceneOptimizerOptions(targetFrameRate);
  28801. var priority = 0;
  28802. result.optimizations.push(new MergeMeshesOptimization(priority));
  28803. result.optimizations.push(new ShadowsOptimization(priority));
  28804. result.optimizations.push(new LensFlaresOptimization(priority));
  28805. // Next priority
  28806. priority++;
  28807. result.optimizations.push(new PostProcessesOptimization(priority));
  28808. result.optimizations.push(new ParticlesOptimization(priority));
  28809. // Next priority
  28810. priority++;
  28811. result.optimizations.push(new TextureOptimization(priority, 512));
  28812. // Next priority
  28813. priority++;
  28814. result.optimizations.push(new RenderTargetsOptimization(priority));
  28815. // Next priority
  28816. priority++;
  28817. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28818. return result;
  28819. };
  28820. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28821. var result = new SceneOptimizerOptions(targetFrameRate);
  28822. var priority = 0;
  28823. result.optimizations.push(new MergeMeshesOptimization(priority));
  28824. result.optimizations.push(new ShadowsOptimization(priority));
  28825. result.optimizations.push(new LensFlaresOptimization(priority));
  28826. // Next priority
  28827. priority++;
  28828. result.optimizations.push(new PostProcessesOptimization(priority));
  28829. result.optimizations.push(new ParticlesOptimization(priority));
  28830. // Next priority
  28831. priority++;
  28832. result.optimizations.push(new TextureOptimization(priority, 256));
  28833. // Next priority
  28834. priority++;
  28835. result.optimizations.push(new RenderTargetsOptimization(priority));
  28836. // Next priority
  28837. priority++;
  28838. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28839. return result;
  28840. };
  28841. return SceneOptimizerOptions;
  28842. })();
  28843. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28844. // Scene optimizer tool
  28845. var SceneOptimizer = (function () {
  28846. function SceneOptimizer() {
  28847. }
  28848. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28849. // TODO: add an epsilon
  28850. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28851. if (onSuccess) {
  28852. onSuccess();
  28853. }
  28854. return;
  28855. }
  28856. // Apply current level of optimizations
  28857. var allDone = true;
  28858. var noOptimizationApplied = true;
  28859. for (var index = 0; index < options.optimizations.length; index++) {
  28860. var optimization = options.optimizations[index];
  28861. if (optimization.priority === currentPriorityLevel) {
  28862. noOptimizationApplied = false;
  28863. allDone = allDone && optimization.apply(scene);
  28864. }
  28865. }
  28866. // If no optimization was applied, this is a failure :(
  28867. if (noOptimizationApplied) {
  28868. if (onFailure) {
  28869. onFailure();
  28870. }
  28871. return;
  28872. }
  28873. // If all optimizations were done, move to next level
  28874. if (allDone) {
  28875. currentPriorityLevel++;
  28876. }
  28877. // Let's the system running for a specific amount of time before checking FPS
  28878. scene.executeWhenReady(function () {
  28879. setTimeout(function () {
  28880. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28881. }, options.trackerDuration);
  28882. });
  28883. };
  28884. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28885. if (!options) {
  28886. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28887. }
  28888. // Let's the system running for a specific amount of time before checking FPS
  28889. scene.executeWhenReady(function () {
  28890. setTimeout(function () {
  28891. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28892. }, options.trackerDuration);
  28893. });
  28894. };
  28895. return SceneOptimizer;
  28896. })();
  28897. BABYLON.SceneOptimizer = SceneOptimizer;
  28898. })(BABYLON || (BABYLON = {}));
  28899. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28900. var BABYLON;
  28901. (function (BABYLON) {
  28902. var Internals;
  28903. (function (Internals) {
  28904. var MeshLODLevel = (function () {
  28905. function MeshLODLevel(distance, mesh) {
  28906. this.distance = distance;
  28907. this.mesh = mesh;
  28908. }
  28909. return MeshLODLevel;
  28910. })();
  28911. Internals.MeshLODLevel = MeshLODLevel;
  28912. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28913. })(BABYLON || (BABYLON = {}));
  28914. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28915. var BABYLON;
  28916. (function (BABYLON) {
  28917. var AudioEngine = (function () {
  28918. function AudioEngine() {
  28919. this._audioContext = null;
  28920. this._audioContextInitialized = false;
  28921. this.canUseWebAudio = false;
  28922. this.WarnedWebAudioUnsupported = false;
  28923. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28924. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28925. this.canUseWebAudio = true;
  28926. }
  28927. }
  28928. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28929. get: function () {
  28930. if (!this._audioContextInitialized) {
  28931. this._initializeAudioContext();
  28932. }
  28933. return this._audioContext;
  28934. },
  28935. enumerable: true,
  28936. configurable: true
  28937. });
  28938. AudioEngine.prototype._initializeAudioContext = function () {
  28939. try {
  28940. if (this.canUseWebAudio) {
  28941. this._audioContext = new AudioContext();
  28942. // create a global volume gain node
  28943. this.masterGain = this._audioContext.createGain();
  28944. this.masterGain.gain.value = 1;
  28945. this.masterGain.connect(this._audioContext.destination);
  28946. this._audioContextInitialized = true;
  28947. }
  28948. }
  28949. catch (e) {
  28950. this.canUseWebAudio = false;
  28951. BABYLON.Tools.Error("Web Audio: " + e.message);
  28952. }
  28953. };
  28954. AudioEngine.prototype.dispose = function () {
  28955. if (this.canUseWebAudio && this._audioContextInitialized) {
  28956. if (this._connectedAnalyser) {
  28957. this._connectedAnalyser.stopDebugCanvas();
  28958. this._connectedAnalyser.dispose();
  28959. this.masterGain.disconnect();
  28960. this.masterGain.connect(this._audioContext.destination);
  28961. this._connectedAnalyser = null;
  28962. }
  28963. this.masterGain.gain.value = 1;
  28964. }
  28965. this.WarnedWebAudioUnsupported = false;
  28966. };
  28967. AudioEngine.prototype.getGlobalVolume = function () {
  28968. if (this.canUseWebAudio && this._audioContextInitialized) {
  28969. return this.masterGain.gain.value;
  28970. }
  28971. else {
  28972. return -1;
  28973. }
  28974. };
  28975. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28976. if (this.canUseWebAudio && this._audioContextInitialized) {
  28977. this.masterGain.gain.value = newVolume;
  28978. }
  28979. };
  28980. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28981. if (this._connectedAnalyser) {
  28982. this._connectedAnalyser.stopDebugCanvas();
  28983. }
  28984. if (this.canUseWebAudio && this._audioContextInitialized) {
  28985. this._connectedAnalyser = analyser;
  28986. this.masterGain.disconnect();
  28987. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28988. }
  28989. };
  28990. return AudioEngine;
  28991. })();
  28992. BABYLON.AudioEngine = AudioEngine;
  28993. })(BABYLON || (BABYLON = {}));
  28994. //# sourceMappingURL=babylon.audioEngine.js.map
  28995. var BABYLON;
  28996. (function (BABYLON) {
  28997. var Sound = (function () {
  28998. /**
  28999. * Create a sound and attach it to a scene
  29000. * @param name Name of your sound
  29001. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29002. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29003. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  29004. */
  29005. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29006. var _this = this;
  29007. this.autoplay = false;
  29008. this.loop = false;
  29009. this.useCustomAttenuation = false;
  29010. this.spatialSound = false;
  29011. this.refDistance = 1;
  29012. this.rolloffFactor = 1;
  29013. this.maxDistance = 100;
  29014. this.distanceModel = "linear";
  29015. this._panningModel = "equalpower";
  29016. this._playbackRate = 1;
  29017. this._startTime = 0;
  29018. this._startOffset = 0;
  29019. this._position = BABYLON.Vector3.Zero();
  29020. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29021. this._volume = 1;
  29022. this._isLoaded = false;
  29023. this._isReadyToPlay = false;
  29024. this.isPlaying = false;
  29025. this.isPaused = false;
  29026. this._isDirectional = false;
  29027. // Used if you'd like to create a directional sound.
  29028. // If not set, the sound will be omnidirectional
  29029. this._coneInnerAngle = 360;
  29030. this._coneOuterAngle = 360;
  29031. this._coneOuterGain = 0;
  29032. this.name = name;
  29033. this._scene = scene;
  29034. this._readyToPlayCallback = readyToPlayCallback;
  29035. // Default custom attenuation function is a linear attenuation
  29036. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29037. if (currentDistance < maxDistance) {
  29038. return currentVolume * (1 - currentDistance / maxDistance);
  29039. }
  29040. else {
  29041. return 0;
  29042. }
  29043. };
  29044. if (options) {
  29045. this.autoplay = options.autoplay || false;
  29046. this.loop = options.loop || false;
  29047. // if volume === 0, we need another way to check this option
  29048. if (options.volume !== undefined) {
  29049. this._volume = options.volume;
  29050. }
  29051. this.spatialSound = options.spatialSound || false;
  29052. this.maxDistance = options.maxDistance || 100;
  29053. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29054. this.rolloffFactor = options.rolloffFactor || 1;
  29055. this.refDistance = options.refDistance || 1;
  29056. this.distanceModel = options.distanceModel || "linear";
  29057. this._playbackRate = options.playbackRate || 1;
  29058. }
  29059. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29060. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29061. this._soundGain.gain.value = this._volume;
  29062. this._inputAudioNode = this._soundGain;
  29063. this._ouputAudioNode = this._soundGain;
  29064. if (this.spatialSound) {
  29065. this._createSpatialParameters();
  29066. }
  29067. this._scene.mainSoundTrack.AddSound(this);
  29068. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29069. if (urlOrArrayBuffer) {
  29070. // If it's an URL
  29071. if (typeof (urlOrArrayBuffer) === "string") {
  29072. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  29073. }
  29074. else {
  29075. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29076. this._soundLoaded(urlOrArrayBuffer);
  29077. }
  29078. else {
  29079. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29080. }
  29081. }
  29082. }
  29083. }
  29084. else {
  29085. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29086. this._scene.mainSoundTrack.AddSound(this);
  29087. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29088. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29089. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29090. }
  29091. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29092. if (this._readyToPlayCallback) {
  29093. window.setTimeout(function () {
  29094. _this._readyToPlayCallback();
  29095. }, 1000);
  29096. }
  29097. }
  29098. }
  29099. Sound.prototype.dispose = function () {
  29100. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29101. if (this.isPlaying) {
  29102. this.stop();
  29103. }
  29104. this._isReadyToPlay = false;
  29105. if (this.soundTrackId === -1) {
  29106. this._scene.mainSoundTrack.RemoveSound(this);
  29107. }
  29108. else {
  29109. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29110. }
  29111. if (this._soundGain) {
  29112. this._soundGain.disconnect();
  29113. this._soundGain = null;
  29114. }
  29115. if (this._soundPanner) {
  29116. this._soundPanner.disconnect();
  29117. this._soundPanner = null;
  29118. }
  29119. if (this._soundSource) {
  29120. this._soundSource.disconnect();
  29121. this._soundSource = null;
  29122. }
  29123. this._audioBuffer = null;
  29124. if (this._connectedMesh) {
  29125. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29126. this._connectedMesh = null;
  29127. }
  29128. }
  29129. };
  29130. Sound.prototype._soundLoaded = function (audioData) {
  29131. var _this = this;
  29132. this._isLoaded = true;
  29133. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29134. _this._audioBuffer = buffer;
  29135. _this._isReadyToPlay = true;
  29136. if (_this.autoplay) {
  29137. _this.play();
  29138. }
  29139. if (_this._readyToPlayCallback) {
  29140. _this._readyToPlayCallback();
  29141. }
  29142. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  29143. };
  29144. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29146. this._audioBuffer = audioBuffer;
  29147. this._isReadyToPlay = true;
  29148. }
  29149. };
  29150. Sound.prototype.updateOptions = function (options) {
  29151. if (options) {
  29152. this.loop = options.loop || this.loop;
  29153. this.maxDistance = options.maxDistance || this.maxDistance;
  29154. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29155. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29156. this.refDistance = options.refDistance || this.refDistance;
  29157. this.distanceModel = options.distanceModel || this.distanceModel;
  29158. this._playbackRate = options.playbackRate || this._playbackRate;
  29159. this._updateSpatialParameters();
  29160. if (this.isPlaying) {
  29161. this._soundSource.playbackRate.value = this._playbackRate;
  29162. }
  29163. }
  29164. };
  29165. Sound.prototype._createSpatialParameters = function () {
  29166. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29167. if (this._scene.headphone) {
  29168. this._panningModel = "HRTF";
  29169. }
  29170. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29171. this._updateSpatialParameters();
  29172. this._soundPanner.connect(this._ouputAudioNode);
  29173. this._inputAudioNode = this._soundPanner;
  29174. }
  29175. };
  29176. Sound.prototype._updateSpatialParameters = function () {
  29177. if (this.spatialSound) {
  29178. if (this.useCustomAttenuation) {
  29179. // Tricks to disable in a way embedded Web Audio attenuation
  29180. this._soundPanner.distanceModel = "linear";
  29181. this._soundPanner.maxDistance = Number.MAX_VALUE;
  29182. this._soundPanner.refDistance = 1;
  29183. this._soundPanner.rolloffFactor = 1;
  29184. this._soundPanner.panningModel = this._panningModel;
  29185. }
  29186. else {
  29187. this._soundPanner.distanceModel = this.distanceModel;
  29188. this._soundPanner.maxDistance = this.maxDistance;
  29189. this._soundPanner.refDistance = this.refDistance;
  29190. this._soundPanner.rolloffFactor = this.rolloffFactor;
  29191. this._soundPanner.panningModel = this._panningModel;
  29192. }
  29193. }
  29194. };
  29195. Sound.prototype.switchPanningModelToHRTF = function () {
  29196. this._panningModel = "HRTF";
  29197. this._switchPanningModel();
  29198. };
  29199. Sound.prototype.switchPanningModelToEqualPower = function () {
  29200. this._panningModel = "equalpower";
  29201. this._switchPanningModel();
  29202. };
  29203. Sound.prototype._switchPanningModel = function () {
  29204. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29205. this._soundPanner.panningModel = this._panningModel;
  29206. }
  29207. };
  29208. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29209. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29210. this._ouputAudioNode.disconnect();
  29211. this._ouputAudioNode.connect(soundTrackAudioNode);
  29212. }
  29213. };
  29214. /**
  29215. * Transform this sound into a directional source
  29216. * @param coneInnerAngle Size of the inner cone in degree
  29217. * @param coneOuterAngle Size of the outer cone in degree
  29218. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29219. */
  29220. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29221. if (coneOuterAngle < coneInnerAngle) {
  29222. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29223. return;
  29224. }
  29225. this._coneInnerAngle = coneInnerAngle;
  29226. this._coneOuterAngle = coneOuterAngle;
  29227. this._coneOuterGain = coneOuterGain;
  29228. this._isDirectional = true;
  29229. if (this.isPlaying && this.loop) {
  29230. this.stop();
  29231. this.play();
  29232. }
  29233. };
  29234. Sound.prototype.setPosition = function (newPosition) {
  29235. this._position = newPosition;
  29236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29237. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29238. }
  29239. };
  29240. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  29241. this._localDirection = newLocalDirection;
  29242. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  29243. this._updateDirection();
  29244. }
  29245. };
  29246. Sound.prototype._updateDirection = function () {
  29247. var mat = this._connectedMesh.getWorldMatrix();
  29248. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29249. direction.normalize();
  29250. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29251. };
  29252. Sound.prototype.updateDistanceFromListener = function () {
  29253. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29254. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29255. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29256. }
  29257. };
  29258. Sound.prototype.setAttenuationFunction = function (callback) {
  29259. this._customAttenuationFunction = callback;
  29260. };
  29261. /**
  29262. * Play the sound
  29263. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29264. */
  29265. Sound.prototype.play = function (time) {
  29266. var _this = this;
  29267. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29268. try {
  29269. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29270. if (!this._soundSource) {
  29271. if (this.spatialSound) {
  29272. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29273. if (this._isDirectional) {
  29274. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29275. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29276. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29277. if (this._connectedMesh) {
  29278. this._updateDirection();
  29279. }
  29280. else {
  29281. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29282. }
  29283. }
  29284. }
  29285. }
  29286. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29287. this._soundSource.buffer = this._audioBuffer;
  29288. this._soundSource.connect(this._inputAudioNode);
  29289. this._soundSource.loop = this.loop;
  29290. this._soundSource.playbackRate.value = this._playbackRate;
  29291. this._startTime = startTime;
  29292. this._soundSource.onended = function () { _this._onended(); };
  29293. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29294. this.isPlaying = true;
  29295. this.isPaused = false;
  29296. }
  29297. catch (ex) {
  29298. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29299. }
  29300. }
  29301. };
  29302. Sound.prototype._onended = function () {
  29303. this.isPlaying = false;
  29304. if (this.onended) {
  29305. this.onended();
  29306. }
  29307. };
  29308. /**
  29309. * Stop the sound
  29310. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29311. */
  29312. Sound.prototype.stop = function (time) {
  29313. if (this.isPlaying) {
  29314. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29315. this._soundSource.stop(stopTime);
  29316. this.isPlaying = false;
  29317. }
  29318. };
  29319. Sound.prototype.pause = function () {
  29320. if (this.isPlaying) {
  29321. this.stop(0);
  29322. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29323. this.isPaused = true;
  29324. }
  29325. };
  29326. Sound.prototype.setVolume = function (newVolume, time) {
  29327. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29328. if (time) {
  29329. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29330. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29331. }
  29332. else {
  29333. this._soundGain.gain.value = newVolume;
  29334. }
  29335. }
  29336. this._volume = newVolume;
  29337. };
  29338. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29339. this._playbackRate = newPlaybackRate;
  29340. if (this.isPlaying) {
  29341. this._soundSource.playbackRate.value = this._playbackRate;
  29342. }
  29343. };
  29344. Sound.prototype.getVolume = function () {
  29345. return this._volume;
  29346. };
  29347. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29348. var _this = this;
  29349. this._connectedMesh = meshToConnectTo;
  29350. if (!this.spatialSound) {
  29351. this.spatialSound = true;
  29352. this._createSpatialParameters();
  29353. if (this.isPlaying && this.loop) {
  29354. this.stop();
  29355. this.play();
  29356. }
  29357. }
  29358. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29359. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29360. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29361. };
  29362. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29363. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29364. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29365. this._updateDirection();
  29366. }
  29367. };
  29368. return Sound;
  29369. })();
  29370. BABYLON.Sound = Sound;
  29371. })(BABYLON || (BABYLON = {}));
  29372. //# sourceMappingURL=babylon.sound.js.map
  29373. var BABYLON;
  29374. (function (BABYLON) {
  29375. var SoundTrack = (function () {
  29376. function SoundTrack(scene, options) {
  29377. this.id = -1;
  29378. this._isMainTrack = false;
  29379. this._scene = scene;
  29380. this._audioEngine = BABYLON.Engine.audioEngine;
  29381. this.soundCollection = new Array();
  29382. if (this._audioEngine.canUseWebAudio) {
  29383. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  29384. this._outputAudioNode.connect(this._audioEngine.masterGain);
  29385. if (options) {
  29386. if (options.volume) {
  29387. this._outputAudioNode.gain.value = options.volume;
  29388. }
  29389. if (options.mainTrack) {
  29390. this._isMainTrack = options.mainTrack;
  29391. }
  29392. }
  29393. }
  29394. if (!this._isMainTrack) {
  29395. this._scene.soundTracks.push(this);
  29396. this.id = this._scene.soundTracks.length - 1;
  29397. }
  29398. }
  29399. SoundTrack.prototype.dispose = function () {
  29400. if (this._audioEngine.canUseWebAudio) {
  29401. if (this._connectedAnalyser) {
  29402. this._connectedAnalyser.stopDebugCanvas();
  29403. }
  29404. while (this.soundCollection.length) {
  29405. this.soundCollection[0].dispose();
  29406. }
  29407. this._outputAudioNode.disconnect();
  29408. this._outputAudioNode = null;
  29409. }
  29410. };
  29411. SoundTrack.prototype.AddSound = function (sound) {
  29412. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29413. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  29414. }
  29415. if (sound.soundTrackId) {
  29416. if (sound.soundTrackId === -1) {
  29417. this._scene.mainSoundTrack.RemoveSound(sound);
  29418. }
  29419. else {
  29420. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29421. }
  29422. }
  29423. this.soundCollection.push(sound);
  29424. sound.soundTrackId = this.id;
  29425. };
  29426. SoundTrack.prototype.RemoveSound = function (sound) {
  29427. var index = this.soundCollection.indexOf(sound);
  29428. if (index !== -1) {
  29429. this.soundCollection.splice(index, 1);
  29430. }
  29431. };
  29432. SoundTrack.prototype.setVolume = function (newVolume) {
  29433. if (this._audioEngine.canUseWebAudio) {
  29434. this._outputAudioNode.gain.value = newVolume;
  29435. }
  29436. };
  29437. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29438. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29439. for (var i = 0; i < this.soundCollection.length; i++) {
  29440. this.soundCollection[i].switchPanningModelToHRTF();
  29441. }
  29442. }
  29443. };
  29444. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29445. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29446. for (var i = 0; i < this.soundCollection.length; i++) {
  29447. this.soundCollection[i].switchPanningModelToEqualPower();
  29448. }
  29449. }
  29450. };
  29451. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29452. if (this._connectedAnalyser) {
  29453. this._connectedAnalyser.stopDebugCanvas();
  29454. }
  29455. this._connectedAnalyser = analyser;
  29456. if (this._audioEngine.canUseWebAudio) {
  29457. this._outputAudioNode.disconnect();
  29458. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  29459. }
  29460. };
  29461. return SoundTrack;
  29462. })();
  29463. BABYLON.SoundTrack = SoundTrack;
  29464. })(BABYLON || (BABYLON = {}));
  29465. //# sourceMappingURL=babylon.soundtrack.js.map
  29466. var BABYLON;
  29467. (function (BABYLON) {
  29468. var DebugLayer = (function () {
  29469. function DebugLayer(scene) {
  29470. var _this = this;
  29471. this._transformationMatrix = BABYLON.Matrix.Identity();
  29472. this._enabled = false;
  29473. this._labelsEnabled = false;
  29474. this._displayStatistics = true;
  29475. this._displayTree = false;
  29476. this._displayLogs = false;
  29477. this._identityMatrix = BABYLON.Matrix.Identity();
  29478. this.axisRatio = 0.02;
  29479. this.accentColor = "orange";
  29480. this._scene = scene;
  29481. this._syncPositions = function () {
  29482. var engine = _this._scene.getEngine();
  29483. var canvasRect = engine.getRenderingCanvasClientRect();
  29484. if (_this._showUI) {
  29485. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29486. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29487. _this._statsDiv.style.width = "400px";
  29488. _this._statsDiv.style.height = "auto";
  29489. _this._statsSubsetDiv.style.maxHeight = "240px";
  29490. _this._optionsDiv.style.left = "0px";
  29491. _this._optionsDiv.style.top = "10px";
  29492. _this._optionsDiv.style.width = "200px";
  29493. _this._optionsDiv.style.height = "auto";
  29494. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29495. _this._logDiv.style.left = "0px";
  29496. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29497. _this._logDiv.style.width = "600px";
  29498. _this._logDiv.style.height = "160px";
  29499. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29500. _this._treeDiv.style.top = "10px";
  29501. _this._treeDiv.style.width = "300px";
  29502. _this._treeDiv.style.height = "auto";
  29503. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29504. }
  29505. _this._globalDiv.style.left = canvasRect.left + "px";
  29506. _this._globalDiv.style.top = canvasRect.top + "px";
  29507. _this._drawingCanvas.style.left = "0px";
  29508. _this._drawingCanvas.style.top = "0px";
  29509. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29510. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29511. var devicePixelRatio = window.devicePixelRatio || 1;
  29512. var context = _this._drawingContext;
  29513. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29514. context.mozBackingStorePixelRatio ||
  29515. context.msBackingStorePixelRatio ||
  29516. context.oBackingStorePixelRatio ||
  29517. context.backingStorePixelRatio || 1;
  29518. _this._ratio = devicePixelRatio / backingStoreRatio;
  29519. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29520. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29521. };
  29522. this._onCanvasClick = function (evt) {
  29523. _this._clickPosition = {
  29524. x: evt.clientX * _this._ratio,
  29525. y: evt.clientY * _this._ratio
  29526. };
  29527. };
  29528. this._syncUI = function () {
  29529. if (_this._showUI) {
  29530. if (_this._displayStatistics) {
  29531. _this._displayStats();
  29532. _this._statsDiv.style.display = "";
  29533. }
  29534. else {
  29535. _this._statsDiv.style.display = "none";
  29536. }
  29537. if (_this._displayLogs) {
  29538. _this._logDiv.style.display = "";
  29539. }
  29540. else {
  29541. _this._logDiv.style.display = "none";
  29542. }
  29543. if (_this._displayTree) {
  29544. _this._treeDiv.style.display = "";
  29545. if (_this._needToRefreshMeshesTree) {
  29546. _this._needToRefreshMeshesTree = false;
  29547. _this._refreshMeshesTreeContent();
  29548. }
  29549. }
  29550. else {
  29551. _this._treeDiv.style.display = "none";
  29552. }
  29553. }
  29554. };
  29555. this._syncData = function () {
  29556. if (_this._labelsEnabled || !_this._showUI) {
  29557. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29558. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29559. var engine = _this._scene.getEngine();
  29560. var viewport = _this._camera.viewport;
  29561. var globalViewport = viewport.toGlobal(engine);
  29562. // Meshes
  29563. var meshes = _this._camera.getActiveMeshes();
  29564. for (var index = 0; index < meshes.length; index++) {
  29565. var mesh = meshes.data[index];
  29566. var position = mesh.getBoundingInfo().boundingSphere.center;
  29567. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29568. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29569. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29570. }
  29571. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29572. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29573. }
  29574. }
  29575. // Cameras
  29576. var cameras = _this._scene.cameras;
  29577. for (index = 0; index < cameras.length; index++) {
  29578. var camera = cameras[index];
  29579. if (camera === _this._camera) {
  29580. continue;
  29581. }
  29582. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29583. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29584. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29585. _this._camera.detachControl(engine.getRenderingCanvas());
  29586. _this._camera = camera;
  29587. _this._camera.attachControl(engine.getRenderingCanvas());
  29588. }, function () { return "purple"; });
  29589. }
  29590. }
  29591. // Lights
  29592. var lights = _this._scene.lights;
  29593. for (index = 0; index < lights.length; index++) {
  29594. var light = lights[index];
  29595. if (light.position) {
  29596. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29597. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29598. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29599. light.setEnabled(!light.isEnabled());
  29600. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29601. }
  29602. }
  29603. }
  29604. }
  29605. _this._clickPosition = undefined;
  29606. };
  29607. }
  29608. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29609. while (this._treeSubsetDiv.hasChildNodes()) {
  29610. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29611. }
  29612. // Add meshes
  29613. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29614. sortedArray.sort(function (a, b) {
  29615. if (a.name === b.name) {
  29616. return 0;
  29617. }
  29618. return (a.name > b.name) ? 1 : -1;
  29619. });
  29620. for (var index = 0; index < sortedArray.length; index++) {
  29621. var mesh = sortedArray[index];
  29622. if (!mesh.isEnabled()) {
  29623. continue;
  29624. }
  29625. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29626. m.isVisible = element.checked;
  29627. }, mesh);
  29628. }
  29629. };
  29630. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29631. this._drawingContext.beginPath();
  29632. this._drawingContext.moveTo(zero.x, zero.y);
  29633. this._drawingContext.lineTo(unit.x, unit.y);
  29634. this._drawingContext.strokeStyle = color;
  29635. this._drawingContext.lineWidth = 4;
  29636. this._drawingContext.stroke();
  29637. this._drawingContext.font = "normal 14px Segoe UI";
  29638. this._drawingContext.fillStyle = color;
  29639. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29640. };
  29641. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29642. var position = mesh.getBoundingInfo().boundingSphere.center;
  29643. var worldMatrix = mesh.getWorldMatrix();
  29644. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29645. var unit = (unprojectedVector.subtract(position)).length();
  29646. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29647. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29648. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29649. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29650. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29651. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29652. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29653. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29654. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29655. };
  29656. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29657. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29658. this._drawingContext.font = "normal 12px Segoe UI";
  29659. var textMetrics = this._drawingContext.measureText(text);
  29660. var centerX = projectedPosition.x - textMetrics.width / 2;
  29661. var centerY = projectedPosition.y;
  29662. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29663. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29664. onClick();
  29665. }
  29666. this._drawingContext.beginPath();
  29667. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29668. this._drawingContext.fillStyle = getFillStyle();
  29669. this._drawingContext.globalAlpha = 0.5;
  29670. this._drawingContext.fill();
  29671. this._drawingContext.globalAlpha = 1.0;
  29672. this._drawingContext.strokeStyle = '#FFFFFF';
  29673. this._drawingContext.lineWidth = 1;
  29674. this._drawingContext.stroke();
  29675. this._drawingContext.fillStyle = "#FFFFFF";
  29676. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29677. this._drawingContext.beginPath();
  29678. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29679. this._drawingContext.fill();
  29680. }
  29681. };
  29682. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29683. if (!this._clickPosition) {
  29684. return false;
  29685. }
  29686. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29687. return false;
  29688. }
  29689. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29690. return false;
  29691. }
  29692. return true;
  29693. };
  29694. DebugLayer.prototype.isVisible = function () {
  29695. return this._enabled;
  29696. };
  29697. DebugLayer.prototype.hide = function () {
  29698. if (!this._enabled) {
  29699. return;
  29700. }
  29701. this._enabled = false;
  29702. var engine = this._scene.getEngine();
  29703. this._scene.unregisterBeforeRender(this._syncData);
  29704. this._scene.unregisterAfterRender(this._syncUI);
  29705. document.body.removeChild(this._globalDiv);
  29706. window.removeEventListener("resize", this._syncPositions);
  29707. this._scene.forceShowBoundingBoxes = false;
  29708. this._scene.forceWireframe = false;
  29709. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29710. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29711. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29712. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29713. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29714. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29715. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29716. this._scene.shadowsEnabled = true;
  29717. this._scene.particlesEnabled = true;
  29718. this._scene.postProcessesEnabled = true;
  29719. this._scene.collisionsEnabled = true;
  29720. this._scene.lightsEnabled = true;
  29721. this._scene.texturesEnabled = true;
  29722. this._scene.lensFlaresEnabled = true;
  29723. this._scene.proceduralTexturesEnabled = true;
  29724. this._scene.renderTargetsEnabled = true;
  29725. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29726. };
  29727. DebugLayer.prototype.show = function (showUI, camera) {
  29728. if (showUI === void 0) { showUI = true; }
  29729. if (camera === void 0) { camera = null; }
  29730. if (this._enabled) {
  29731. return;
  29732. }
  29733. this._enabled = true;
  29734. if (camera) {
  29735. this._camera = camera;
  29736. }
  29737. else {
  29738. this._camera = this._scene.activeCamera;
  29739. }
  29740. this._showUI = showUI;
  29741. var engine = this._scene.getEngine();
  29742. this._globalDiv = document.createElement("div");
  29743. document.body.appendChild(this._globalDiv);
  29744. this._generateDOMelements();
  29745. window.addEventListener("resize", this._syncPositions);
  29746. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29747. this._syncPositions();
  29748. this._scene.registerBeforeRender(this._syncData);
  29749. this._scene.registerAfterRender(this._syncUI);
  29750. };
  29751. DebugLayer.prototype._clearLabels = function () {
  29752. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29753. for (var index = 0; index < this._scene.meshes.length; index++) {
  29754. var mesh = this._scene.meshes[index];
  29755. mesh.renderOverlay = false;
  29756. }
  29757. };
  29758. DebugLayer.prototype._generateheader = function (root, text) {
  29759. var header = document.createElement("div");
  29760. header.innerHTML = text + "&nbsp;";
  29761. header.style.textAlign = "right";
  29762. header.style.width = "100%";
  29763. header.style.color = "white";
  29764. header.style.backgroundColor = "Black";
  29765. header.style.padding = "5px 5px 4px 0px";
  29766. header.style.marginLeft = "-5px";
  29767. header.style.fontWeight = "bold";
  29768. root.appendChild(header);
  29769. };
  29770. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29771. var label = document.createElement("label");
  29772. label.innerHTML = title;
  29773. label.style.color = color;
  29774. root.appendChild(label);
  29775. root.appendChild(document.createElement("br"));
  29776. };
  29777. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29778. if (tag === void 0) { tag = null; }
  29779. var label = document.createElement("label");
  29780. var boundingBoxesCheckbox = document.createElement("input");
  29781. boundingBoxesCheckbox.type = "checkbox";
  29782. boundingBoxesCheckbox.checked = initialState;
  29783. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29784. task(evt.target, tag);
  29785. });
  29786. label.appendChild(boundingBoxesCheckbox);
  29787. var container = document.createElement("span");
  29788. var leftPart = document.createElement("span");
  29789. var rightPart = document.createElement("span");
  29790. rightPart.style.cssFloat = "right";
  29791. leftPart.innerHTML = leftTitle;
  29792. rightPart.innerHTML = rightTitle;
  29793. rightPart.style.fontSize = "12px";
  29794. rightPart.style.maxWidth = "200px";
  29795. container.appendChild(leftPart);
  29796. container.appendChild(rightPart);
  29797. label.appendChild(container);
  29798. root.appendChild(label);
  29799. root.appendChild(document.createElement("br"));
  29800. };
  29801. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29802. if (tag === void 0) { tag = null; }
  29803. var label = document.createElement("label");
  29804. var checkBox = document.createElement("input");
  29805. checkBox.type = "checkbox";
  29806. checkBox.checked = initialState;
  29807. checkBox.addEventListener("change", function (evt) {
  29808. task(evt.target, tag);
  29809. });
  29810. label.appendChild(checkBox);
  29811. label.appendChild(document.createTextNode(title));
  29812. root.appendChild(label);
  29813. root.appendChild(document.createElement("br"));
  29814. };
  29815. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29816. if (tag === void 0) { tag = null; }
  29817. var button = document.createElement("button");
  29818. button.innerHTML = title;
  29819. button.style.height = "24px";
  29820. button.style.color = "#444444";
  29821. button.style.border = "1px solid white";
  29822. button.className = "debugLayerButton";
  29823. button.addEventListener("click", function (evt) {
  29824. task(evt.target, tag);
  29825. });
  29826. root.appendChild(button);
  29827. root.appendChild(document.createElement("br"));
  29828. };
  29829. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29830. if (tag === void 0) { tag = null; }
  29831. var label = document.createElement("label");
  29832. var boundingBoxesRadio = document.createElement("input");
  29833. boundingBoxesRadio.type = "radio";
  29834. boundingBoxesRadio.name = name;
  29835. boundingBoxesRadio.checked = initialState;
  29836. boundingBoxesRadio.addEventListener("change", function (evt) {
  29837. task(evt.target, tag);
  29838. });
  29839. label.appendChild(boundingBoxesRadio);
  29840. label.appendChild(document.createTextNode(title));
  29841. root.appendChild(label);
  29842. root.appendChild(document.createElement("br"));
  29843. };
  29844. DebugLayer.prototype._generateDOMelements = function () {
  29845. var _this = this;
  29846. this._globalDiv.id = "DebugLayer";
  29847. this._globalDiv.style.position = "absolute";
  29848. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29849. this._globalDiv.style.fontSize = "14px";
  29850. this._globalDiv.style.color = "white";
  29851. // Drawing canvas
  29852. this._drawingCanvas = document.createElement("canvas");
  29853. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29854. this._drawingCanvas.style.position = "absolute";
  29855. this._drawingCanvas.style.pointerEvents = "none";
  29856. this._drawingContext = this._drawingCanvas.getContext("2d");
  29857. this._globalDiv.appendChild(this._drawingCanvas);
  29858. if (this._showUI) {
  29859. var background = "rgba(128, 128, 128, 0.4)";
  29860. var border = "rgb(180, 180, 180) solid 1px";
  29861. // Stats
  29862. this._statsDiv = document.createElement("div");
  29863. this._statsDiv.id = "DebugLayerStats";
  29864. this._statsDiv.style.border = border;
  29865. this._statsDiv.style.position = "absolute";
  29866. this._statsDiv.style.background = background;
  29867. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29868. this._generateheader(this._statsDiv, "STATISTICS");
  29869. this._statsSubsetDiv = document.createElement("div");
  29870. this._statsSubsetDiv.style.paddingTop = "5px";
  29871. this._statsSubsetDiv.style.paddingBottom = "5px";
  29872. this._statsSubsetDiv.style.overflowY = "auto";
  29873. this._statsDiv.appendChild(this._statsSubsetDiv);
  29874. // Tree
  29875. this._treeDiv = document.createElement("div");
  29876. this._treeDiv.id = "DebugLayerTree";
  29877. this._treeDiv.style.border = border;
  29878. this._treeDiv.style.position = "absolute";
  29879. this._treeDiv.style.background = background;
  29880. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29881. this._treeDiv.style.display = "none";
  29882. this._generateheader(this._treeDiv, "MESHES TREE");
  29883. this._treeSubsetDiv = document.createElement("div");
  29884. this._treeSubsetDiv.style.paddingTop = "5px";
  29885. this._treeSubsetDiv.style.paddingRight = "5px";
  29886. this._treeSubsetDiv.style.overflowY = "auto";
  29887. this._treeSubsetDiv.style.maxHeight = "300px";
  29888. this._treeDiv.appendChild(this._treeSubsetDiv);
  29889. this._needToRefreshMeshesTree = true;
  29890. // Logs
  29891. this._logDiv = document.createElement("div");
  29892. this._logDiv.style.border = border;
  29893. this._logDiv.id = "DebugLayerLogs";
  29894. this._logDiv.style.position = "absolute";
  29895. this._logDiv.style.background = background;
  29896. this._logDiv.style.padding = "0px 0px 0px 5px";
  29897. this._logDiv.style.display = "none";
  29898. this._generateheader(this._logDiv, "LOGS");
  29899. this._logSubsetDiv = document.createElement("div");
  29900. this._logSubsetDiv.style.height = "127px";
  29901. this._logSubsetDiv.style.paddingTop = "5px";
  29902. this._logSubsetDiv.style.overflowY = "auto";
  29903. this._logSubsetDiv.style.fontSize = "12px";
  29904. this._logSubsetDiv.style.fontFamily = "consolas";
  29905. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29906. this._logDiv.appendChild(this._logSubsetDiv);
  29907. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29908. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29909. };
  29910. // Options
  29911. this._optionsDiv = document.createElement("div");
  29912. this._optionsDiv.id = "DebugLayerOptions";
  29913. this._optionsDiv.style.border = border;
  29914. this._optionsDiv.style.position = "absolute";
  29915. this._optionsDiv.style.background = background;
  29916. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29917. this._optionsDiv.style.overflowY = "auto";
  29918. this._generateheader(this._optionsDiv, "OPTIONS");
  29919. this._optionsSubsetDiv = document.createElement("div");
  29920. this._optionsSubsetDiv.style.paddingTop = "5px";
  29921. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29922. this._optionsSubsetDiv.style.overflowY = "auto";
  29923. this._optionsSubsetDiv.style.maxHeight = "200px";
  29924. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29925. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29926. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29927. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29928. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29929. _this._displayTree = element.checked;
  29930. _this._needToRefreshMeshesTree = true;
  29931. });
  29932. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29933. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29934. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29935. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29936. _this._labelsEnabled = element.checked;
  29937. if (!_this._labelsEnabled) {
  29938. _this._clearLabels();
  29939. }
  29940. });
  29941. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29942. if (element.checked) {
  29943. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29944. }
  29945. else {
  29946. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29947. }
  29948. });
  29949. ;
  29950. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29951. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29952. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29953. if (element.checked) {
  29954. _this._scene.forceWireframe = false;
  29955. _this._scene.forcePointsCloud = false;
  29956. }
  29957. });
  29958. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29959. if (element.checked) {
  29960. _this._scene.forceWireframe = true;
  29961. _this._scene.forcePointsCloud = false;
  29962. }
  29963. });
  29964. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29965. if (element.checked) {
  29966. _this._scene.forceWireframe = false;
  29967. _this._scene.forcePointsCloud = true;
  29968. }
  29969. });
  29970. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29971. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29972. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29973. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29974. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29975. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29976. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29977. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29978. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29979. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29980. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29981. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29982. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29983. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29984. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29985. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29986. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29987. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29988. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29989. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29990. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29991. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29992. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29993. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29994. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29995. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29996. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29997. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29998. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29999. if (element.checked) {
  30000. _this._scene.headphone = true;
  30001. }
  30002. });
  30003. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  30004. if (element.checked) {
  30005. _this._scene.headphone = false;
  30006. }
  30007. });
  30008. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  30009. _this._scene.audioEnabled = !element.checked;
  30010. });
  30011. }
  30012. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30013. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  30014. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  30015. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30016. this._globalDiv.appendChild(this._statsDiv);
  30017. this._globalDiv.appendChild(this._logDiv);
  30018. this._globalDiv.appendChild(this._optionsDiv);
  30019. this._globalDiv.appendChild(this._treeDiv);
  30020. }
  30021. };
  30022. DebugLayer.prototype._displayStats = function () {
  30023. var scene = this._scene;
  30024. var engine = scene.getEngine();
  30025. var glInfo = engine.getGlInfo();
  30026. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  30027. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30028. + "<b>Count</b><br>"
  30029. + "Total meshes: " + scene.meshes.length + "<br>"
  30030. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  30031. + "Total materials: " + scene.materials.length + "<br>"
  30032. + "Total textures: " + scene.textures.length + "<br>"
  30033. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  30034. + "Active indices: " + scene.getActiveIndices() + "<br>"
  30035. + "Active bones: " + scene.getActiveBones() + "<br>"
  30036. + "Active particles: " + scene.getActiveParticles() + "<br>"
  30037. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  30038. + "<b>Duration</b><br>"
  30039. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  30040. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  30041. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  30042. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  30043. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  30044. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  30045. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  30046. + "</div>"
  30047. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30048. + "<b>Extensions</b><br>"
  30049. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  30050. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  30051. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  30052. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  30053. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  30054. + "<b>Caps.</b><br>"
  30055. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  30056. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  30057. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  30058. + "</div><br>"
  30059. + "<b>Info</b><br>"
  30060. + glInfo.version + "<br>"
  30061. + glInfo.renderer + "<br>";
  30062. if (this.customStatsFunction) {
  30063. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  30064. }
  30065. };
  30066. return DebugLayer;
  30067. })();
  30068. BABYLON.DebugLayer = DebugLayer;
  30069. })(BABYLON || (BABYLON = {}));
  30070. //# sourceMappingURL=babylon.debugLayer.js.map
  30071. var __extends = this.__extends || function (d, b) {
  30072. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30073. function __() { this.constructor = d; }
  30074. __.prototype = b.prototype;
  30075. d.prototype = new __();
  30076. };
  30077. var BABYLON;
  30078. (function (BABYLON) {
  30079. var RawTexture = (function (_super) {
  30080. __extends(RawTexture, _super);
  30081. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  30082. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30083. if (invertY === void 0) { invertY = false; }
  30084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30085. _super.call(this, null, scene, !generateMipMaps, invertY);
  30086. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  30087. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30088. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30089. }
  30090. // Statics
  30091. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30092. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30093. if (invertY === void 0) { invertY = false; }
  30094. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30095. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  30096. };
  30097. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30098. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30099. if (invertY === void 0) { invertY = false; }
  30100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30101. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30102. };
  30103. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30104. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30105. if (invertY === void 0) { invertY = false; }
  30106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30107. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30108. };
  30109. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30110. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30111. if (invertY === void 0) { invertY = false; }
  30112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30113. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  30114. };
  30115. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30116. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30117. if (invertY === void 0) { invertY = false; }
  30118. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30119. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  30120. };
  30121. return RawTexture;
  30122. })(BABYLON.Texture);
  30123. BABYLON.RawTexture = RawTexture;
  30124. })(BABYLON || (BABYLON = {}));
  30125. //# sourceMappingURL=babylon.rawTexture.js.map
  30126. var __extends = this.__extends || function (d, b) {
  30127. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30128. function __() { this.constructor = d; }
  30129. __.prototype = b.prototype;
  30130. d.prototype = new __();
  30131. };
  30132. var BABYLON;
  30133. (function (BABYLON) {
  30134. var IndexedVector2 = (function (_super) {
  30135. __extends(IndexedVector2, _super);
  30136. function IndexedVector2(original, index) {
  30137. _super.call(this, original.x, original.y);
  30138. this.index = index;
  30139. }
  30140. return IndexedVector2;
  30141. })(BABYLON.Vector2);
  30142. var PolygonPoints = (function () {
  30143. function PolygonPoints() {
  30144. this.elements = new Array();
  30145. }
  30146. PolygonPoints.prototype.add = function (originalPoints) {
  30147. var _this = this;
  30148. var result = new Array();
  30149. originalPoints.forEach(function (point) {
  30150. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  30151. var newPoint = new IndexedVector2(point, _this.elements.length);
  30152. result.push(newPoint);
  30153. _this.elements.push(newPoint);
  30154. }
  30155. });
  30156. return result;
  30157. };
  30158. PolygonPoints.prototype.computeBounds = function () {
  30159. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30160. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30161. this.elements.forEach(function (point) {
  30162. // x
  30163. if (point.x < lmin.x) {
  30164. lmin.x = point.x;
  30165. }
  30166. else if (point.x > lmax.x) {
  30167. lmax.x = point.x;
  30168. }
  30169. // y
  30170. if (point.y < lmin.y) {
  30171. lmin.y = point.y;
  30172. }
  30173. else if (point.y > lmax.y) {
  30174. lmax.y = point.y;
  30175. }
  30176. });
  30177. return {
  30178. min: lmin,
  30179. max: lmax,
  30180. width: lmax.x - lmin.x,
  30181. height: lmax.y - lmin.y
  30182. };
  30183. };
  30184. return PolygonPoints;
  30185. })();
  30186. var Polygon = (function () {
  30187. function Polygon() {
  30188. }
  30189. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  30190. return [
  30191. new BABYLON.Vector2(xmin, ymin),
  30192. new BABYLON.Vector2(xmax, ymin),
  30193. new BABYLON.Vector2(xmax, ymax),
  30194. new BABYLON.Vector2(xmin, ymax)
  30195. ];
  30196. };
  30197. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  30198. if (cx === void 0) { cx = 0; }
  30199. if (cy === void 0) { cy = 0; }
  30200. if (numberOfSides === void 0) { numberOfSides = 32; }
  30201. var result = new Array();
  30202. var angle = 0;
  30203. var increment = (Math.PI * 2) / numberOfSides;
  30204. for (var i = 0; i < numberOfSides; i++) {
  30205. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  30206. angle -= increment;
  30207. }
  30208. return result;
  30209. };
  30210. Polygon.Parse = function (input) {
  30211. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  30212. var i, result = [];
  30213. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  30214. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  30215. }
  30216. return result;
  30217. };
  30218. Polygon.StartingAt = function (x, y) {
  30219. return BABYLON.Path2.StartingAt(x, y);
  30220. };
  30221. return Polygon;
  30222. })();
  30223. BABYLON.Polygon = Polygon;
  30224. var PolygonMeshBuilder = (function () {
  30225. function PolygonMeshBuilder(name, contours, scene) {
  30226. this._points = new PolygonPoints();
  30227. this._outlinepoints = new PolygonPoints();
  30228. this._holes = [];
  30229. if (!("poly2tri" in window)) {
  30230. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  30231. }
  30232. this._name = name;
  30233. this._scene = scene;
  30234. var points;
  30235. if (contours instanceof BABYLON.Path2) {
  30236. points = contours.getPoints();
  30237. }
  30238. else {
  30239. points = contours;
  30240. }
  30241. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  30242. this._outlinepoints.add(points);
  30243. }
  30244. PolygonMeshBuilder.prototype.addHole = function (hole) {
  30245. this._swctx.addHole(this._points.add(hole));
  30246. var holepoints = new PolygonPoints();
  30247. holepoints.add(hole);
  30248. this._holes.push(holepoints);
  30249. return this;
  30250. };
  30251. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  30252. var _this = this;
  30253. if (updatable === void 0) { updatable = false; }
  30254. var result = new BABYLON.Mesh(this._name, this._scene);
  30255. var normals = [];
  30256. var positions = [];
  30257. var uvs = [];
  30258. var bounds = this._points.computeBounds();
  30259. this._points.elements.forEach(function (p) {
  30260. normals.push(0, 1.0, 0);
  30261. positions.push(p.x, 0, p.y);
  30262. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  30263. });
  30264. var indices = [];
  30265. this._swctx.triangulate();
  30266. this._swctx.getTriangles().forEach(function (triangle) {
  30267. triangle.getPoints().forEach(function (point) {
  30268. indices.push(point.index);
  30269. });
  30270. });
  30271. if (depth > 0) {
  30272. var positionscount = (positions.length / 3); //get the current pointcount
  30273. this._points.elements.forEach(function (p) {
  30274. normals.push(0, -1.0, 0);
  30275. positions.push(p.x, -depth, p.y);
  30276. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  30277. });
  30278. var p1; //we need to change order of point so the triangles are made in the rigth way.
  30279. var p2;
  30280. var poscounter = 0;
  30281. this._swctx.getTriangles().forEach(function (triangle) {
  30282. triangle.getPoints().forEach(function (point) {
  30283. switch (poscounter) {
  30284. case 0:
  30285. p1 = point;
  30286. break;
  30287. case 1:
  30288. p2 = point;
  30289. break;
  30290. case 2:
  30291. indices.push(point.index + positionscount);
  30292. indices.push(p2.index + positionscount);
  30293. indices.push(p1.index + positionscount);
  30294. poscounter = -1;
  30295. break;
  30296. }
  30297. poscounter++;
  30298. //indices.push((<IndexedVector2>point).index + positionscount);
  30299. });
  30300. });
  30301. //Add the sides
  30302. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30303. this._holes.forEach(function (hole) {
  30304. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30305. });
  30306. }
  30307. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  30308. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  30309. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  30310. result.setIndices(indices);
  30311. return result;
  30312. };
  30313. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30314. var StartIndex = positions.length / 3;
  30315. var ulength = 0;
  30316. for (var i = 0; i < points.elements.length; i++) {
  30317. var p = points.elements[i];
  30318. var p1;
  30319. if ((i + 1) > points.elements.length - 1) {
  30320. p1 = points.elements[0];
  30321. }
  30322. else {
  30323. p1 = points.elements[i + 1];
  30324. }
  30325. positions.push(p.x, 0, p.y);
  30326. positions.push(p.x, -depth, p.y);
  30327. positions.push(p1.x, 0, p1.y);
  30328. positions.push(p1.x, -depth, p1.y);
  30329. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30330. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30331. var v3 = v2.subtract(v1);
  30332. var v4 = new BABYLON.Vector3(0, 1, 0);
  30333. var vn = BABYLON.Vector3.Cross(v3, v4);
  30334. vn = vn.normalize();
  30335. uvs.push(ulength / bounds.width, 0);
  30336. uvs.push(ulength / bounds.width, 1);
  30337. ulength += v3.length();
  30338. uvs.push((ulength / bounds.width), 0);
  30339. uvs.push((ulength / bounds.width), 1);
  30340. if (!flip) {
  30341. normals.push(-vn.x, -vn.y, -vn.z);
  30342. normals.push(-vn.x, -vn.y, -vn.z);
  30343. normals.push(-vn.x, -vn.y, -vn.z);
  30344. normals.push(-vn.x, -vn.y, -vn.z);
  30345. indices.push(StartIndex);
  30346. indices.push(StartIndex + 1);
  30347. indices.push(StartIndex + 2);
  30348. indices.push(StartIndex + 1);
  30349. indices.push(StartIndex + 3);
  30350. indices.push(StartIndex + 2);
  30351. }
  30352. else {
  30353. normals.push(vn.x, vn.y, vn.z);
  30354. normals.push(vn.x, vn.y, vn.z);
  30355. normals.push(vn.x, vn.y, vn.z);
  30356. normals.push(vn.x, vn.y, vn.z);
  30357. indices.push(StartIndex);
  30358. indices.push(StartIndex + 2);
  30359. indices.push(StartIndex + 1);
  30360. indices.push(StartIndex + 1);
  30361. indices.push(StartIndex + 2);
  30362. indices.push(StartIndex + 3);
  30363. }
  30364. StartIndex += 4;
  30365. }
  30366. ;
  30367. };
  30368. return PolygonMeshBuilder;
  30369. })();
  30370. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30371. })(BABYLON || (BABYLON = {}));
  30372. //# sourceMappingURL=babylon.polygonMesh.js.map
  30373. var BABYLON;
  30374. (function (BABYLON) {
  30375. var SimplificationSettings = (function () {
  30376. function SimplificationSettings(quality, distance, optimizeMesh) {
  30377. this.quality = quality;
  30378. this.distance = distance;
  30379. this.optimizeMesh = optimizeMesh;
  30380. }
  30381. return SimplificationSettings;
  30382. })();
  30383. BABYLON.SimplificationSettings = SimplificationSettings;
  30384. var SimplificationQueue = (function () {
  30385. function SimplificationQueue() {
  30386. this.running = false;
  30387. this._simplificationArray = [];
  30388. }
  30389. SimplificationQueue.prototype.addTask = function (task) {
  30390. this._simplificationArray.push(task);
  30391. };
  30392. SimplificationQueue.prototype.executeNext = function () {
  30393. var task = this._simplificationArray.pop();
  30394. if (task) {
  30395. this.running = true;
  30396. this.runSimplification(task);
  30397. }
  30398. else {
  30399. this.running = false;
  30400. }
  30401. };
  30402. SimplificationQueue.prototype.runSimplification = function (task) {
  30403. var _this = this;
  30404. if (task.parallelProcessing) {
  30405. //parallel simplifier
  30406. task.settings.forEach(function (setting) {
  30407. var simplifier = _this.getSimplifier(task);
  30408. simplifier.simplify(setting, function (newMesh) {
  30409. task.mesh.addLODLevel(setting.distance, newMesh);
  30410. newMesh.isVisible = true;
  30411. //check if it is the last
  30412. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30413. //all done, run the success callback.
  30414. task.successCallback();
  30415. }
  30416. _this.executeNext();
  30417. });
  30418. });
  30419. }
  30420. else {
  30421. //single simplifier.
  30422. var simplifier = this.getSimplifier(task);
  30423. var runDecimation = function (setting, callback) {
  30424. simplifier.simplify(setting, function (newMesh) {
  30425. task.mesh.addLODLevel(setting.distance, newMesh);
  30426. newMesh.isVisible = true;
  30427. //run the next quality level
  30428. callback();
  30429. });
  30430. };
  30431. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30432. runDecimation(task.settings[loop.index], function () {
  30433. loop.executeNext();
  30434. });
  30435. }, function () {
  30436. //execution ended, run the success callback.
  30437. if (task.successCallback) {
  30438. task.successCallback();
  30439. }
  30440. _this.executeNext();
  30441. });
  30442. }
  30443. };
  30444. SimplificationQueue.prototype.getSimplifier = function (task) {
  30445. switch (task.simplificationType) {
  30446. case SimplificationType.QUADRATIC:
  30447. default:
  30448. return new QuadraticErrorSimplification(task.mesh);
  30449. }
  30450. };
  30451. return SimplificationQueue;
  30452. })();
  30453. BABYLON.SimplificationQueue = SimplificationQueue;
  30454. /**
  30455. * The implemented types of simplification.
  30456. * At the moment only Quadratic Error Decimation is implemented.
  30457. */
  30458. (function (SimplificationType) {
  30459. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30460. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30461. var SimplificationType = BABYLON.SimplificationType;
  30462. var DecimationTriangle = (function () {
  30463. function DecimationTriangle(vertices) {
  30464. this.vertices = vertices;
  30465. this.error = new Array(4);
  30466. this.deleted = false;
  30467. this.isDirty = false;
  30468. this.deletePending = false;
  30469. this.borderFactor = 0;
  30470. }
  30471. return DecimationTriangle;
  30472. })();
  30473. BABYLON.DecimationTriangle = DecimationTriangle;
  30474. var DecimationVertex = (function () {
  30475. function DecimationVertex(position, id) {
  30476. this.position = position;
  30477. this.id = id;
  30478. this.isBorder = true;
  30479. this.q = new QuadraticMatrix();
  30480. this.triangleCount = 0;
  30481. this.triangleStart = 0;
  30482. this.originalOffsets = [];
  30483. }
  30484. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30485. this.position.copyFrom(newPosition);
  30486. };
  30487. return DecimationVertex;
  30488. })();
  30489. BABYLON.DecimationVertex = DecimationVertex;
  30490. var QuadraticMatrix = (function () {
  30491. function QuadraticMatrix(data) {
  30492. this.data = new Array(10);
  30493. for (var i = 0; i < 10; ++i) {
  30494. if (data && data[i]) {
  30495. this.data[i] = data[i];
  30496. }
  30497. else {
  30498. this.data[i] = 0;
  30499. }
  30500. }
  30501. }
  30502. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30503. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30504. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30505. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30506. return det;
  30507. };
  30508. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30509. for (var i = 0; i < 10; ++i) {
  30510. this.data[i] += matrix.data[i];
  30511. }
  30512. };
  30513. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30514. for (var i = 0; i < 10; ++i) {
  30515. this.data[i] += data[i];
  30516. }
  30517. };
  30518. QuadraticMatrix.prototype.add = function (matrix) {
  30519. var m = new QuadraticMatrix();
  30520. for (var i = 0; i < 10; ++i) {
  30521. m.data[i] = this.data[i] + matrix.data[i];
  30522. }
  30523. return m;
  30524. };
  30525. QuadraticMatrix.FromData = function (a, b, c, d) {
  30526. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30527. };
  30528. //returning an array to avoid garbage collection
  30529. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30530. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30531. };
  30532. return QuadraticMatrix;
  30533. })();
  30534. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30535. var Reference = (function () {
  30536. function Reference(vertexId, triangleId) {
  30537. this.vertexId = vertexId;
  30538. this.triangleId = triangleId;
  30539. }
  30540. return Reference;
  30541. })();
  30542. BABYLON.Reference = Reference;
  30543. /**
  30544. * An implementation of the Quadratic Error simplification algorithm.
  30545. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30546. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30547. * @author RaananW
  30548. */
  30549. var QuadraticErrorSimplification = (function () {
  30550. function QuadraticErrorSimplification(_mesh) {
  30551. this._mesh = _mesh;
  30552. this.initialized = false;
  30553. this.syncIterations = 5000;
  30554. this.aggressiveness = 7;
  30555. this.decimationIterations = 100;
  30556. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30557. }
  30558. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30559. var _this = this;
  30560. this.initDecimatedMesh();
  30561. //iterating through the submeshes array, one after the other.
  30562. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30563. _this.initWithMesh(loop.index, function () {
  30564. _this.runDecimation(settings, loop.index, function () {
  30565. loop.executeNext();
  30566. });
  30567. }, settings.optimizeMesh);
  30568. }, function () {
  30569. setTimeout(function () {
  30570. successCallback(_this._reconstructedMesh);
  30571. }, 0);
  30572. });
  30573. };
  30574. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30575. var _this = this;
  30576. var gCount = 0;
  30577. triangle.vertices.forEach(function (vertex) {
  30578. var count = 0;
  30579. var vPos = vertex.position;
  30580. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30581. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30582. ++count;
  30583. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30584. ++count;
  30585. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30586. ++count;
  30587. if (count > 1) {
  30588. ++gCount;
  30589. }
  30590. ;
  30591. });
  30592. if (gCount > 1) {
  30593. console.log(triangle, gCount);
  30594. }
  30595. return gCount > 1;
  30596. };
  30597. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30598. var _this = this;
  30599. var targetCount = ~~(this.triangles.length * settings.quality);
  30600. var deletedTriangles = 0;
  30601. var triangleCount = this.triangles.length;
  30602. var iterationFunction = function (iteration, callback) {
  30603. setTimeout(function () {
  30604. if (iteration % 5 === 0) {
  30605. _this.updateMesh(iteration === 0);
  30606. }
  30607. for (var i = 0; i < _this.triangles.length; ++i) {
  30608. _this.triangles[i].isDirty = false;
  30609. }
  30610. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30611. var trianglesIterator = function (i) {
  30612. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30613. var t = _this.triangles[tIdx];
  30614. if (!t)
  30615. return;
  30616. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30617. return;
  30618. }
  30619. for (var j = 0; j < 3; ++j) {
  30620. if (t.error[j] < threshold) {
  30621. var deleted0 = [];
  30622. var deleted1 = [];
  30623. var v0 = t.vertices[j];
  30624. var v1 = t.vertices[(j + 1) % 3];
  30625. if (v0.isBorder !== v1.isBorder)
  30626. continue;
  30627. var p = BABYLON.Vector3.Zero();
  30628. var n = BABYLON.Vector3.Zero();
  30629. var uv = BABYLON.Vector2.Zero();
  30630. var color = new BABYLON.Color4(0, 0, 0, 1);
  30631. _this.calculateError(v0, v1, p, n, uv, color);
  30632. var delTr = [];
  30633. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30634. continue;
  30635. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30636. continue;
  30637. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30638. continue;
  30639. var uniqueArray = [];
  30640. delTr.forEach(function (deletedT) {
  30641. if (uniqueArray.indexOf(deletedT) === -1) {
  30642. deletedT.deletePending = true;
  30643. uniqueArray.push(deletedT);
  30644. }
  30645. });
  30646. if (uniqueArray.length % 2 != 0) {
  30647. continue;
  30648. }
  30649. v0.q = v1.q.add(v0.q);
  30650. v0.updatePosition(p);
  30651. var tStart = _this.references.length;
  30652. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30653. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30654. var tCount = _this.references.length - tStart;
  30655. if (tCount <= v0.triangleCount) {
  30656. if (tCount) {
  30657. for (var c = 0; c < tCount; c++) {
  30658. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30659. }
  30660. }
  30661. }
  30662. else {
  30663. v0.triangleStart = tStart;
  30664. }
  30665. v0.triangleCount = tCount;
  30666. break;
  30667. }
  30668. }
  30669. };
  30670. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30671. }, 0);
  30672. };
  30673. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30674. if (triangleCount - deletedTriangles <= targetCount)
  30675. loop.breakLoop();
  30676. else {
  30677. iterationFunction(loop.index, function () {
  30678. loop.executeNext();
  30679. });
  30680. }
  30681. }, function () {
  30682. setTimeout(function () {
  30683. //reconstruct this part of the mesh
  30684. _this.reconstructMesh(submeshIndex);
  30685. successCallback();
  30686. }, 0);
  30687. });
  30688. };
  30689. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30690. var _this = this;
  30691. this.vertices = [];
  30692. this.triangles = [];
  30693. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30694. var indices = this._mesh.getIndices();
  30695. var submesh = this._mesh.subMeshes[submeshIndex];
  30696. var findInVertices = function (positionToSearch) {
  30697. if (optimizeMesh) {
  30698. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30699. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30700. return _this.vertices[ii];
  30701. }
  30702. }
  30703. }
  30704. return null;
  30705. };
  30706. var vertexReferences = [];
  30707. var vertexInit = function (i) {
  30708. var offset = i + submesh.verticesStart;
  30709. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30710. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30711. vertex.originalOffsets.push(offset);
  30712. if (vertex.id == _this.vertices.length) {
  30713. _this.vertices.push(vertex);
  30714. }
  30715. vertexReferences.push(vertex.id);
  30716. };
  30717. //var totalVertices = mesh.getTotalVertices();
  30718. var totalVertices = submesh.verticesCount;
  30719. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30720. var indicesInit = function (i) {
  30721. var offset = (submesh.indexStart / 3) + i;
  30722. var pos = (offset * 3);
  30723. var i0 = indices[pos + 0];
  30724. var i1 = indices[pos + 1];
  30725. var i2 = indices[pos + 2];
  30726. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30727. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30728. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30729. var triangle = new DecimationTriangle([v0, v1, v2]);
  30730. triangle.originalOffset = pos;
  30731. _this.triangles.push(triangle);
  30732. };
  30733. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30734. _this.init(callback);
  30735. });
  30736. });
  30737. };
  30738. QuadraticErrorSimplification.prototype.init = function (callback) {
  30739. var _this = this;
  30740. var triangleInit1 = function (i) {
  30741. var t = _this.triangles[i];
  30742. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30743. for (var j = 0; j < 3; j++) {
  30744. 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))));
  30745. }
  30746. };
  30747. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30748. var triangleInit2 = function (i) {
  30749. var t = _this.triangles[i];
  30750. for (var j = 0; j < 3; ++j) {
  30751. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30752. }
  30753. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30754. };
  30755. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30756. _this.initialized = true;
  30757. callback();
  30758. });
  30759. });
  30760. };
  30761. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30762. var newTriangles = [];
  30763. var i;
  30764. for (i = 0; i < this.vertices.length; ++i) {
  30765. this.vertices[i].triangleCount = 0;
  30766. }
  30767. var t;
  30768. var j;
  30769. for (i = 0; i < this.triangles.length; ++i) {
  30770. if (!this.triangles[i].deleted) {
  30771. t = this.triangles[i];
  30772. for (j = 0; j < 3; ++j) {
  30773. t.vertices[j].triangleCount = 1;
  30774. }
  30775. newTriangles.push(t);
  30776. }
  30777. }
  30778. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30779. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30780. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30781. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30782. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30783. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30784. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30785. var vertexCount = 0;
  30786. for (i = 0; i < this.vertices.length; ++i) {
  30787. var vertex = this.vertices[i];
  30788. vertex.id = vertexCount;
  30789. if (vertex.triangleCount) {
  30790. vertex.originalOffsets.forEach(function (originalOffset) {
  30791. newPositionData.push(vertex.position.x);
  30792. newPositionData.push(vertex.position.y);
  30793. newPositionData.push(vertex.position.z);
  30794. newNormalData.push(normalData[originalOffset * 3]);
  30795. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30796. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30797. if (uvs && uvs.length) {
  30798. newUVsData.push(uvs[(originalOffset * 2)]);
  30799. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30800. }
  30801. else if (colorsData && colorsData.length) {
  30802. newColorsData.push(colorsData[(originalOffset * 4)]);
  30803. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30804. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30805. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30806. }
  30807. ++vertexCount;
  30808. });
  30809. }
  30810. }
  30811. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30812. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30813. var submeshesArray = this._reconstructedMesh.subMeshes;
  30814. this._reconstructedMesh.subMeshes = [];
  30815. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30816. var originalIndices = this._mesh.getIndices();
  30817. for (i = 0; i < newTriangles.length; ++i) {
  30818. var t = newTriangles[i];
  30819. //now get the new referencing point for each vertex
  30820. [0, 1, 2].forEach(function (idx) {
  30821. var id = originalIndices[t.originalOffset + idx];
  30822. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30823. if (offset < 0)
  30824. offset = 0;
  30825. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30826. });
  30827. }
  30828. //overwriting the old vertex buffers and indices.
  30829. this._reconstructedMesh.setIndices(newIndicesArray);
  30830. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30831. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30832. if (newUVsData.length > 0)
  30833. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30834. if (newColorsData.length > 0)
  30835. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30836. //create submesh
  30837. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30838. if (submeshIndex > 0) {
  30839. this._reconstructedMesh.subMeshes = [];
  30840. submeshesArray.forEach(function (submesh) {
  30841. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30842. });
  30843. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30844. }
  30845. };
  30846. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30847. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30848. this._reconstructedMesh.material = this._mesh.material;
  30849. this._reconstructedMesh.parent = this._mesh.parent;
  30850. this._reconstructedMesh.isVisible = false;
  30851. };
  30852. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30853. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30854. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30855. if (t.deleted)
  30856. continue;
  30857. var s = this.references[vertex1.triangleStart + i].vertexId;
  30858. var v1 = t.vertices[(s + 1) % 3];
  30859. var v2 = t.vertices[(s + 2) % 3];
  30860. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30861. deletedArray[i] = true;
  30862. delTr.push(t);
  30863. continue;
  30864. }
  30865. var d1 = v1.position.subtract(point);
  30866. d1 = d1.normalize();
  30867. var d2 = v2.position.subtract(point);
  30868. d2 = d2.normalize();
  30869. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30870. return true;
  30871. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30872. deletedArray[i] = false;
  30873. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30874. return true;
  30875. }
  30876. return false;
  30877. };
  30878. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30879. var newDeleted = deletedTriangles;
  30880. for (var i = 0; i < vertex.triangleCount; ++i) {
  30881. var ref = this.references[vertex.triangleStart + i];
  30882. var t = this.triangles[ref.triangleId];
  30883. if (t.deleted)
  30884. continue;
  30885. if (deletedArray[i] && t.deletePending) {
  30886. t.deleted = true;
  30887. newDeleted++;
  30888. continue;
  30889. }
  30890. t.vertices[ref.vertexId] = origVertex;
  30891. t.isDirty = true;
  30892. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30893. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30894. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30895. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30896. this.references.push(ref);
  30897. }
  30898. return newDeleted;
  30899. };
  30900. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30901. for (var i = 0; i < this.vertices.length; ++i) {
  30902. var vCount = [];
  30903. var vId = [];
  30904. var v = this.vertices[i];
  30905. var j;
  30906. for (j = 0; j < v.triangleCount; ++j) {
  30907. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30908. for (var ii = 0; ii < 3; ii++) {
  30909. var ofs = 0;
  30910. var vv = triangle.vertices[ii];
  30911. while (ofs < vCount.length) {
  30912. if (vId[ofs] === vv.id)
  30913. break;
  30914. ++ofs;
  30915. }
  30916. if (ofs === vCount.length) {
  30917. vCount.push(1);
  30918. vId.push(vv.id);
  30919. }
  30920. else {
  30921. vCount[ofs]++;
  30922. }
  30923. }
  30924. }
  30925. for (j = 0; j < vCount.length; ++j) {
  30926. if (vCount[j] === 1) {
  30927. this.vertices[vId[j]].isBorder = true;
  30928. }
  30929. else {
  30930. this.vertices[vId[j]].isBorder = false;
  30931. }
  30932. }
  30933. }
  30934. };
  30935. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30936. if (identifyBorders === void 0) { identifyBorders = false; }
  30937. var i;
  30938. if (!identifyBorders) {
  30939. var newTrianglesVector = [];
  30940. for (i = 0; i < this.triangles.length; ++i) {
  30941. if (!this.triangles[i].deleted) {
  30942. newTrianglesVector.push(this.triangles[i]);
  30943. }
  30944. }
  30945. this.triangles = newTrianglesVector;
  30946. }
  30947. for (i = 0; i < this.vertices.length; ++i) {
  30948. this.vertices[i].triangleCount = 0;
  30949. this.vertices[i].triangleStart = 0;
  30950. }
  30951. var t;
  30952. var j;
  30953. var v;
  30954. for (i = 0; i < this.triangles.length; ++i) {
  30955. t = this.triangles[i];
  30956. for (j = 0; j < 3; ++j) {
  30957. v = t.vertices[j];
  30958. v.triangleCount++;
  30959. }
  30960. }
  30961. var tStart = 0;
  30962. for (i = 0; i < this.vertices.length; ++i) {
  30963. this.vertices[i].triangleStart = tStart;
  30964. tStart += this.vertices[i].triangleCount;
  30965. this.vertices[i].triangleCount = 0;
  30966. }
  30967. var newReferences = new Array(this.triangles.length * 3);
  30968. for (i = 0; i < this.triangles.length; ++i) {
  30969. t = this.triangles[i];
  30970. for (j = 0; j < 3; ++j) {
  30971. v = t.vertices[j];
  30972. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30973. v.triangleCount++;
  30974. }
  30975. }
  30976. this.references = newReferences;
  30977. if (identifyBorders) {
  30978. this.identifyBorder();
  30979. }
  30980. };
  30981. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30982. var x = point.x;
  30983. var y = point.y;
  30984. var z = point.z;
  30985. 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
  30986. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30987. };
  30988. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30989. var q = vertex1.q.add(vertex2.q);
  30990. var border = vertex1.isBorder && vertex2.isBorder;
  30991. var error = 0;
  30992. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30993. if (qDet !== 0 && !border) {
  30994. if (!pointResult) {
  30995. pointResult = BABYLON.Vector3.Zero();
  30996. }
  30997. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30998. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30999. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31000. error = this.vertexError(q, pointResult);
  31001. }
  31002. else {
  31003. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31004. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31005. var error1 = this.vertexError(q, vertex1.position);
  31006. var error2 = this.vertexError(q, vertex2.position);
  31007. var error3 = this.vertexError(q, p3);
  31008. error = Math.min(error1, error2, error3);
  31009. if (error === error1) {
  31010. if (pointResult) {
  31011. pointResult.copyFrom(vertex1.position);
  31012. }
  31013. }
  31014. else if (error === error2) {
  31015. if (pointResult) {
  31016. pointResult.copyFrom(vertex2.position);
  31017. }
  31018. }
  31019. else {
  31020. if (pointResult) {
  31021. pointResult.copyFrom(p3);
  31022. }
  31023. }
  31024. }
  31025. return error;
  31026. };
  31027. return QuadraticErrorSimplification;
  31028. })();
  31029. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31030. })(BABYLON || (BABYLON = {}));
  31031. //# sourceMappingURL=babylon.meshSimplification.js.map
  31032. var BABYLON;
  31033. (function (BABYLON) {
  31034. var Analyser = (function () {
  31035. function Analyser(scene) {
  31036. this.SMOOTHING = 0.75;
  31037. this.FFT_SIZE = 512;
  31038. this.BARGRAPHAMPLITUDE = 256;
  31039. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  31040. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  31041. this._scene = scene;
  31042. this._audioEngine = BABYLON.Engine.audioEngine;
  31043. if (this._audioEngine.canUseWebAudio) {
  31044. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  31045. this._webAudioAnalyser.minDecibels = -140;
  31046. this._webAudioAnalyser.maxDecibels = 0;
  31047. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31048. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31049. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  31050. }
  31051. }
  31052. Analyser.prototype.getFrequencyBinCount = function () {
  31053. if (this._audioEngine.canUseWebAudio) {
  31054. return this._webAudioAnalyser.frequencyBinCount;
  31055. }
  31056. else {
  31057. return 0;
  31058. }
  31059. };
  31060. Analyser.prototype.getByteFrequencyData = function () {
  31061. if (this._audioEngine.canUseWebAudio) {
  31062. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31063. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31064. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  31065. }
  31066. return this._byteFreqs;
  31067. };
  31068. Analyser.prototype.getByteTimeDomainData = function () {
  31069. if (this._audioEngine.canUseWebAudio) {
  31070. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31071. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31072. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  31073. }
  31074. return this._byteTime;
  31075. };
  31076. Analyser.prototype.getFloatFrequencyData = function () {
  31077. if (this._audioEngine.canUseWebAudio) {
  31078. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31079. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31080. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  31081. }
  31082. return this._floatFreqs;
  31083. };
  31084. Analyser.prototype.drawDebugCanvas = function () {
  31085. var _this = this;
  31086. if (this._audioEngine.canUseWebAudio) {
  31087. if (!this._debugCanvas) {
  31088. this._debugCanvas = document.createElement("canvas");
  31089. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  31090. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  31091. this._debugCanvas.style.position = "absolute";
  31092. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  31093. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  31094. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  31095. document.body.appendChild(this._debugCanvas);
  31096. this._registerFunc = function () {
  31097. _this.drawDebugCanvas();
  31098. };
  31099. this._scene.registerBeforeRender(this._registerFunc);
  31100. }
  31101. if (this._registerFunc) {
  31102. var workingArray = this.getByteFrequencyData();
  31103. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  31104. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  31105. // Draw the frequency domain chart.
  31106. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  31107. var value = workingArray[i];
  31108. var percent = value / this.BARGRAPHAMPLITUDE;
  31109. var height = this.DEBUGCANVASSIZE.height * percent;
  31110. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  31111. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  31112. var hue = i / this.getFrequencyBinCount() * 360;
  31113. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  31114. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  31115. }
  31116. }
  31117. }
  31118. };
  31119. Analyser.prototype.stopDebugCanvas = function () {
  31120. if (this._debugCanvas) {
  31121. this._scene.unregisterBeforeRender(this._registerFunc);
  31122. this._registerFunc = null;
  31123. document.body.removeChild(this._debugCanvas);
  31124. this._debugCanvas = null;
  31125. this._debugCanvasContext = null;
  31126. }
  31127. };
  31128. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  31129. if (this._audioEngine.canUseWebAudio) {
  31130. inputAudioNode.connect(this._webAudioAnalyser);
  31131. this._webAudioAnalyser.connect(outputAudioNode);
  31132. }
  31133. };
  31134. Analyser.prototype.dispose = function () {
  31135. if (this._audioEngine.canUseWebAudio) {
  31136. this._webAudioAnalyser.disconnect();
  31137. }
  31138. };
  31139. return Analyser;
  31140. })();
  31141. BABYLON.Analyser = Analyser;
  31142. })(BABYLON || (BABYLON = {}));
  31143. //# sourceMappingURL=babylon.analyser.js.map
  31144. var BABYLON;
  31145. (function (BABYLON) {
  31146. var DepthRenderer = (function () {
  31147. function DepthRenderer(scene, type) {
  31148. var _this = this;
  31149. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  31150. this._viewMatrix = BABYLON.Matrix.Zero();
  31151. this._projectionMatrix = BABYLON.Matrix.Zero();
  31152. this._transformMatrix = BABYLON.Matrix.Zero();
  31153. this._worldViewProjection = BABYLON.Matrix.Zero();
  31154. this._scene = scene;
  31155. var engine = scene.getEngine();
  31156. // Render target
  31157. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  31158. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31159. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31160. this._depthMap.refreshRate = 1;
  31161. this._depthMap.renderParticles = false;
  31162. this._depthMap.renderList = null;
  31163. // set default depth value to 1.0 (far away)
  31164. this._depthMap.onClear = function (engine) {
  31165. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  31166. };
  31167. // Custom render function
  31168. var renderSubMesh = function (subMesh) {
  31169. var mesh = subMesh.getRenderingMesh();
  31170. var scene = _this._scene;
  31171. var engine = scene.getEngine();
  31172. // Culling
  31173. engine.setState(subMesh.getMaterial().backFaceCulling);
  31174. // Managing instances
  31175. var batch = mesh._getInstancesRenderList(subMesh._id);
  31176. if (batch.mustReturn) {
  31177. return;
  31178. }
  31179. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31180. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31181. engine.enableEffect(_this._effect);
  31182. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  31183. var material = subMesh.getMaterial();
  31184. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31185. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  31186. // Alpha test
  31187. if (material && material.needAlphaTesting()) {
  31188. var alphaTexture = material.getAlphaTestTexture();
  31189. _this._effect.setTexture("diffuseSampler", alphaTexture);
  31190. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31191. }
  31192. // Bones
  31193. if (mesh.useBones) {
  31194. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31195. }
  31196. // Draw
  31197. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  31198. }
  31199. };
  31200. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  31201. var index;
  31202. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31203. renderSubMesh(opaqueSubMeshes.data[index]);
  31204. }
  31205. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31206. renderSubMesh(alphaTestSubMeshes.data[index]);
  31207. }
  31208. };
  31209. }
  31210. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  31211. var defines = [];
  31212. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31213. var mesh = subMesh.getMesh();
  31214. var scene = mesh.getScene();
  31215. var material = subMesh.getMaterial();
  31216. // Alpha test
  31217. if (material && material.needAlphaTesting()) {
  31218. defines.push("#define ALPHATEST");
  31219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31220. attribs.push(BABYLON.VertexBuffer.UVKind);
  31221. defines.push("#define UV1");
  31222. }
  31223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31224. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31225. defines.push("#define UV2");
  31226. }
  31227. }
  31228. // Bones
  31229. if (mesh.useBones) {
  31230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31232. defines.push("#define BONES");
  31233. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31234. }
  31235. // Instances
  31236. if (useInstances) {
  31237. defines.push("#define INSTANCES");
  31238. attribs.push("world0");
  31239. attribs.push("world1");
  31240. attribs.push("world2");
  31241. attribs.push("world3");
  31242. }
  31243. // Get correct effect
  31244. var join = defines.join("\n");
  31245. if (this._cachedDefines !== join) {
  31246. this._cachedDefines = join;
  31247. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  31248. }
  31249. return this._effect.isReady();
  31250. };
  31251. DepthRenderer.prototype.getDepthMap = function () {
  31252. return this._depthMap;
  31253. };
  31254. // Methods
  31255. DepthRenderer.prototype.dispose = function () {
  31256. this._depthMap.dispose();
  31257. };
  31258. return DepthRenderer;
  31259. })();
  31260. BABYLON.DepthRenderer = DepthRenderer;
  31261. })(BABYLON || (BABYLON = {}));
  31262. //# sourceMappingURL=babylon.depthRenderer.js.map
  31263. var __extends = this.__extends || function (d, b) {
  31264. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31265. function __() { this.constructor = d; }
  31266. __.prototype = b.prototype;
  31267. d.prototype = new __();
  31268. };
  31269. var BABYLON;
  31270. (function (BABYLON) {
  31271. var SSAORenderingPipeline = (function (_super) {
  31272. __extends(SSAORenderingPipeline, _super);
  31273. /**
  31274. * @constructor
  31275. * @param {string} name - The rendering pipeline name
  31276. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31277. * @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 }
  31278. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31279. */
  31280. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  31281. var _this = this;
  31282. _super.call(this, scene.getEngine(), name);
  31283. // Members
  31284. /**
  31285. * The PassPostProcess id in the pipeline that contains the original scene color
  31286. * @type {string}
  31287. */
  31288. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  31289. /**
  31290. * The SSAO PostProcess id in the pipeline
  31291. * @type {string}
  31292. */
  31293. this.SSAORenderEffect = "SSAORenderEffect";
  31294. /**
  31295. * The horizontal blur PostProcess id in the pipeline
  31296. * @type {string}
  31297. */
  31298. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  31299. /**
  31300. * The vertical blur PostProcess id in the pipeline
  31301. * @type {string}
  31302. */
  31303. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  31304. /**
  31305. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  31306. * @type {string}
  31307. */
  31308. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31309. /**
  31310. * The output strength of the SSAO post-process. Default value is 1.0.
  31311. * @type {number}
  31312. */
  31313. this.totalStrength = 1.0;
  31314. /**
  31315. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31316. * @type {number}
  31317. */
  31318. this.radius = 0.0002;
  31319. /**
  31320. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31321. * Must not be equal to fallOff and superior to fallOff.
  31322. * Default value is 0.0075
  31323. * @type {number}
  31324. */
  31325. this.area = 0.0075;
  31326. /**
  31327. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31328. * Must not be equal to area and inferior to area.
  31329. * Default value is 0.0002
  31330. * @type {number}
  31331. */
  31332. this.fallOff = 0.0002;
  31333. this._firstUpdate = true;
  31334. this._scene = scene;
  31335. // Set up assets
  31336. this._createRandomTexture();
  31337. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31338. var ssaoRatio = ratio.ssaoRatio || ratio;
  31339. var combineRatio = ratio.combineRatio || ratio;
  31340. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31341. this._createSSAOPostProcess(ssaoRatio);
  31342. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31343. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31344. this._createSSAOCombinePostProcess(combineRatio);
  31345. // Set up pipeline
  31346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  31347. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  31348. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  31349. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  31350. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  31351. // Finish
  31352. scene.postProcessRenderPipelineManager.addPipeline(this);
  31353. if (cameras)
  31354. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31355. }
  31356. // Public Methods
  31357. /**
  31358. * Returns the horizontal blur PostProcess
  31359. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31360. */
  31361. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31362. return this._blurHPostProcess;
  31363. };
  31364. /**
  31365. * Returns the vertical blur PostProcess
  31366. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31367. */
  31368. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31369. return this._blurVPostProcess;
  31370. };
  31371. /**
  31372. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31373. */
  31374. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31375. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31376. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31377. this._originalColorPostProcess = undefined;
  31378. this._ssaoPostProcess = undefined;
  31379. this._blurHPostProcess = undefined;
  31380. this._blurVPostProcess = undefined;
  31381. this._ssaoCombinePostProcess = undefined;
  31382. this._randomTexture.dispose();
  31383. if (disableDepthRender)
  31384. this._scene.disableDepthRenderer();
  31385. };
  31386. // Private Methods
  31387. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31388. var _this = this;
  31389. var sampleSphere = [
  31390. 0.5381, 0.1856, -0.4319,
  31391. 0.1379, 0.2486, 0.4430,
  31392. 0.3371, 0.5679, -0.0057,
  31393. -0.6999, -0.0451, -0.0019,
  31394. 0.0689, -0.1598, -0.8547,
  31395. 0.0560, 0.0069, -0.1843,
  31396. -0.0146, 0.1402, 0.0762,
  31397. 0.0100, -0.1924, -0.0344,
  31398. -0.3577, -0.5301, -0.4358,
  31399. -0.3169, 0.1063, 0.0158,
  31400. 0.0103, -0.5869, 0.0046,
  31401. -0.0897, -0.4940, 0.3287,
  31402. 0.7119, -0.0154, -0.0918,
  31403. -0.0533, 0.0596, -0.5411,
  31404. 0.0352, -0.0631, 0.5460,
  31405. -0.4776, 0.2847, -0.0271
  31406. ];
  31407. var samplesFactor = 1.0 / 16.0;
  31408. 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);
  31409. this._ssaoPostProcess.onApply = function (effect) {
  31410. if (_this._firstUpdate) {
  31411. effect.setArray3("sampleSphere", sampleSphere);
  31412. effect.setFloat("samplesFactor", samplesFactor);
  31413. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31414. _this._firstUpdate = false;
  31415. }
  31416. effect.setFloat("totalStrength", _this.totalStrength);
  31417. effect.setFloat("radius", _this.radius);
  31418. effect.setFloat("area", _this.area);
  31419. effect.setFloat("fallOff", _this.fallOff);
  31420. effect.setTexture("textureSampler", _this._depthTexture);
  31421. effect.setTexture("randomSampler", _this._randomTexture);
  31422. };
  31423. };
  31424. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31425. var _this = this;
  31426. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31427. this._ssaoCombinePostProcess.onApply = function (effect) {
  31428. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31429. };
  31430. };
  31431. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31432. var size = 512;
  31433. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31434. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31435. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31436. var context = this._randomTexture.getContext();
  31437. var rand = function (min, max) {
  31438. return Math.random() * (max - min) + min;
  31439. };
  31440. for (var x = 0; x < size; x++) {
  31441. for (var y = 0; y < size; y++) {
  31442. var randVector = BABYLON.Vector3.Zero();
  31443. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31444. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31445. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31446. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31447. context.fillRect(x, y, 1, 1);
  31448. }
  31449. }
  31450. this._randomTexture.update(false);
  31451. };
  31452. return SSAORenderingPipeline;
  31453. })(BABYLON.PostProcessRenderPipeline);
  31454. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31455. })(BABYLON || (BABYLON = {}));
  31456. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31457. var __extends = this.__extends || function (d, b) {
  31458. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31459. function __() { this.constructor = d; }
  31460. __.prototype = b.prototype;
  31461. d.prototype = new __();
  31462. };
  31463. var BABYLON;
  31464. (function (BABYLON) {
  31465. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31466. var VolumetricLightScatteringPostProcess = (function (_super) {
  31467. __extends(VolumetricLightScatteringPostProcess, _super);
  31468. /**
  31469. * @constructor
  31470. * @param {string} name - The post-process name
  31471. * @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)
  31472. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31473. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31474. * @param {number} samples - The post-process quality, default 100
  31475. * @param {number} samplingMode - The post-process filtering mode
  31476. * @param {BABYLON.Engine} engine - The babylon engine
  31477. * @param {boolean} reusable - If the post-process is reusable
  31478. */
  31479. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31480. var _this = this;
  31481. if (samples === void 0) { samples = 100; }
  31482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31483. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31484. this._screenCoordinates = BABYLON.Vector2.Zero();
  31485. /**
  31486. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31487. * @type {boolean}
  31488. */
  31489. this.useCustomMeshPosition = false;
  31490. /**
  31491. * If the post-process should inverse the light scattering direction
  31492. * @type {boolean}
  31493. */
  31494. this.invert = true;
  31495. /**
  31496. * Array containing the excluded meshes not rendered in the internal pass
  31497. */
  31498. this.excludedMeshes = new Array();
  31499. this.exposure = 0.3;
  31500. this.decay = 0.96815;
  31501. this.weight = 0.58767;
  31502. this.density = 0.926;
  31503. var scene = camera.getScene();
  31504. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31505. // Configure mesh
  31506. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31507. // Configure
  31508. this._createPass(scene, ratio.passRatio || ratio);
  31509. this.onApply = function (effect) {
  31510. _this._updateMeshScreenCoordinates(scene);
  31511. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31512. effect.setFloat("exposure", _this.exposure);
  31513. effect.setFloat("decay", _this.decay);
  31514. effect.setFloat("weight", _this.weight);
  31515. effect.setFloat("density", _this.density);
  31516. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31517. };
  31518. }
  31519. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31520. var mesh = subMesh.getMesh();
  31521. var defines = [];
  31522. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31523. var material = subMesh.getMaterial();
  31524. var needUV = false;
  31525. // Render this.mesh as default
  31526. if (mesh === this.mesh) {
  31527. defines.push("#define BASIC_RENDER");
  31528. defines.push("#define NEED_UV");
  31529. needUV = true;
  31530. }
  31531. // Alpha test
  31532. if (material) {
  31533. if (material.needAlphaTesting() || mesh === this.mesh)
  31534. defines.push("#define ALPHATEST");
  31535. if (material.opacityTexture !== undefined) {
  31536. defines.push("#define OPACITY");
  31537. if (material.opacityTexture.getAlphaFromRGB)
  31538. defines.push("#define OPACITYRGB");
  31539. if (!needUV)
  31540. defines.push("#define NEED_UV");
  31541. }
  31542. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31543. attribs.push(BABYLON.VertexBuffer.UVKind);
  31544. defines.push("#define UV1");
  31545. }
  31546. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31547. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31548. defines.push("#define UV2");
  31549. }
  31550. }
  31551. // Bones
  31552. if (mesh.useBones) {
  31553. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31554. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31555. defines.push("#define BONES");
  31556. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31557. }
  31558. // Instances
  31559. if (useInstances) {
  31560. defines.push("#define INSTANCES");
  31561. attribs.push("world0");
  31562. attribs.push("world1");
  31563. attribs.push("world2");
  31564. attribs.push("world3");
  31565. }
  31566. // Get correct effect
  31567. var join = defines.join("\n");
  31568. if (this._cachedDefines !== join) {
  31569. this._cachedDefines = join;
  31570. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31571. }
  31572. return this._volumetricLightScatteringPass.isReady();
  31573. };
  31574. /**
  31575. * Sets the new light position for light scattering effect
  31576. * @param {BABYLON.Vector3} The new custom light position
  31577. */
  31578. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31579. this._customMeshPosition = position;
  31580. };
  31581. /**
  31582. * Returns the light position for light scattering effect
  31583. * @return {BABYLON.Vector3} The custom light position
  31584. */
  31585. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31586. return this._customMeshPosition;
  31587. };
  31588. /**
  31589. * Disposes the internal assets and detaches the post-process from the camera
  31590. */
  31591. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31592. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31593. if (rttIndex !== -1) {
  31594. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31595. }
  31596. this._volumetricLightScatteringRTT.dispose();
  31597. _super.prototype.dispose.call(this, camera);
  31598. };
  31599. /**
  31600. * Returns the render target texture used by the post-process
  31601. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31602. */
  31603. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31604. return this._volumetricLightScatteringRTT;
  31605. };
  31606. // Private methods
  31607. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31608. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31609. return true;
  31610. }
  31611. return false;
  31612. };
  31613. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31614. var _this = this;
  31615. var engine = scene.getEngine();
  31616. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31617. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31618. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31619. this._volumetricLightScatteringRTT.renderList = null;
  31620. this._volumetricLightScatteringRTT.renderParticles = false;
  31621. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31622. // Custom render function for submeshes
  31623. var renderSubMesh = function (subMesh) {
  31624. var mesh = subMesh.getRenderingMesh();
  31625. if (_this._meshExcluded(mesh)) {
  31626. return;
  31627. }
  31628. var scene = mesh.getScene();
  31629. var engine = scene.getEngine();
  31630. // Culling
  31631. engine.setState(subMesh.getMaterial().backFaceCulling);
  31632. // Managing instances
  31633. var batch = mesh._getInstancesRenderList(subMesh._id);
  31634. if (batch.mustReturn) {
  31635. return;
  31636. }
  31637. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31638. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31639. engine.enableEffect(_this._volumetricLightScatteringPass);
  31640. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31641. var material = subMesh.getMaterial();
  31642. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31643. // Alpha test
  31644. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31645. var alphaTexture = material.getAlphaTestTexture();
  31646. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31647. if (alphaTexture) {
  31648. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31649. }
  31650. if (material.opacityTexture !== undefined) {
  31651. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31652. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31653. }
  31654. }
  31655. // Bones
  31656. if (mesh.useBones) {
  31657. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31658. }
  31659. // Draw
  31660. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31661. }
  31662. };
  31663. // Render target texture callbacks
  31664. var savedSceneClearColor;
  31665. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31666. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31667. savedSceneClearColor = scene.clearColor;
  31668. scene.clearColor = sceneClearColor;
  31669. };
  31670. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31671. scene.clearColor = savedSceneClearColor;
  31672. };
  31673. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31674. var engine = scene.getEngine();
  31675. var index;
  31676. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31677. renderSubMesh(opaqueSubMeshes.data[index]);
  31678. }
  31679. engine.setAlphaTesting(true);
  31680. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31681. renderSubMesh(alphaTestSubMeshes.data[index]);
  31682. }
  31683. engine.setAlphaTesting(false);
  31684. if (transparentSubMeshes.length) {
  31685. // Sort sub meshes
  31686. for (index = 0; index < transparentSubMeshes.length; index++) {
  31687. var submesh = transparentSubMeshes.data[index];
  31688. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31689. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31690. }
  31691. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31692. sortedArray.sort(function (a, b) {
  31693. // Alpha index first
  31694. if (a._alphaIndex > b._alphaIndex) {
  31695. return 1;
  31696. }
  31697. if (a._alphaIndex < b._alphaIndex) {
  31698. return -1;
  31699. }
  31700. // Then distance to camera
  31701. if (a._distanceToCamera < b._distanceToCamera) {
  31702. return 1;
  31703. }
  31704. if (a._distanceToCamera > b._distanceToCamera) {
  31705. return -1;
  31706. }
  31707. return 0;
  31708. });
  31709. // Render sub meshes
  31710. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31711. for (index = 0; index < sortedArray.length; index++) {
  31712. renderSubMesh(sortedArray[index]);
  31713. }
  31714. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31715. }
  31716. };
  31717. };
  31718. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31719. var transform = scene.getTransformMatrix();
  31720. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31721. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31722. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31723. if (this.invert)
  31724. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31725. };
  31726. // Static methods
  31727. /**
  31728. * Creates a default mesh for the Volumeric Light Scattering post-process
  31729. * @param {string} The mesh name
  31730. * @param {BABYLON.Scene} The scene where to create the mesh
  31731. * @return {BABYLON.Mesh} the default mesh
  31732. */
  31733. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31734. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31735. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31736. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31737. return mesh;
  31738. };
  31739. return VolumetricLightScatteringPostProcess;
  31740. })(BABYLON.PostProcess);
  31741. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31742. })(BABYLON || (BABYLON = {}));
  31743. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31744. var __extends = this.__extends || function (d, b) {
  31745. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31746. function __() { this.constructor = d; }
  31747. __.prototype = b.prototype;
  31748. d.prototype = new __();
  31749. };
  31750. var BABYLON;
  31751. (function (BABYLON) {
  31752. var LensRenderingPipeline = (function (_super) {
  31753. __extends(LensRenderingPipeline, _super);
  31754. /**
  31755. * @constructor
  31756. *
  31757. * Effect parameters are as follow:
  31758. * {
  31759. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31760. * edge_blur: number; // from 0 to x (1 for realism)
  31761. * distortion: number; // from 0 to x (1 for realism)
  31762. * grain_amount: number; // from 0 to 1
  31763. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31764. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31765. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31766. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31767. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31768. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31769. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31770. * }
  31771. * Note: if an effect parameter is unset, effect is disabled
  31772. *
  31773. * @param {string} name - The rendering pipeline name
  31774. * @param {object} parameters - An object containing all parameters (see above)
  31775. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31776. * @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)
  31777. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31778. */
  31779. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31780. var _this = this;
  31781. if (ratio === void 0) { ratio = 1.0; }
  31782. _super.call(this, scene.getEngine(), name);
  31783. // Lens effects can be of the following:
  31784. // - chromatic aberration (slight shift of RGB colors)
  31785. // - blur on the edge of the lens
  31786. // - lens distortion
  31787. // - depth-of-field blur & highlights enhancing
  31788. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31789. // - grain effect (noise or custom texture)
  31790. // Two additional texture samplers are needed:
  31791. // - depth map (for depth-of-field)
  31792. // - grain texture
  31793. /**
  31794. * The chromatic aberration PostProcess id in the pipeline
  31795. * @type {string}
  31796. */
  31797. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31798. /**
  31799. * The highlights enhancing PostProcess id in the pipeline
  31800. * @type {string}
  31801. */
  31802. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31803. /**
  31804. * The depth-of-field PostProcess id in the pipeline
  31805. * @type {string}
  31806. */
  31807. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31808. this._scene = scene;
  31809. // Fetch texture samplers
  31810. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31811. if (parameters.grain_texture) {
  31812. this._grainTexture = parameters.grain_texture;
  31813. }
  31814. else {
  31815. this._createGrainTexture();
  31816. }
  31817. // save parameters
  31818. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31819. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31820. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31821. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31822. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31823. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31824. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31825. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31826. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31827. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31828. // Create effects
  31829. this._createChromaticAberrationPostProcess(ratio);
  31830. this._createHighlightsPostProcess(ratio);
  31831. this._createDepthOfFieldPostProcess(ratio);
  31832. // Set up pipeline
  31833. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31836. if (this._highlightsGain == -1) {
  31837. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31838. }
  31839. // Finish
  31840. scene.postProcessRenderPipelineManager.addPipeline(this);
  31841. if (cameras) {
  31842. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31843. }
  31844. }
  31845. // public methods (self explanatory)
  31846. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31847. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31848. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31849. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31850. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31851. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31852. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31853. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31854. LensRenderingPipeline.prototype.setFocusDepth = function (amount) { this._dofDepth = amount; };
  31855. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDepth = -1; };
  31856. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31857. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31858. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31859. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31860. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31861. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31862. this._highlightsGain = amount;
  31863. };
  31864. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31865. if (this._highlightsGain == -1) {
  31866. this._highlightsGain = 1.0;
  31867. }
  31868. this._highlightsThreshold = amount;
  31869. };
  31870. LensRenderingPipeline.prototype.disableHighlights = function () {
  31871. this._highlightsGain = -1;
  31872. };
  31873. /**
  31874. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31875. */
  31876. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31877. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31878. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31879. this._chromaticAberrationPostProcess = undefined;
  31880. this._highlightsPostProcess = undefined;
  31881. this._depthOfFieldPostProcess = undefined;
  31882. this._grainTexture.dispose();
  31883. if (disableDepthRender)
  31884. this._scene.disableDepthRenderer();
  31885. };
  31886. // colors shifting and distortion
  31887. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31888. var _this = this;
  31889. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31890. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31891. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31892. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31893. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31894. };
  31895. };
  31896. // highlights enhancing
  31897. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31898. var _this = this;
  31899. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31900. this._highlightsPostProcess.onApply = function (effect) {
  31901. effect.setFloat('gain', _this._highlightsGain);
  31902. effect.setFloat('threshold', _this._highlightsThreshold);
  31903. effect.setBool('pentagon', _this._dofPentagon);
  31904. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31905. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31906. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31907. };
  31908. };
  31909. // colors shifting and distortion
  31910. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31911. var _this = this;
  31912. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31913. "focus_depth", "aperture", "pentagon", "maxZ", "edge_blur", "chromatic_aberration",
  31914. "distortion", "blur_noise", "grain_amount", "screen_width", "screen_height", "highlights"
  31915. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31916. this._depthOfFieldPostProcess.onApply = function (effect) {
  31917. effect.setBool('blur_noise', _this._blurNoise);
  31918. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31919. effect.setFloat('grain_amount', _this._grainAmount);
  31920. effect.setTexture("depthSampler", _this._depthTexture);
  31921. effect.setTexture("grainSampler", _this._grainTexture);
  31922. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31923. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31924. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31925. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31926. effect.setFloat('distortion', _this._distortion);
  31927. effect.setFloat('focus_depth', _this._dofDepth);
  31928. effect.setFloat('aperture', _this._dofAperture);
  31929. effect.setFloat('edge_blur', _this._edgeBlur);
  31930. effect.setBool('highlights', (_this._highlightsGain != -1));
  31931. };
  31932. };
  31933. // creates a black and white random noise texture, 512x512
  31934. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31935. var size = 512;
  31936. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31937. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31938. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31939. var context = this._grainTexture.getContext();
  31940. var rand = function (min, max) {
  31941. return Math.random() * (max - min) + min;
  31942. };
  31943. var value;
  31944. for (var x = 0; x < size; x++) {
  31945. for (var y = 0; y < size; y++) {
  31946. value = Math.floor(rand(0.42, 0.58) * 255);
  31947. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31948. context.fillRect(x, y, 1, 1);
  31949. }
  31950. }
  31951. this._grainTexture.update(false);
  31952. };
  31953. return LensRenderingPipeline;
  31954. })(BABYLON.PostProcessRenderPipeline);
  31955. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31956. })(BABYLON || (BABYLON = {}));
  31957. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31958. //
  31959. // This post-process allows the modification of rendered colors by using
  31960. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31961. //
  31962. // The object needs to be provided an url to a texture containing the color
  31963. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31964. // Use an image editing software to tweak the LUT to match your needs.
  31965. //
  31966. // For an example of a color LUT, see here:
  31967. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31968. // For explanations on color grading, see here:
  31969. // http://udn.epicgames.com/Three/ColorGrading.html
  31970. //
  31971. var __extends = this.__extends || function (d, b) {
  31972. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31973. function __() { this.constructor = d; }
  31974. __.prototype = b.prototype;
  31975. d.prototype = new __();
  31976. };
  31977. var BABYLON;
  31978. (function (BABYLON) {
  31979. var ColorCorrectionPostProcess = (function (_super) {
  31980. __extends(ColorCorrectionPostProcess, _super);
  31981. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31982. var _this = this;
  31983. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31984. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31985. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31986. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31987. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31988. this.onApply = function (effect) {
  31989. effect.setTexture("colorTable", _this._colorTableTexture);
  31990. };
  31991. }
  31992. return ColorCorrectionPostProcess;
  31993. })(BABYLON.PostProcess);
  31994. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31995. })(BABYLON || (BABYLON = {}));
  31996. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31997. var __extends = this.__extends || function (d, b) {
  31998. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31999. function __() { this.constructor = d; }
  32000. __.prototype = b.prototype;
  32001. d.prototype = new __();
  32002. };
  32003. var BABYLON;
  32004. (function (BABYLON) {
  32005. var StereoscopicFreeCamera = (function (_super) {
  32006. __extends(StereoscopicFreeCamera, _super);
  32007. function StereoscopicFreeCamera(name, position, eyeSpace, isVertical, scene) {
  32008. _super.call(this, name, position, scene);
  32009. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  32010. }
  32011. return StereoscopicFreeCamera;
  32012. })(BABYLON.FreeCamera);
  32013. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  32014. var StereoscopicArcRotateCamera = (function (_super) {
  32015. __extends(StereoscopicArcRotateCamera, _super);
  32016. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, isVertical, scene) {
  32017. _super.call(this, name, alpha, beta, radius, target, scene);
  32018. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  32019. }
  32020. return StereoscopicArcRotateCamera;
  32021. })(BABYLON.ArcRotateCamera);
  32022. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  32023. var StereoscopicGamepadCamera = (function (_super) {
  32024. __extends(StereoscopicGamepadCamera, _super);
  32025. function StereoscopicGamepadCamera(name, position, eyeSpace, isVertical, scene) {
  32026. _super.call(this, name, position, scene);
  32027. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  32028. }
  32029. return StereoscopicGamepadCamera;
  32030. })(BABYLON.GamepadCamera);
  32031. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  32032. })(BABYLON || (BABYLON = {}));
  32033. //# sourceMappingURL=babylon.stereoscopicCamera.js.map
  32034. 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}"};
  32035. 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={}));";