babylon.1.14-beta-debug.js 996 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { 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. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.multiply = function (otherColor) {
  33. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  34. };
  35. Color3.prototype.multiplyToRef = function (otherColor, result) {
  36. result.r = this.r * otherColor.r;
  37. result.g = this.g * otherColor.g;
  38. result.b = this.b * otherColor.b;
  39. };
  40. Color3.prototype.equals = function (otherColor) {
  41. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  42. };
  43. Color3.prototype.scale = function (scale) {
  44. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  45. };
  46. Color3.prototype.scaleToRef = function (scale, result) {
  47. result.r = this.r * scale;
  48. result.g = this.g * scale;
  49. result.b = this.b * scale;
  50. };
  51. Color3.prototype.add = function (otherColor) {
  52. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  53. };
  54. Color3.prototype.addToRef = function (otherColor, result) {
  55. result.r = this.r + otherColor.r;
  56. result.g = this.g + otherColor.g;
  57. result.b = this.b + otherColor.b;
  58. };
  59. Color3.prototype.subtract = function (otherColor) {
  60. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  61. };
  62. Color3.prototype.subtractToRef = function (otherColor, result) {
  63. result.r = this.r - otherColor.r;
  64. result.g = this.g - otherColor.g;
  65. result.b = this.b - otherColor.b;
  66. };
  67. Color3.prototype.clone = function () {
  68. return new Color3(this.r, this.g, this.b);
  69. };
  70. Color3.prototype.copyFrom = function (source) {
  71. this.r = source.r;
  72. this.g = source.g;
  73. this.b = source.b;
  74. };
  75. Color3.prototype.copyFromFloats = function (r, g, b) {
  76. this.r = r;
  77. this.g = g;
  78. this.b = b;
  79. };
  80. Color3.FromArray = function (array) {
  81. return new Color3(array[0], array[1], array[2]);
  82. };
  83. Color3.FromInts = function (r, g, b) {
  84. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  85. };
  86. Color3.Lerp = function (start, end, amount) {
  87. var r = start.r + ((end.r - start.r) * amount);
  88. var g = start.g + ((end.g - start.g) * amount);
  89. var b = start.b + ((end.b - start.b) * amount);
  90. return new Color3(r, g, b);
  91. };
  92. Color3.Red = function () {
  93. return new Color3(1, 0, 0);
  94. };
  95. Color3.Green = function () {
  96. return new Color3(0, 1, 0);
  97. };
  98. Color3.Blue = function () {
  99. return new Color3(0, 0, 1);
  100. };
  101. Color3.Black = function () {
  102. return new Color3(0, 0, 0);
  103. };
  104. Color3.White = function () {
  105. return new Color3(1, 1, 1);
  106. };
  107. Color3.Purple = function () {
  108. return new Color3(0.5, 0, 0.5);
  109. };
  110. Color3.Magenta = function () {
  111. return new Color3(1, 0, 1);
  112. };
  113. Color3.Yellow = function () {
  114. return new Color3(1, 1, 0);
  115. };
  116. Color3.Gray = function () {
  117. return new Color3(0.5, 0.5, 0.5);
  118. };
  119. return Color3;
  120. })();
  121. BABYLON.Color3 = Color3;
  122. var Color4 = (function () {
  123. function Color4(r, g, b, a) {
  124. this.r = r;
  125. this.g = g;
  126. this.b = b;
  127. this.a = a;
  128. }
  129. Color4.prototype.addInPlace = function (right) {
  130. this.r += right.r;
  131. this.g += right.g;
  132. this.b += right.b;
  133. this.a += right.a;
  134. };
  135. Color4.prototype.asArray = function () {
  136. var result = [];
  137. this.toArray(result, 0);
  138. return result;
  139. };
  140. Color4.prototype.toArray = function (array, index) {
  141. if (index === undefined) {
  142. index = 0;
  143. }
  144. array[index] = this.r;
  145. array[index + 1] = this.g;
  146. array[index + 2] = this.b;
  147. array[index + 3] = this.a;
  148. };
  149. Color4.prototype.add = function (right) {
  150. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  151. };
  152. Color4.prototype.subtract = function (right) {
  153. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  154. };
  155. Color4.prototype.subtractToRef = function (right, result) {
  156. result.r = this.r - right.r;
  157. result.g = this.g - right.g;
  158. result.b = this.b - right.b;
  159. result.a = this.a - right.a;
  160. };
  161. Color4.prototype.scale = function (scale) {
  162. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  163. };
  164. Color4.prototype.scaleToRef = function (scale, result) {
  165. result.r = this.r * scale;
  166. result.g = this.g * scale;
  167. result.b = this.b * scale;
  168. result.a = this.a * scale;
  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.Lerp = function (left, right, amount) {
  177. var result = new Color4(0, 0, 0, 0);
  178. BABYLON.Color4.LerpToRef(left, right, amount, result);
  179. return result;
  180. };
  181. Color4.LerpToRef = function (left, right, amount, result) {
  182. result.r = left.r + (right.r - left.r) * amount;
  183. result.g = left.g + (right.g - left.g) * amount;
  184. result.b = left.b + (right.b - left.b) * amount;
  185. result.a = left.a + (right.a - left.a) * amount;
  186. };
  187. Color4.FromArray = function (array, offset) {
  188. if (typeof offset === "undefined") { offset = 0; }
  189. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  190. };
  191. Color4.FromInts = function (r, g, b, a) {
  192. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  193. };
  194. return Color4;
  195. })();
  196. BABYLON.Color4 = Color4;
  197. var Vector2 = (function () {
  198. function Vector2(x, y) {
  199. this.x = x;
  200. this.y = y;
  201. }
  202. Vector2.prototype.toString = function () {
  203. return "{X: " + this.x + " Y:" + this.y + "}";
  204. };
  205. Vector2.prototype.toArray = function (array, index) {
  206. if (index === undefined) {
  207. index = 0;
  208. }
  209. array[index] = this.x;
  210. array[index + 1] = this.y;
  211. };
  212. Vector2.prototype.asArray = function () {
  213. var result = [];
  214. this.toArray(result, 0);
  215. return result;
  216. };
  217. Vector2.prototype.copyFrom = function (source) {
  218. this.x = source.x;
  219. this.y = source.y;
  220. };
  221. Vector2.prototype.copyFromFloats = function (x, y) {
  222. this.x = x;
  223. this.y = y;
  224. };
  225. Vector2.prototype.add = function (otherVector) {
  226. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  227. };
  228. Vector2.prototype.addVector3 = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.subtract = function (otherVector) {
  232. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  233. };
  234. Vector2.prototype.negate = function () {
  235. return new Vector2(-this.x, -this.y);
  236. };
  237. Vector2.prototype.scaleInPlace = function (scale) {
  238. this.x *= scale;
  239. this.y *= scale;
  240. };
  241. Vector2.prototype.scale = function (scale) {
  242. return new Vector2(this.x * scale, this.y * scale);
  243. };
  244. Vector2.prototype.equals = function (otherVector) {
  245. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  246. };
  247. Vector2.prototype.length = function () {
  248. return Math.sqrt(this.x * this.x + this.y * this.y);
  249. };
  250. Vector2.prototype.lengthSquared = function () {
  251. return (this.x * this.x + this.y * this.y);
  252. };
  253. Vector2.prototype.normalize = function () {
  254. var len = this.length();
  255. if (len === 0)
  256. return;
  257. var num = 1.0 / len;
  258. this.x *= num;
  259. this.y *= num;
  260. };
  261. Vector2.prototype.clone = function () {
  262. return new Vector2(this.x, this.y);
  263. };
  264. Vector2.Zero = function () {
  265. return new Vector2(0, 0);
  266. };
  267. Vector2.FromArray = function (array, offset) {
  268. if (!offset) {
  269. offset = 0;
  270. }
  271. return new Vector2(array[offset], array[offset + 1]);
  272. };
  273. Vector2.FromArrayToRef = function (array, offset, result) {
  274. result.x = array[offset];
  275. result.y = array[offset + 1];
  276. };
  277. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  278. var squared = amount * amount;
  279. var cubed = amount * squared;
  280. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  281. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  282. return new Vector2(x, y);
  283. };
  284. Vector2.Clamp = function (value, min, max) {
  285. var x = value.x;
  286. x = (x > max.x) ? max.x : x;
  287. x = (x < min.x) ? min.x : x;
  288. var y = value.y;
  289. y = (y > max.y) ? max.y : y;
  290. y = (y < min.y) ? min.y : y;
  291. return new Vector2(x, y);
  292. };
  293. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  294. var squared = amount * amount;
  295. var cubed = amount * squared;
  296. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  297. var part2 = (-2.0 * cubed) + (3.0 * squared);
  298. var part3 = (cubed - (2.0 * squared)) + amount;
  299. var part4 = cubed - squared;
  300. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  301. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  302. return new Vector2(x, y);
  303. };
  304. Vector2.Lerp = function (start, end, amount) {
  305. var x = start.x + ((end.x - start.x) * amount);
  306. var y = start.y + ((end.y - start.y) * amount);
  307. return new Vector2(x, y);
  308. };
  309. Vector2.Dot = function (left, right) {
  310. return left.x * right.x + left.y * right.y;
  311. };
  312. Vector2.Normalize = function (vector) {
  313. var newVector = vector.clone();
  314. newVector.normalize();
  315. return newVector;
  316. };
  317. Vector2.Minimize = function (left, right) {
  318. var x = (left.x < right.x) ? left.x : right.x;
  319. var y = (left.y < right.y) ? left.y : right.y;
  320. return new Vector2(x, y);
  321. };
  322. Vector2.Maximize = function (left, right) {
  323. var x = (left.x > right.x) ? left.x : right.x;
  324. var y = (left.y > right.y) ? left.y : right.y;
  325. return new Vector2(x, y);
  326. };
  327. Vector2.Transform = function (vector, transformation) {
  328. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  329. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  330. return new Vector2(x, y);
  331. };
  332. Vector2.Distance = function (value1, value2) {
  333. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  334. };
  335. Vector2.DistanceSquared = function (value1, value2) {
  336. var x = value1.x - value2.x;
  337. var y = value1.y - value2.y;
  338. return (x * x) + (y * y);
  339. };
  340. return Vector2;
  341. })();
  342. BABYLON.Vector2 = Vector2;
  343. var Vector3 = (function () {
  344. function Vector3(x, y, z) {
  345. this.x = x;
  346. this.y = y;
  347. this.z = z;
  348. }
  349. Vector3.prototype.toString = function () {
  350. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  351. };
  352. Vector3.prototype.asArray = function () {
  353. var result = [];
  354. this.toArray(result, 0);
  355. return result;
  356. };
  357. Vector3.prototype.toArray = function (array, index) {
  358. if (index === undefined) {
  359. index = 0;
  360. }
  361. array[index] = this.x;
  362. array[index + 1] = this.y;
  363. array[index + 2] = this.z;
  364. };
  365. Vector3.prototype.addInPlace = function (otherVector) {
  366. this.x += otherVector.x;
  367. this.y += otherVector.y;
  368. this.z += otherVector.z;
  369. };
  370. Vector3.prototype.add = function (otherVector) {
  371. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  372. };
  373. Vector3.prototype.addToRef = function (otherVector, result) {
  374. result.x = this.x + otherVector.x;
  375. result.y = this.y + otherVector.y;
  376. result.z = this.z + otherVector.z;
  377. };
  378. Vector3.prototype.subtractInPlace = function (otherVector) {
  379. this.x -= otherVector.x;
  380. this.y -= otherVector.y;
  381. this.z -= otherVector.z;
  382. };
  383. Vector3.prototype.subtract = function (otherVector) {
  384. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  385. };
  386. Vector3.prototype.subtractToRef = function (otherVector, result) {
  387. result.x = this.x - otherVector.x;
  388. result.y = this.y - otherVector.y;
  389. result.z = this.z - otherVector.z;
  390. };
  391. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  392. return new Vector3(this.x - x, this.y - y, this.z - z);
  393. };
  394. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  395. result.x = this.x - x;
  396. result.y = this.y - y;
  397. result.z = this.z - z;
  398. };
  399. Vector3.prototype.negate = function () {
  400. return new Vector3(-this.x, -this.y, -this.z);
  401. };
  402. Vector3.prototype.scaleInPlace = function (scale) {
  403. this.x *= scale;
  404. this.y *= scale;
  405. this.z *= scale;
  406. };
  407. Vector3.prototype.scale = function (scale) {
  408. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  409. };
  410. Vector3.prototype.scaleToRef = function (scale, result) {
  411. result.x = this.x * scale;
  412. result.y = this.y * scale;
  413. result.z = this.z * scale;
  414. };
  415. Vector3.prototype.equals = function (otherVector) {
  416. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  417. };
  418. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  419. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  420. };
  421. Vector3.prototype.equalsToFloats = function (x, y, z) {
  422. return this.x === x && this.y === y && this.z === z;
  423. };
  424. Vector3.prototype.multiplyInPlace = function (otherVector) {
  425. this.x *= otherVector.x;
  426. this.y *= otherVector.y;
  427. this.z *= otherVector.z;
  428. };
  429. Vector3.prototype.multiply = function (otherVector) {
  430. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  431. };
  432. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  433. result.x = this.x * otherVector.x;
  434. result.y = this.y * otherVector.y;
  435. result.z = this.z * otherVector.z;
  436. };
  437. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  438. return new Vector3(this.x * x, this.y * y, this.z * z);
  439. };
  440. Vector3.prototype.divide = function (otherVector) {
  441. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  442. };
  443. Vector3.prototype.divideToRef = function (otherVector, result) {
  444. result.x = this.x / otherVector.x;
  445. result.y = this.y / otherVector.y;
  446. result.z = this.z / otherVector.z;
  447. };
  448. Vector3.prototype.MinimizeInPlace = function (other) {
  449. if (other.x < this.x)
  450. this.x = other.x;
  451. if (other.y < this.y)
  452. this.y = other.y;
  453. if (other.z < this.z)
  454. this.z = other.z;
  455. };
  456. Vector3.prototype.MaximizeInPlace = function (other) {
  457. if (other.x > this.x)
  458. this.x = other.x;
  459. if (other.y > this.y)
  460. this.y = other.y;
  461. if (other.z > this.z)
  462. this.z = other.z;
  463. };
  464. Vector3.prototype.length = function () {
  465. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  466. };
  467. Vector3.prototype.lengthSquared = function () {
  468. return (this.x * this.x + this.y * this.y + this.z * this.z);
  469. };
  470. Vector3.prototype.normalize = function () {
  471. var len = this.length();
  472. if (len === 0)
  473. return;
  474. var num = 1.0 / len;
  475. this.x *= num;
  476. this.y *= num;
  477. this.z *= num;
  478. };
  479. Vector3.prototype.clone = function () {
  480. return new Vector3(this.x, this.y, this.z);
  481. };
  482. Vector3.prototype.copyFrom = function (source) {
  483. this.x = source.x;
  484. this.y = source.y;
  485. this.z = source.z;
  486. };
  487. Vector3.prototype.copyFromFloats = function (x, y, z) {
  488. this.x = x;
  489. this.y = y;
  490. this.z = z;
  491. };
  492. Vector3.FromArray = function (array, offset) {
  493. if (!offset) {
  494. offset = 0;
  495. }
  496. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  497. };
  498. Vector3.FromArrayToRef = function (array, offset, result) {
  499. result.x = array[offset];
  500. result.y = array[offset + 1];
  501. result.z = array[offset + 2];
  502. };
  503. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  504. result.x = array[offset];
  505. result.y = array[offset + 1];
  506. result.z = array[offset + 2];
  507. };
  508. Vector3.FromFloatsToRef = function (x, y, z, result) {
  509. result.x = x;
  510. result.y = y;
  511. result.z = z;
  512. };
  513. Vector3.Zero = function () {
  514. return new Vector3(0, 0, 0);
  515. };
  516. Vector3.Up = function () {
  517. return new Vector3(0, 1.0, 0);
  518. };
  519. Vector3.TransformCoordinates = function (vector, transformation) {
  520. var result = Vector3.Zero();
  521. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  522. return result;
  523. };
  524. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  525. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  526. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  527. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  528. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  529. result.x = x / w;
  530. result.y = y / w;
  531. result.z = z / w;
  532. };
  533. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  534. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  535. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  536. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  537. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  538. result.x = rx / rw;
  539. result.y = ry / rw;
  540. result.z = rz / rw;
  541. };
  542. Vector3.TransformNormal = function (vector, transformation) {
  543. var result = Vector3.Zero();
  544. Vector3.TransformNormalToRef(vector, transformation, result);
  545. return result;
  546. };
  547. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  548. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  549. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  550. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  551. };
  552. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  553. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  554. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  555. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  556. };
  557. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  558. var squared = amount * amount;
  559. var cubed = amount * squared;
  560. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  561. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  562. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  563. return new Vector3(x, y, z);
  564. };
  565. Vector3.Clamp = function (value, min, max) {
  566. var x = value.x;
  567. x = (x > max.x) ? max.x : x;
  568. x = (x < min.x) ? min.x : x;
  569. var y = value.y;
  570. y = (y > max.y) ? max.y : y;
  571. y = (y < min.y) ? min.y : y;
  572. var z = value.z;
  573. z = (z > max.z) ? max.z : z;
  574. z = (z < min.z) ? min.z : z;
  575. return new Vector3(x, y, z);
  576. };
  577. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  578. var squared = amount * amount;
  579. var cubed = amount * squared;
  580. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  581. var part2 = (-2.0 * cubed) + (3.0 * squared);
  582. var part3 = (cubed - (2.0 * squared)) + amount;
  583. var part4 = cubed - squared;
  584. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  585. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  586. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  587. return new Vector3(x, y, z);
  588. };
  589. Vector3.Lerp = function (start, end, amount) {
  590. var x = start.x + ((end.x - start.x) * amount);
  591. var y = start.y + ((end.y - start.y) * amount);
  592. var z = start.z + ((end.z - start.z) * amount);
  593. return new Vector3(x, y, z);
  594. };
  595. Vector3.Dot = function (left, right) {
  596. return (left.x * right.x + left.y * right.y + left.z * right.z);
  597. };
  598. Vector3.Cross = function (left, right) {
  599. var result = Vector3.Zero();
  600. Vector3.CrossToRef(left, right, result);
  601. return result;
  602. };
  603. Vector3.CrossToRef = function (left, right, result) {
  604. result.x = left.y * right.z - left.z * right.y;
  605. result.y = left.z * right.x - left.x * right.z;
  606. result.z = left.x * right.y - left.y * right.x;
  607. };
  608. Vector3.Normalize = function (vector) {
  609. var result = Vector3.Zero();
  610. Vector3.NormalizeToRef(vector, result);
  611. return result;
  612. };
  613. Vector3.NormalizeToRef = function (vector, result) {
  614. result.copyFrom(vector);
  615. result.normalize();
  616. };
  617. Vector3.Project = function (vector, world, transform, viewport) {
  618. var cw = viewport.width;
  619. var ch = viewport.height;
  620. var cx = viewport.x;
  621. var cy = viewport.y;
  622. var viewportMatrix = BABYLON.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);
  623. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  624. return Vector3.TransformCoordinates(vector, finalMatrix);
  625. };
  626. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  627. var matrix = world.multiply(view).multiply(projection);
  628. matrix.invert();
  629. source.x = source.x / viewportWidth * 2 - 1;
  630. source.y = -(source.y / viewportHeight * 2 - 1);
  631. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  632. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  633. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  634. vector = vector.scale(1.0 / num);
  635. }
  636. return vector;
  637. };
  638. Vector3.Minimize = function (left, right) {
  639. var min = left.clone();
  640. min.MinimizeInPlace(right);
  641. return min;
  642. };
  643. Vector3.Maximize = function (left, right) {
  644. var max = left.clone();
  645. max.MaximizeInPlace(right);
  646. return max;
  647. };
  648. Vector3.Distance = function (value1, value2) {
  649. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  650. };
  651. Vector3.DistanceSquared = function (value1, value2) {
  652. var x = value1.x - value2.x;
  653. var y = value1.y - value2.y;
  654. var z = value1.z - value2.z;
  655. return (x * x) + (y * y) + (z * z);
  656. };
  657. Vector3.Center = function (value1, value2) {
  658. var center = value1.add(value2);
  659. center.scaleInPlace(0.5);
  660. return center;
  661. };
  662. return Vector3;
  663. })();
  664. BABYLON.Vector3 = Vector3;
  665. var Quaternion = (function () {
  666. function Quaternion(x, y, z, w) {
  667. if (typeof x === "undefined") { x = 0; }
  668. if (typeof y === "undefined") { y = 0; }
  669. if (typeof z === "undefined") { z = 0; }
  670. if (typeof w === "undefined") { w = 1; }
  671. this.x = x;
  672. this.y = y;
  673. this.z = z;
  674. this.w = w;
  675. }
  676. Quaternion.prototype.toString = function () {
  677. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  678. };
  679. Quaternion.prototype.asArray = function () {
  680. return [this.x, this.y, this.z, this.w];
  681. };
  682. Quaternion.prototype.equals = function (otherQuaternion) {
  683. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  684. };
  685. Quaternion.prototype.clone = function () {
  686. return new Quaternion(this.x, this.y, this.z, this.w);
  687. };
  688. Quaternion.prototype.copyFrom = function (other) {
  689. this.x = other.x;
  690. this.y = other.y;
  691. this.z = other.z;
  692. this.w = other.w;
  693. };
  694. Quaternion.prototype.add = function (other) {
  695. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  696. };
  697. Quaternion.prototype.subtract = function (other) {
  698. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  699. };
  700. Quaternion.prototype.scale = function (value) {
  701. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  702. };
  703. Quaternion.prototype.multiply = function (q1) {
  704. var result = new Quaternion(0, 0, 0, 1.0);
  705. this.multiplyToRef(q1, result);
  706. return result;
  707. };
  708. Quaternion.prototype.multiplyToRef = function (q1, result) {
  709. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  710. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  711. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  712. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  713. };
  714. Quaternion.prototype.length = function () {
  715. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  716. };
  717. Quaternion.prototype.normalize = function () {
  718. var length = 1.0 / this.length();
  719. this.x *= length;
  720. this.y *= length;
  721. this.z *= length;
  722. this.w *= length;
  723. };
  724. Quaternion.prototype.toEulerAngles = function () {
  725. var qx = this.x;
  726. var qy = this.y;
  727. var qz = this.z;
  728. var qw = this.w;
  729. var sqx = qx * qx;
  730. var sqy = qy * qy;
  731. var sqz = qz * qz;
  732. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  733. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  734. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  735. var gimbaLockTest = qx * qy + qz * qw;
  736. if (gimbaLockTest > 0.499) {
  737. yaw = 2.0 * Math.atan2(qx, qw);
  738. roll = 0;
  739. } else if (gimbaLockTest < -0.499) {
  740. yaw = -2.0 * Math.atan2(qx, qw);
  741. roll = 0;
  742. }
  743. return new Vector3(pitch, yaw, roll);
  744. };
  745. Quaternion.prototype.toRotationMatrix = function (result) {
  746. var xx = this.x * this.x;
  747. var yy = this.y * this.y;
  748. var zz = this.z * this.z;
  749. var xy = this.x * this.y;
  750. var zw = this.z * this.w;
  751. var zx = this.z * this.x;
  752. var yw = this.y * this.w;
  753. var yz = this.y * this.z;
  754. var xw = this.x * this.w;
  755. result.m[0] = 1.0 - (2.0 * (yy + zz));
  756. result.m[1] = 2.0 * (xy + zw);
  757. result.m[2] = 2.0 * (zx - yw);
  758. result.m[3] = 0;
  759. result.m[4] = 2.0 * (xy - zw);
  760. result.m[5] = 1.0 - (2.0 * (zz + xx));
  761. result.m[6] = 2.0 * (yz + xw);
  762. result.m[7] = 0;
  763. result.m[8] = 2.0 * (zx + yw);
  764. result.m[9] = 2.0 * (yz - xw);
  765. result.m[10] = 1.0 - (2.0 * (yy + xx));
  766. result.m[11] = 0;
  767. result.m[12] = 0;
  768. result.m[13] = 0;
  769. result.m[14] = 0;
  770. result.m[15] = 1.0;
  771. };
  772. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  773. var data = matrix.m;
  774. var m11 = data[0], m12 = data[4], m13 = data[8];
  775. var m21 = data[1], m22 = data[5], m23 = data[9];
  776. var m31 = data[2], m32 = data[6], m33 = data[10];
  777. var trace = m11 + m22 + m33;
  778. var s;
  779. if (trace > 0) {
  780. s = 0.5 / Math.sqrt(trace + 1.0);
  781. this.w = 0.25 / s;
  782. this.x = (m32 - m23) * s;
  783. this.y = (m13 - m31) * s;
  784. this.z = (m21 - m12) * s;
  785. return;
  786. }
  787. if (m11 > m22 && m11 > m33) {
  788. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  789. this.w = (m32 - m23) / s;
  790. this.x = 0.25 * s;
  791. this.y = (m12 + m21) / s;
  792. this.z = (m13 + m31) / s;
  793. return;
  794. }
  795. if (m22 > m33) {
  796. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  797. this.w = (m13 - m31) / s;
  798. this.x = (m12 + m21) / s;
  799. this.y = 0.25 * s;
  800. this.z = (m23 + m32) / s;
  801. return;
  802. }
  803. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  804. this.w = (m21 - m12) / s;
  805. this.x = (m13 + m31) / s;
  806. this.y = (m23 + m32) / s;
  807. this.z = 0.25 * s;
  808. };
  809. Quaternion.RotationAxis = function (axis, angle) {
  810. var result = new Quaternion();
  811. var sin = Math.sin(angle / 2);
  812. result.w = Math.cos(angle / 2);
  813. result.x = axis.x * sin;
  814. result.y = axis.y * sin;
  815. result.z = axis.z * sin;
  816. return result;
  817. };
  818. Quaternion.FromArray = function (array, offset) {
  819. if (!offset) {
  820. offset = 0;
  821. }
  822. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  823. };
  824. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  825. var result = new Quaternion();
  826. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  827. return result;
  828. };
  829. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  830. var halfRoll = roll * 0.5;
  831. var halfPitch = pitch * 0.5;
  832. var halfYaw = yaw * 0.5;
  833. var sinRoll = Math.sin(halfRoll);
  834. var cosRoll = Math.cos(halfRoll);
  835. var sinPitch = Math.sin(halfPitch);
  836. var cosPitch = Math.cos(halfPitch);
  837. var sinYaw = Math.sin(halfYaw);
  838. var cosYaw = Math.cos(halfYaw);
  839. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  840. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  841. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  842. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  843. };
  844. Quaternion.Slerp = function (left, right, amount) {
  845. var num2;
  846. var num3;
  847. var num = amount;
  848. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  849. var flag = false;
  850. if (num4 < 0) {
  851. flag = true;
  852. num4 = -num4;
  853. }
  854. if (num4 > 0.999999) {
  855. num3 = 1 - num;
  856. num2 = flag ? -num : num;
  857. } else {
  858. var num5 = Math.acos(num4);
  859. var num6 = (1.0 / Math.sin(num5));
  860. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  861. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  862. }
  863. 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));
  864. };
  865. return Quaternion;
  866. })();
  867. BABYLON.Quaternion = Quaternion;
  868. var Matrix = (function () {
  869. function Matrix() {
  870. this.m = new Float32Array(16);
  871. }
  872. Matrix.prototype.isIdentity = function () {
  873. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  874. return false;
  875. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  876. return false;
  877. return true;
  878. };
  879. Matrix.prototype.determinant = function () {
  880. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  881. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  882. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  883. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  884. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  885. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  886. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  887. };
  888. Matrix.prototype.toArray = function () {
  889. return this.m;
  890. };
  891. Matrix.prototype.asArray = function () {
  892. return this.toArray();
  893. };
  894. Matrix.prototype.invert = function () {
  895. this.invertToRef(this);
  896. };
  897. Matrix.prototype.invertToRef = function (other) {
  898. var l1 = this.m[0];
  899. var l2 = this.m[1];
  900. var l3 = this.m[2];
  901. var l4 = this.m[3];
  902. var l5 = this.m[4];
  903. var l6 = this.m[5];
  904. var l7 = this.m[6];
  905. var l8 = this.m[7];
  906. var l9 = this.m[8];
  907. var l10 = this.m[9];
  908. var l11 = this.m[10];
  909. var l12 = this.m[11];
  910. var l13 = this.m[12];
  911. var l14 = this.m[13];
  912. var l15 = this.m[14];
  913. var l16 = this.m[15];
  914. var l17 = (l11 * l16) - (l12 * l15);
  915. var l18 = (l10 * l16) - (l12 * l14);
  916. var l19 = (l10 * l15) - (l11 * l14);
  917. var l20 = (l9 * l16) - (l12 * l13);
  918. var l21 = (l9 * l15) - (l11 * l13);
  919. var l22 = (l9 * l14) - (l10 * l13);
  920. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  921. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  922. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  923. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  924. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  925. var l28 = (l7 * l16) - (l8 * l15);
  926. var l29 = (l6 * l16) - (l8 * l14);
  927. var l30 = (l6 * l15) - (l7 * l14);
  928. var l31 = (l5 * l16) - (l8 * l13);
  929. var l32 = (l5 * l15) - (l7 * l13);
  930. var l33 = (l5 * l14) - (l6 * l13);
  931. var l34 = (l7 * l12) - (l8 * l11);
  932. var l35 = (l6 * l12) - (l8 * l10);
  933. var l36 = (l6 * l11) - (l7 * l10);
  934. var l37 = (l5 * l12) - (l8 * l9);
  935. var l38 = (l5 * l11) - (l7 * l9);
  936. var l39 = (l5 * l10) - (l6 * l9);
  937. other.m[0] = l23 * l27;
  938. other.m[4] = l24 * l27;
  939. other.m[8] = l25 * l27;
  940. other.m[12] = l26 * l27;
  941. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  942. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  943. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  944. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  945. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  946. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  947. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  948. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  949. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  950. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  951. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  952. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  953. };
  954. Matrix.prototype.setTranslation = function (vector3) {
  955. this.m[12] = vector3.x;
  956. this.m[13] = vector3.y;
  957. this.m[14] = vector3.z;
  958. };
  959. Matrix.prototype.multiply = function (other) {
  960. var result = new Matrix();
  961. this.multiplyToRef(other, result);
  962. return result;
  963. };
  964. Matrix.prototype.copyFrom = function (other) {
  965. for (var index = 0; index < 16; index++) {
  966. this.m[index] = other.m[index];
  967. }
  968. };
  969. Matrix.prototype.copyToArray = function (array, offset) {
  970. if (typeof offset === "undefined") { offset = 0; }
  971. for (var index = 0; index < 16; index++) {
  972. array[offset + index] = this.m[index];
  973. }
  974. };
  975. Matrix.prototype.multiplyToRef = function (other, result) {
  976. this.multiplyToArray(other, result.m, 0);
  977. };
  978. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  979. var tm0 = this.m[0];
  980. var tm1 = this.m[1];
  981. var tm2 = this.m[2];
  982. var tm3 = this.m[3];
  983. var tm4 = this.m[4];
  984. var tm5 = this.m[5];
  985. var tm6 = this.m[6];
  986. var tm7 = this.m[7];
  987. var tm8 = this.m[8];
  988. var tm9 = this.m[9];
  989. var tm10 = this.m[10];
  990. var tm11 = this.m[11];
  991. var tm12 = this.m[12];
  992. var tm13 = this.m[13];
  993. var tm14 = this.m[14];
  994. var tm15 = this.m[15];
  995. var om0 = other.m[0];
  996. var om1 = other.m[1];
  997. var om2 = other.m[2];
  998. var om3 = other.m[3];
  999. var om4 = other.m[4];
  1000. var om5 = other.m[5];
  1001. var om6 = other.m[6];
  1002. var om7 = other.m[7];
  1003. var om8 = other.m[8];
  1004. var om9 = other.m[9];
  1005. var om10 = other.m[10];
  1006. var om11 = other.m[11];
  1007. var om12 = other.m[12];
  1008. var om13 = other.m[13];
  1009. var om14 = other.m[14];
  1010. var om15 = other.m[15];
  1011. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1012. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1013. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1014. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1015. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1016. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1017. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1018. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1019. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1020. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1021. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1022. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1023. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1024. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1025. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1026. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1027. };
  1028. Matrix.prototype.equals = function (value) {
  1029. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1030. };
  1031. Matrix.prototype.clone = function () {
  1032. 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]);
  1033. };
  1034. Matrix.FromArray = function (array, offset) {
  1035. var result = new Matrix();
  1036. if (!offset) {
  1037. offset = 0;
  1038. }
  1039. Matrix.FromArrayToRef(array, offset, result);
  1040. return result;
  1041. };
  1042. Matrix.FromArrayToRef = function (array, offset, result) {
  1043. for (var index = 0; index < 16; index++) {
  1044. result.m[index] = array[index + offset];
  1045. }
  1046. };
  1047. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1048. result.m[0] = initialM11;
  1049. result.m[1] = initialM12;
  1050. result.m[2] = initialM13;
  1051. result.m[3] = initialM14;
  1052. result.m[4] = initialM21;
  1053. result.m[5] = initialM22;
  1054. result.m[6] = initialM23;
  1055. result.m[7] = initialM24;
  1056. result.m[8] = initialM31;
  1057. result.m[9] = initialM32;
  1058. result.m[10] = initialM33;
  1059. result.m[11] = initialM34;
  1060. result.m[12] = initialM41;
  1061. result.m[13] = initialM42;
  1062. result.m[14] = initialM43;
  1063. result.m[15] = initialM44;
  1064. };
  1065. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1066. var result = new Matrix();
  1067. result.m[0] = initialM11;
  1068. result.m[1] = initialM12;
  1069. result.m[2] = initialM13;
  1070. result.m[3] = initialM14;
  1071. result.m[4] = initialM21;
  1072. result.m[5] = initialM22;
  1073. result.m[6] = initialM23;
  1074. result.m[7] = initialM24;
  1075. result.m[8] = initialM31;
  1076. result.m[9] = initialM32;
  1077. result.m[10] = initialM33;
  1078. result.m[11] = initialM34;
  1079. result.m[12] = initialM41;
  1080. result.m[13] = initialM42;
  1081. result.m[14] = initialM43;
  1082. result.m[15] = initialM44;
  1083. return result;
  1084. };
  1085. Matrix.Identity = function () {
  1086. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1087. };
  1088. Matrix.IdentityToRef = function (result) {
  1089. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1090. };
  1091. Matrix.Zero = function () {
  1092. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1093. };
  1094. Matrix.RotationX = function (angle) {
  1095. var result = new Matrix();
  1096. Matrix.RotationXToRef(angle, result);
  1097. return result;
  1098. };
  1099. Matrix.RotationXToRef = function (angle, result) {
  1100. var s = Math.sin(angle);
  1101. var c = Math.cos(angle);
  1102. result.m[0] = 1.0;
  1103. result.m[15] = 1.0;
  1104. result.m[5] = c;
  1105. result.m[10] = c;
  1106. result.m[9] = -s;
  1107. result.m[6] = s;
  1108. result.m[1] = 0;
  1109. result.m[2] = 0;
  1110. result.m[3] = 0;
  1111. result.m[4] = 0;
  1112. result.m[7] = 0;
  1113. result.m[8] = 0;
  1114. result.m[11] = 0;
  1115. result.m[12] = 0;
  1116. result.m[13] = 0;
  1117. result.m[14] = 0;
  1118. };
  1119. Matrix.RotationY = function (angle) {
  1120. var result = new Matrix();
  1121. Matrix.RotationYToRef(angle, result);
  1122. return result;
  1123. };
  1124. Matrix.RotationYToRef = function (angle, result) {
  1125. var s = Math.sin(angle);
  1126. var c = Math.cos(angle);
  1127. result.m[5] = 1.0;
  1128. result.m[15] = 1.0;
  1129. result.m[0] = c;
  1130. result.m[2] = -s;
  1131. result.m[8] = s;
  1132. result.m[10] = c;
  1133. result.m[1] = 0;
  1134. result.m[3] = 0;
  1135. result.m[4] = 0;
  1136. result.m[6] = 0;
  1137. result.m[7] = 0;
  1138. result.m[9] = 0;
  1139. result.m[11] = 0;
  1140. result.m[12] = 0;
  1141. result.m[13] = 0;
  1142. result.m[14] = 0;
  1143. };
  1144. Matrix.RotationZ = function (angle) {
  1145. var result = new Matrix();
  1146. Matrix.RotationZToRef(angle, result);
  1147. return result;
  1148. };
  1149. Matrix.RotationZToRef = function (angle, result) {
  1150. var s = Math.sin(angle);
  1151. var c = Math.cos(angle);
  1152. result.m[10] = 1.0;
  1153. result.m[15] = 1.0;
  1154. result.m[0] = c;
  1155. result.m[1] = s;
  1156. result.m[4] = -s;
  1157. result.m[5] = c;
  1158. result.m[2] = 0;
  1159. result.m[3] = 0;
  1160. result.m[6] = 0;
  1161. result.m[7] = 0;
  1162. result.m[8] = 0;
  1163. result.m[9] = 0;
  1164. result.m[11] = 0;
  1165. result.m[12] = 0;
  1166. result.m[13] = 0;
  1167. result.m[14] = 0;
  1168. };
  1169. Matrix.RotationAxis = function (axis, angle) {
  1170. var s = Math.sin(-angle);
  1171. var c = Math.cos(-angle);
  1172. var c1 = 1 - c;
  1173. axis.normalize();
  1174. var result = Matrix.Zero();
  1175. result.m[0] = (axis.x * axis.x) * c1 + c;
  1176. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1177. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1178. result.m[3] = 0.0;
  1179. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1180. result.m[5] = (axis.y * axis.y) * c1 + c;
  1181. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1182. result.m[7] = 0.0;
  1183. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1184. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1185. result.m[10] = (axis.z * axis.z) * c1 + c;
  1186. result.m[11] = 0.0;
  1187. result.m[15] = 1.0;
  1188. return result;
  1189. };
  1190. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1191. var result = new Matrix();
  1192. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1193. return result;
  1194. };
  1195. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1196. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1197. this._tempQuaternion.toRotationMatrix(result);
  1198. };
  1199. Matrix.Scaling = function (x, y, z) {
  1200. var result = Matrix.Zero();
  1201. Matrix.ScalingToRef(x, y, z, result);
  1202. return result;
  1203. };
  1204. Matrix.ScalingToRef = function (x, y, z, result) {
  1205. result.m[0] = x;
  1206. result.m[1] = 0;
  1207. result.m[2] = 0;
  1208. result.m[3] = 0;
  1209. result.m[4] = 0;
  1210. result.m[5] = y;
  1211. result.m[6] = 0;
  1212. result.m[7] = 0;
  1213. result.m[8] = 0;
  1214. result.m[9] = 0;
  1215. result.m[10] = z;
  1216. result.m[11] = 0;
  1217. result.m[12] = 0;
  1218. result.m[13] = 0;
  1219. result.m[14] = 0;
  1220. result.m[15] = 1.0;
  1221. };
  1222. Matrix.Translation = function (x, y, z) {
  1223. var result = Matrix.Identity();
  1224. Matrix.TranslationToRef(x, y, z, result);
  1225. return result;
  1226. };
  1227. Matrix.TranslationToRef = function (x, y, z, result) {
  1228. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1229. };
  1230. Matrix.LookAtLH = function (eye, target, up) {
  1231. var result = Matrix.Zero();
  1232. Matrix.LookAtLHToRef(eye, target, up, result);
  1233. return result;
  1234. };
  1235. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1236. target.subtractToRef(eye, this._zAxis);
  1237. this._zAxis.normalize();
  1238. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1239. this._xAxis.normalize();
  1240. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1241. this._yAxis.normalize();
  1242. var ex = -Vector3.Dot(this._xAxis, eye);
  1243. var ey = -Vector3.Dot(this._yAxis, eye);
  1244. var ez = -Vector3.Dot(this._zAxis, eye);
  1245. 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);
  1246. };
  1247. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1248. var hw = 2.0 / width;
  1249. var hh = 2.0 / height;
  1250. var id = 1.0 / (zfar - znear);
  1251. var nid = znear / (znear - zfar);
  1252. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1253. };
  1254. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1255. var matrix = Matrix.Zero();
  1256. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1257. return matrix;
  1258. };
  1259. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1260. result.m[0] = 2.0 / (right - left);
  1261. result.m[1] = result.m[2] = result.m[3] = 0;
  1262. result.m[5] = 2.0 / (top - bottom);
  1263. result.m[4] = result.m[6] = result.m[7] = 0;
  1264. result.m[10] = -1.0 / (znear - zfar);
  1265. result.m[8] = result.m[9] = result.m[11] = 0;
  1266. result.m[12] = (left + right) / (left - right);
  1267. result.m[13] = (top + bottom) / (bottom - top);
  1268. result.m[14] = znear / (znear - zfar);
  1269. result.m[15] = 1.0;
  1270. };
  1271. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1272. var matrix = Matrix.Zero();
  1273. matrix.m[0] = (2.0 * znear) / width;
  1274. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1275. matrix.m[5] = (2.0 * znear) / height;
  1276. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1277. matrix.m[10] = -zfar / (znear - zfar);
  1278. matrix.m[8] = matrix.m[9] = 0.0;
  1279. matrix.m[11] = 1.0;
  1280. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1281. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1282. return matrix;
  1283. };
  1284. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1285. var matrix = Matrix.Zero();
  1286. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1287. return matrix;
  1288. };
  1289. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1290. var tan = 1.0 / (Math.tan(fov * 0.5));
  1291. result.m[0] = tan / aspect;
  1292. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1293. result.m[5] = tan;
  1294. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1295. result.m[8] = result.m[9] = 0.0;
  1296. result.m[10] = -zfar / (znear - zfar);
  1297. result.m[11] = 1.0;
  1298. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1299. result.m[14] = (znear * zfar) / (znear - zfar);
  1300. };
  1301. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1302. var cw = viewport.width;
  1303. var ch = viewport.height;
  1304. var cx = viewport.x;
  1305. var cy = viewport.y;
  1306. 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);
  1307. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1308. };
  1309. Matrix.Transpose = function (matrix) {
  1310. var result = new Matrix();
  1311. result.m[0] = matrix.m[0];
  1312. result.m[1] = matrix.m[4];
  1313. result.m[2] = matrix.m[8];
  1314. result.m[3] = matrix.m[12];
  1315. result.m[4] = matrix.m[1];
  1316. result.m[5] = matrix.m[5];
  1317. result.m[6] = matrix.m[9];
  1318. result.m[7] = matrix.m[13];
  1319. result.m[8] = matrix.m[2];
  1320. result.m[9] = matrix.m[6];
  1321. result.m[10] = matrix.m[10];
  1322. result.m[11] = matrix.m[14];
  1323. result.m[12] = matrix.m[3];
  1324. result.m[13] = matrix.m[7];
  1325. result.m[14] = matrix.m[11];
  1326. result.m[15] = matrix.m[15];
  1327. return result;
  1328. };
  1329. Matrix.Reflection = function (plane) {
  1330. var matrix = new Matrix();
  1331. Matrix.ReflectionToRef(plane, matrix);
  1332. return matrix;
  1333. };
  1334. Matrix.ReflectionToRef = function (plane, result) {
  1335. plane.normalize();
  1336. var x = plane.normal.x;
  1337. var y = plane.normal.y;
  1338. var z = plane.normal.z;
  1339. var temp = -2 * x;
  1340. var temp2 = -2 * y;
  1341. var temp3 = -2 * z;
  1342. result.m[0] = (temp * x) + 1;
  1343. result.m[1] = temp2 * x;
  1344. result.m[2] = temp3 * x;
  1345. result.m[3] = 0.0;
  1346. result.m[4] = temp * y;
  1347. result.m[5] = (temp2 * y) + 1;
  1348. result.m[6] = temp3 * y;
  1349. result.m[7] = 0.0;
  1350. result.m[8] = temp * z;
  1351. result.m[9] = temp2 * z;
  1352. result.m[10] = (temp3 * z) + 1;
  1353. result.m[11] = 0.0;
  1354. result.m[12] = temp * plane.d;
  1355. result.m[13] = temp2 * plane.d;
  1356. result.m[14] = temp3 * plane.d;
  1357. result.m[15] = 1.0;
  1358. };
  1359. Matrix._tempQuaternion = new Quaternion();
  1360. Matrix._xAxis = Vector3.Zero();
  1361. Matrix._yAxis = Vector3.Zero();
  1362. Matrix._zAxis = Vector3.Zero();
  1363. return Matrix;
  1364. })();
  1365. BABYLON.Matrix = Matrix;
  1366. var Plane = (function () {
  1367. function Plane(a, b, c, d) {
  1368. this.normal = new Vector3(a, b, c);
  1369. this.d = d;
  1370. }
  1371. Plane.prototype.asArray = function () {
  1372. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1373. };
  1374. Plane.prototype.clone = function () {
  1375. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1376. };
  1377. Plane.prototype.normalize = function () {
  1378. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1379. var magnitude = 0;
  1380. if (norm != 0) {
  1381. magnitude = 1.0 / norm;
  1382. }
  1383. this.normal.x *= magnitude;
  1384. this.normal.y *= magnitude;
  1385. this.normal.z *= magnitude;
  1386. this.d *= magnitude;
  1387. };
  1388. Plane.prototype.transform = function (transformation) {
  1389. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1390. var x = this.normal.x;
  1391. var y = this.normal.y;
  1392. var z = this.normal.z;
  1393. var d = this.d;
  1394. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1395. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1396. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1397. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1398. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1399. };
  1400. Plane.prototype.dotCoordinate = function (point) {
  1401. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1402. };
  1403. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1404. var x1 = point2.x - point1.x;
  1405. var y1 = point2.y - point1.y;
  1406. var z1 = point2.z - point1.z;
  1407. var x2 = point3.x - point1.x;
  1408. var y2 = point3.y - point1.y;
  1409. var z2 = point3.z - point1.z;
  1410. var yz = (y1 * z2) - (z1 * y2);
  1411. var xz = (z1 * x2) - (x1 * z2);
  1412. var xy = (x1 * y2) - (y1 * x2);
  1413. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1414. var invPyth;
  1415. if (pyth != 0) {
  1416. invPyth = 1.0 / pyth;
  1417. } else {
  1418. invPyth = 0;
  1419. }
  1420. this.normal.x = yz * invPyth;
  1421. this.normal.y = xz * invPyth;
  1422. this.normal.z = xy * invPyth;
  1423. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1424. };
  1425. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1426. var dot = Vector3.Dot(this.normal, direction);
  1427. return (dot <= epsilon);
  1428. };
  1429. Plane.prototype.signedDistanceTo = function (point) {
  1430. return Vector3.Dot(point, this.normal) + this.d;
  1431. };
  1432. Plane.FromArray = function (array) {
  1433. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1434. };
  1435. Plane.FromPoints = function (point1, point2, point3) {
  1436. var result = new BABYLON.Plane(0, 0, 0, 0);
  1437. result.copyFromPoints(point1, point2, point3);
  1438. return result;
  1439. };
  1440. Plane.FromPositionAndNormal = function (origin, normal) {
  1441. var result = new BABYLON.Plane(0, 0, 0, 0);
  1442. normal.normalize();
  1443. result.normal = normal;
  1444. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1445. return result;
  1446. };
  1447. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1448. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1449. return Vector3.Dot(point, normal) + d;
  1450. };
  1451. return Plane;
  1452. })();
  1453. BABYLON.Plane = Plane;
  1454. var Viewport = (function () {
  1455. function Viewport(x, y, width, height) {
  1456. this.x = x;
  1457. this.y = y;
  1458. this.width = width;
  1459. this.height = height;
  1460. }
  1461. Viewport.prototype.toGlobal = function (engine) {
  1462. var width = engine.getRenderWidth();
  1463. var height = engine.getRenderHeight();
  1464. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1465. };
  1466. return Viewport;
  1467. })();
  1468. BABYLON.Viewport = Viewport;
  1469. var Frustum = (function () {
  1470. function Frustum() {
  1471. }
  1472. Frustum.GetPlanes = function (transform) {
  1473. var frustumPlanes = [];
  1474. for (var index = 0; index < 6; index++) {
  1475. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1476. }
  1477. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1478. return frustumPlanes;
  1479. };
  1480. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1481. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1482. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1483. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1484. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1485. frustumPlanes[0].normalize();
  1486. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1487. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1488. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1489. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1490. frustumPlanes[1].normalize();
  1491. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1492. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1493. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1494. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1495. frustumPlanes[2].normalize();
  1496. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1497. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1498. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1499. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1500. frustumPlanes[3].normalize();
  1501. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1502. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1503. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1504. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1505. frustumPlanes[4].normalize();
  1506. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1507. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1508. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1509. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1510. frustumPlanes[5].normalize();
  1511. };
  1512. return Frustum;
  1513. })();
  1514. BABYLON.Frustum = Frustum;
  1515. var Ray = (function () {
  1516. function Ray(origin, direction) {
  1517. this.origin = origin;
  1518. this.direction = direction;
  1519. }
  1520. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1521. var d = 0.0;
  1522. var maxValue = Number.MAX_VALUE;
  1523. if (Math.abs(this.direction.x) < 0.0000001) {
  1524. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1525. return false;
  1526. }
  1527. } else {
  1528. var inv = 1.0 / this.direction.x;
  1529. var min = (minimum.x - this.origin.x) * inv;
  1530. var max = (maximum.x - this.origin.x) * inv;
  1531. if (min > max) {
  1532. var temp = min;
  1533. min = max;
  1534. max = temp;
  1535. }
  1536. d = Math.max(min, d);
  1537. maxValue = Math.min(max, maxValue);
  1538. if (d > maxValue) {
  1539. return false;
  1540. }
  1541. }
  1542. if (Math.abs(this.direction.y) < 0.0000001) {
  1543. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1544. return false;
  1545. }
  1546. } else {
  1547. inv = 1.0 / this.direction.y;
  1548. min = (minimum.y - this.origin.y) * inv;
  1549. max = (maximum.y - this.origin.y) * inv;
  1550. if (min > max) {
  1551. temp = min;
  1552. min = max;
  1553. max = temp;
  1554. }
  1555. d = Math.max(min, d);
  1556. maxValue = Math.min(max, maxValue);
  1557. if (d > maxValue) {
  1558. return false;
  1559. }
  1560. }
  1561. if (Math.abs(this.direction.z) < 0.0000001) {
  1562. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1563. return false;
  1564. }
  1565. } else {
  1566. inv = 1.0 / this.direction.z;
  1567. min = (minimum.z - this.origin.z) * inv;
  1568. max = (maximum.z - this.origin.z) * inv;
  1569. if (min > max) {
  1570. temp = min;
  1571. min = max;
  1572. max = temp;
  1573. }
  1574. d = Math.max(min, d);
  1575. maxValue = Math.min(max, maxValue);
  1576. if (d > maxValue) {
  1577. return false;
  1578. }
  1579. }
  1580. return true;
  1581. };
  1582. Ray.prototype.intersectsBox = function (box) {
  1583. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1584. };
  1585. Ray.prototype.intersectsSphere = function (sphere) {
  1586. var x = sphere.center.x - this.origin.x;
  1587. var y = sphere.center.y - this.origin.y;
  1588. var z = sphere.center.z - this.origin.z;
  1589. var pyth = (x * x) + (y * y) + (z * z);
  1590. var rr = sphere.radius * sphere.radius;
  1591. if (pyth <= rr) {
  1592. return true;
  1593. }
  1594. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1595. if (dot < 0.0) {
  1596. return false;
  1597. }
  1598. var temp = pyth - (dot * dot);
  1599. return temp <= rr;
  1600. };
  1601. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1602. if (!this._edge1) {
  1603. this._edge1 = BABYLON.Vector3.Zero();
  1604. this._edge2 = BABYLON.Vector3.Zero();
  1605. this._pvec = BABYLON.Vector3.Zero();
  1606. this._tvec = BABYLON.Vector3.Zero();
  1607. this._qvec = BABYLON.Vector3.Zero();
  1608. }
  1609. vertex1.subtractToRef(vertex0, this._edge1);
  1610. vertex2.subtractToRef(vertex0, this._edge2);
  1611. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1612. var det = Vector3.Dot(this._edge1, this._pvec);
  1613. if (det === 0) {
  1614. return null;
  1615. }
  1616. var invdet = 1 / det;
  1617. this.origin.subtractToRef(vertex0, this._tvec);
  1618. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1619. if (bu < 0 || bu > 1.0) {
  1620. return null;
  1621. }
  1622. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1623. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1624. if (bv < 0 || bu + bv > 1.0) {
  1625. return null;
  1626. }
  1627. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1628. };
  1629. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1630. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1631. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1632. var direction = end.subtract(start);
  1633. direction.normalize();
  1634. return new Ray(start, direction);
  1635. };
  1636. Ray.Transform = function (ray, matrix) {
  1637. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1638. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1639. return new Ray(newOrigin, newDirection);
  1640. };
  1641. return Ray;
  1642. })();
  1643. BABYLON.Ray = Ray;
  1644. (function (Space) {
  1645. Space[Space["LOCAL"] = 0] = "LOCAL";
  1646. Space[Space["WORLD"] = 1] = "WORLD";
  1647. })(BABYLON.Space || (BABYLON.Space = {}));
  1648. var Space = BABYLON.Space;
  1649. var Axis = (function () {
  1650. function Axis() {
  1651. }
  1652. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1653. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1654. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1655. return Axis;
  1656. })();
  1657. BABYLON.Axis = Axis;
  1658. ;
  1659. })(BABYLON || (BABYLON = {}));
  1660. var BABYLON;
  1661. (function (BABYLON) {
  1662. var screenshotCanvas;
  1663. var fpsRange = 60;
  1664. var previousFramesDuration = [];
  1665. var fps = 60;
  1666. var deltaTime = 0;
  1667. var cloneValue = function (source, destinationObject) {
  1668. if (!source)
  1669. return null;
  1670. if (source instanceof BABYLON.Mesh) {
  1671. return null;
  1672. }
  1673. if (source instanceof BABYLON.SubMesh) {
  1674. return source.clone(destinationObject);
  1675. } else if (source.clone) {
  1676. return source.clone();
  1677. }
  1678. return null;
  1679. };
  1680. var Tools = (function () {
  1681. function Tools() {
  1682. }
  1683. Tools.GetFilename = function (path) {
  1684. var index = path.lastIndexOf("/");
  1685. if (index < 0)
  1686. return path;
  1687. return path.substring(index + 1);
  1688. };
  1689. Tools.GetDOMTextContent = function (element) {
  1690. var result = "";
  1691. var child = element.firstChild;
  1692. while (child) {
  1693. if (child.nodeType == 3) {
  1694. result += child.textContent;
  1695. }
  1696. child = child.nextSibling;
  1697. }
  1698. return result;
  1699. };
  1700. Tools.ToDegrees = function (angle) {
  1701. return angle * 180 / Math.PI;
  1702. };
  1703. Tools.ToRadians = function (angle) {
  1704. return angle * Math.PI / 180;
  1705. };
  1706. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1707. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1708. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1709. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1710. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1711. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1712. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1713. }
  1714. return {
  1715. minimum: minimum,
  1716. maximum: maximum
  1717. };
  1718. };
  1719. Tools.ExtractMinAndMax = function (positions, start, count) {
  1720. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1721. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1722. for (var index = start; index < start + count; index++) {
  1723. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1724. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1725. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1726. }
  1727. return {
  1728. minimum: minimum,
  1729. maximum: maximum
  1730. };
  1731. };
  1732. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1733. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1734. return undefined;
  1735. return Array.isArray(obj) ? obj : [obj];
  1736. };
  1737. Tools.GetPointerPrefix = function () {
  1738. var eventPrefix = "pointer";
  1739. if (!navigator.pointerEnabled) {
  1740. eventPrefix = "mouse";
  1741. }
  1742. return eventPrefix;
  1743. };
  1744. Tools.QueueNewFrame = function (func) {
  1745. if (window.requestAnimationFrame)
  1746. window.requestAnimationFrame(func);
  1747. else if (window.msRequestAnimationFrame)
  1748. window.msRequestAnimationFrame(func);
  1749. else if (window.webkitRequestAnimationFrame)
  1750. window.webkitRequestAnimationFrame(func);
  1751. else if (window.mozRequestAnimationFrame)
  1752. window.mozRequestAnimationFrame(func);
  1753. else if (window.oRequestAnimationFrame)
  1754. window.oRequestAnimationFrame(func);
  1755. else {
  1756. window.setTimeout(func, 16);
  1757. }
  1758. };
  1759. Tools.RequestFullscreen = function (element) {
  1760. if (element.requestFullscreen)
  1761. element.requestFullscreen();
  1762. else if (element.msRequestFullscreen)
  1763. element.msRequestFullscreen();
  1764. else if (element.webkitRequestFullscreen)
  1765. element.webkitRequestFullscreen();
  1766. else if (element.mozRequestFullScreen)
  1767. element.mozRequestFullScreen();
  1768. };
  1769. Tools.ExitFullscreen = function () {
  1770. if (document.exitFullscreen) {
  1771. document.exitFullscreen();
  1772. } else if (document.mozCancelFullScreen) {
  1773. document.mozCancelFullScreen();
  1774. } else if (document.webkitCancelFullScreen) {
  1775. document.webkitCancelFullScreen();
  1776. } else if (document.msCancelFullScreen) {
  1777. document.msCancelFullScreen();
  1778. }
  1779. };
  1780. Tools.CleanUrl = function (url) {
  1781. url = url.replace(/#/mg, "%23");
  1782. return url;
  1783. };
  1784. Tools.LoadImage = function (url, onload, onerror, database) {
  1785. url = Tools.CleanUrl(url);
  1786. var img = new Image();
  1787. img.crossOrigin = 'anonymous';
  1788. img.onload = function () {
  1789. onload(img);
  1790. };
  1791. img.onerror = function (err) {
  1792. onerror(img, err);
  1793. };
  1794. var noIndexedDB = function () {
  1795. img.src = url;
  1796. };
  1797. var loadFromIndexedDB = function () {
  1798. database.loadImageFromDB(url, img);
  1799. };
  1800. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1801. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1802. } else {
  1803. if (url.indexOf("file:") === -1) {
  1804. noIndexedDB();
  1805. } else {
  1806. try {
  1807. var textureName = url.substring(5);
  1808. var blobURL;
  1809. try {
  1810. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1811. } catch (ex) {
  1812. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1813. }
  1814. img.src = blobURL;
  1815. } catch (e) {
  1816. Tools.Log("Error while trying to load texture: " + textureName);
  1817. img.src = null;
  1818. }
  1819. }
  1820. }
  1821. return img;
  1822. };
  1823. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1824. url = Tools.CleanUrl(url);
  1825. var noIndexedDB = function () {
  1826. var request = new XMLHttpRequest();
  1827. var loadUrl = Tools.BaseUrl + url;
  1828. request.open('GET', loadUrl, true);
  1829. if (useArrayBuffer) {
  1830. request.responseType = "arraybuffer";
  1831. }
  1832. request.onprogress = progressCallBack;
  1833. request.onreadystatechange = function () {
  1834. if (request.readyState == 4) {
  1835. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1836. callback(!useArrayBuffer ? request.responseText : request.response);
  1837. } else {
  1838. if (onError) {
  1839. onError();
  1840. } else {
  1841. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1842. }
  1843. }
  1844. }
  1845. };
  1846. request.send(null);
  1847. };
  1848. var loadFromIndexedDB = function () {
  1849. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1850. };
  1851. if (url.indexOf("file:") !== -1) {
  1852. var fileName = url.substring(5);
  1853. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1854. } else {
  1855. if (database && database.enableSceneOffline) {
  1856. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1857. } else {
  1858. noIndexedDB();
  1859. }
  1860. }
  1861. };
  1862. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1863. var reader = new FileReader();
  1864. reader.onload = function (e) {
  1865. callback(e.target.result);
  1866. };
  1867. reader.onprogress = progressCallBack;
  1868. if (!useArrayBuffer) {
  1869. reader.readAsText(fileToLoad);
  1870. } else {
  1871. reader.readAsArrayBuffer(fileToLoad);
  1872. }
  1873. };
  1874. Tools.CheckExtends = function (v, min, max) {
  1875. if (v.x < min.x)
  1876. min.x = v.x;
  1877. if (v.y < min.y)
  1878. min.y = v.y;
  1879. if (v.z < min.z)
  1880. min.z = v.z;
  1881. if (v.x > max.x)
  1882. max.x = v.x;
  1883. if (v.y > max.y)
  1884. max.y = v.y;
  1885. if (v.z > max.z)
  1886. max.z = v.z;
  1887. };
  1888. Tools.WithinEpsilon = function (a, b) {
  1889. var num = a - b;
  1890. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1891. };
  1892. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1893. for (var prop in source) {
  1894. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1895. continue;
  1896. }
  1897. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1898. continue;
  1899. }
  1900. var sourceValue = source[prop];
  1901. var typeOfSourceValue = typeof sourceValue;
  1902. if (typeOfSourceValue == "function") {
  1903. continue;
  1904. }
  1905. if (typeOfSourceValue == "object") {
  1906. if (sourceValue instanceof Array) {
  1907. destination[prop] = [];
  1908. if (sourceValue.length > 0) {
  1909. if (typeof sourceValue[0] == "object") {
  1910. for (var index = 0; index < sourceValue.length; index++) {
  1911. var clonedValue = cloneValue(sourceValue[index], destination);
  1912. if (destination[prop].indexOf(clonedValue) === -1) {
  1913. destination[prop].push(clonedValue);
  1914. }
  1915. }
  1916. } else {
  1917. destination[prop] = sourceValue.slice(0);
  1918. }
  1919. }
  1920. } else {
  1921. destination[prop] = cloneValue(sourceValue, destination);
  1922. }
  1923. } else {
  1924. destination[prop] = sourceValue;
  1925. }
  1926. }
  1927. };
  1928. Tools.IsEmpty = function (obj) {
  1929. for (var i in obj) {
  1930. return false;
  1931. }
  1932. return true;
  1933. };
  1934. Tools.RegisterTopRootEvents = function (events) {
  1935. for (var index = 0; index < events.length; index++) {
  1936. var event = events[index];
  1937. window.addEventListener(event.name, event.handler, false);
  1938. try {
  1939. if (window.parent) {
  1940. window.parent.addEventListener(event.name, event.handler, false);
  1941. }
  1942. } catch (e) {
  1943. }
  1944. }
  1945. };
  1946. Tools.UnregisterTopRootEvents = function (events) {
  1947. for (var index = 0; index < events.length; index++) {
  1948. var event = events[index];
  1949. window.removeEventListener(event.name, event.handler);
  1950. try {
  1951. if (window.parent) {
  1952. window.parent.removeEventListener(event.name, event.handler);
  1953. }
  1954. } catch (e) {
  1955. }
  1956. }
  1957. };
  1958. Tools.GetFps = function () {
  1959. return fps;
  1960. };
  1961. Tools.GetDeltaTime = function () {
  1962. return deltaTime;
  1963. };
  1964. Tools._MeasureFps = function () {
  1965. previousFramesDuration.push((new Date).getTime());
  1966. var length = previousFramesDuration.length;
  1967. if (length >= 2) {
  1968. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  1969. }
  1970. if (length >= fpsRange) {
  1971. if (length > fpsRange) {
  1972. previousFramesDuration.splice(0, 1);
  1973. length = previousFramesDuration.length;
  1974. }
  1975. var sum = 0;
  1976. for (var id = 0; id < length - 1; id++) {
  1977. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  1978. }
  1979. fps = 1000.0 / (sum / (length - 1));
  1980. }
  1981. };
  1982. Tools.CreateScreenshot = function (engine, camera, size) {
  1983. var width;
  1984. var height;
  1985. var scene = camera.getScene();
  1986. var previousCamera = null;
  1987. if (scene.activeCamera !== camera) {
  1988. previousCamera = scene.activeCamera;
  1989. scene.activeCamera = camera;
  1990. }
  1991. if (size.precision) {
  1992. width = Math.round(engine.getRenderWidth() * size.precision);
  1993. height = Math.round(width / engine.getAspectRatio(camera));
  1994. size = { width: width, height: height };
  1995. } else if (size.width && size.height) {
  1996. width = size.width;
  1997. height = size.height;
  1998. } else if (size.width && !size.height) {
  1999. width = size.width;
  2000. height = Math.round(width / engine.getAspectRatio(camera));
  2001. size = { width: width, height: height };
  2002. } else if (size.height && !size.width) {
  2003. height = size.height;
  2004. width = Math.round(height * engine.getAspectRatio(camera));
  2005. size = { width: width, height: height };
  2006. } else if (!isNaN(size)) {
  2007. height = size;
  2008. width = size;
  2009. } else {
  2010. Tools.Error("Invalid 'size' parameter !");
  2011. return;
  2012. }
  2013. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2014. texture.renderList = engine.scenes[0].meshes;
  2015. texture.onAfterRender = function () {
  2016. var numberOfChannelsByLine = width * 4;
  2017. var halfHeight = height / 2;
  2018. var data = engine.readPixels(0, 0, width, height);
  2019. for (var i = 0; i < halfHeight; i++) {
  2020. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2021. var currentCell = j + i * numberOfChannelsByLine;
  2022. var targetLine = height - i - 1;
  2023. var targetCell = j + targetLine * numberOfChannelsByLine;
  2024. var temp = data[currentCell];
  2025. data[currentCell] = data[targetCell];
  2026. data[targetCell] = temp;
  2027. }
  2028. }
  2029. if (!screenshotCanvas) {
  2030. screenshotCanvas = document.createElement('canvas');
  2031. }
  2032. screenshotCanvas.width = width;
  2033. screenshotCanvas.height = height;
  2034. var context = screenshotCanvas.getContext('2d');
  2035. var imageData = context.createImageData(width, height);
  2036. imageData.data.set(data);
  2037. context.putImageData(imageData, 0, 0);
  2038. var base64Image = screenshotCanvas.toDataURL();
  2039. if (("download" in document.createElement("a"))) {
  2040. var a = window.document.createElement("a");
  2041. a.href = base64Image;
  2042. var date = new Date();
  2043. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2044. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2045. window.document.body.appendChild(a);
  2046. a.addEventListener("click", function () {
  2047. a.parentElement.removeChild(a);
  2048. });
  2049. a.click();
  2050. } else {
  2051. var newWindow = window.open("");
  2052. var img = newWindow.document.createElement("img");
  2053. img.src = base64Image;
  2054. newWindow.document.body.appendChild(img);
  2055. }
  2056. };
  2057. texture.render(true);
  2058. texture.dispose();
  2059. if (previousCamera) {
  2060. scene.activeCamera = previousCamera;
  2061. }
  2062. };
  2063. Tools.ValidateXHRData = function (xhr, dataType) {
  2064. if (typeof dataType === "undefined") { dataType = 7; }
  2065. try {
  2066. if (dataType & 1) {
  2067. if (xhr.responseText && xhr.responseText.length > 0) {
  2068. return true;
  2069. } else if (dataType === 1) {
  2070. return false;
  2071. }
  2072. }
  2073. if (dataType & 2) {
  2074. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2075. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2076. return true;
  2077. } else if (dataType === 2) {
  2078. return false;
  2079. }
  2080. }
  2081. if (dataType & 4) {
  2082. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2083. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2084. return true;
  2085. } else {
  2086. return false;
  2087. }
  2088. }
  2089. } catch (e) {
  2090. }
  2091. return false;
  2092. };
  2093. Object.defineProperty(Tools, "NoneLogLevel", {
  2094. get: function () {
  2095. return Tools._NoneLogLevel;
  2096. },
  2097. enumerable: true,
  2098. configurable: true
  2099. });
  2100. Object.defineProperty(Tools, "MessageLogLevel", {
  2101. get: function () {
  2102. return Tools._MessageLogLevel;
  2103. },
  2104. enumerable: true,
  2105. configurable: true
  2106. });
  2107. Object.defineProperty(Tools, "WarningLogLevel", {
  2108. get: function () {
  2109. return Tools._WarningLogLevel;
  2110. },
  2111. enumerable: true,
  2112. configurable: true
  2113. });
  2114. Object.defineProperty(Tools, "ErrorLogLevel", {
  2115. get: function () {
  2116. return Tools._ErrorLogLevel;
  2117. },
  2118. enumerable: true,
  2119. configurable: true
  2120. });
  2121. Object.defineProperty(Tools, "AllLogLevel", {
  2122. get: function () {
  2123. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2124. },
  2125. enumerable: true,
  2126. configurable: true
  2127. });
  2128. Tools._FormatMessage = function (message) {
  2129. var padStr = function (i) {
  2130. return (i < 10) ? "0" + i : "" + i;
  2131. };
  2132. var date = new Date();
  2133. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2134. };
  2135. Tools._LogDisabled = function (message) {
  2136. };
  2137. Tools._LogEnabled = function (message) {
  2138. console.log(Tools._FormatMessage(message));
  2139. };
  2140. Tools._WarnDisabled = function (message) {
  2141. };
  2142. Tools._WarnEnabled = function (message) {
  2143. console.warn(Tools._FormatMessage(message));
  2144. };
  2145. Tools._ErrorDisabled = function (message) {
  2146. };
  2147. Tools._ErrorEnabled = function (message) {
  2148. console.error(Tools._FormatMessage(message));
  2149. };
  2150. Object.defineProperty(Tools, "LogLevels", {
  2151. set: function (level) {
  2152. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2153. Tools.Log = Tools._LogEnabled;
  2154. } else {
  2155. Tools.Log = Tools._LogDisabled;
  2156. }
  2157. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2158. Tools.Warn = Tools._WarnEnabled;
  2159. } else {
  2160. Tools.Warn = Tools._WarnDisabled;
  2161. }
  2162. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2163. Tools.Error = Tools._ErrorEnabled;
  2164. } else {
  2165. Tools.Error = Tools._ErrorDisabled;
  2166. }
  2167. },
  2168. enumerable: true,
  2169. configurable: true
  2170. });
  2171. Tools.BaseUrl = "";
  2172. Tools._NoneLogLevel = 0;
  2173. Tools._MessageLogLevel = 1;
  2174. Tools._WarningLogLevel = 2;
  2175. Tools._ErrorLogLevel = 4;
  2176. Tools.Log = Tools._LogEnabled;
  2177. Tools.Warn = Tools._WarnEnabled;
  2178. Tools.Error = Tools._ErrorEnabled;
  2179. return Tools;
  2180. })();
  2181. BABYLON.Tools = Tools;
  2182. })(BABYLON || (BABYLON = {}));
  2183. var BABYLON;
  2184. (function (BABYLON) {
  2185. var _DepthCullingState = (function () {
  2186. function _DepthCullingState() {
  2187. this._isDepthTestDirty = false;
  2188. this._isDepthMaskDirty = false;
  2189. this._isDepthFuncDirty = false;
  2190. this._isCullFaceDirty = false;
  2191. this._isCullDirty = false;
  2192. }
  2193. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2194. get: function () {
  2195. return this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2196. },
  2197. enumerable: true,
  2198. configurable: true
  2199. });
  2200. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2201. get: function () {
  2202. return this._cullFace;
  2203. },
  2204. set: function (value) {
  2205. if (this._cullFace === value) {
  2206. return;
  2207. }
  2208. this._cullFace = value;
  2209. this._isCullFaceDirty = true;
  2210. },
  2211. enumerable: true,
  2212. configurable: true
  2213. });
  2214. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2215. get: function () {
  2216. return this._cull;
  2217. },
  2218. set: function (value) {
  2219. if (this._cull === value) {
  2220. return;
  2221. }
  2222. this._cull = value;
  2223. this._isCullDirty = true;
  2224. },
  2225. enumerable: true,
  2226. configurable: true
  2227. });
  2228. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2229. get: function () {
  2230. return this._depthFunc;
  2231. },
  2232. set: function (value) {
  2233. if (this._depthFunc === value) {
  2234. return;
  2235. }
  2236. this._depthFunc = value;
  2237. this._isDepthFuncDirty = true;
  2238. },
  2239. enumerable: true,
  2240. configurable: true
  2241. });
  2242. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2243. get: function () {
  2244. return this._depthMask;
  2245. },
  2246. set: function (value) {
  2247. if (this._depthMask === value) {
  2248. return;
  2249. }
  2250. this._depthMask = value;
  2251. this._isDepthMaskDirty = true;
  2252. },
  2253. enumerable: true,
  2254. configurable: true
  2255. });
  2256. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2257. get: function () {
  2258. return this._depthTest;
  2259. },
  2260. set: function (value) {
  2261. if (this._depthTest === value) {
  2262. return;
  2263. }
  2264. this._depthTest = value;
  2265. this._isDepthTestDirty = true;
  2266. },
  2267. enumerable: true,
  2268. configurable: true
  2269. });
  2270. _DepthCullingState.prototype.reset = function () {
  2271. this._depthMask = true;
  2272. this._depthTest = true;
  2273. this._depthFunc = null;
  2274. this._cull = null;
  2275. this._cullFace = null;
  2276. this._isDepthTestDirty = true;
  2277. this._isDepthMaskDirty = true;
  2278. this._isDepthFuncDirty = false;
  2279. this._isCullFaceDirty = false;
  2280. this._isCullDirty = false;
  2281. };
  2282. _DepthCullingState.prototype.apply = function (gl) {
  2283. if (!this.isDirty) {
  2284. return;
  2285. }
  2286. if (this._isCullDirty) {
  2287. if (this.cull === true) {
  2288. gl.enable(gl.CULL_FACE);
  2289. } else if (this.cull === false) {
  2290. gl.disable(gl.CULL_FACE);
  2291. }
  2292. this._isCullDirty = false;
  2293. }
  2294. if (this._isCullFaceDirty) {
  2295. gl.cullFace(this.cullFace);
  2296. this._isCullFaceDirty = false;
  2297. }
  2298. if (this._isDepthMaskDirty) {
  2299. gl.depthMask(this.depthMask);
  2300. this._isDepthMaskDirty = false;
  2301. }
  2302. if (this._isDepthTestDirty) {
  2303. if (this.depthTest === true) {
  2304. gl.enable(gl.DEPTH_TEST);
  2305. } else if (this.depthTest === false) {
  2306. gl.disable(gl.DEPTH_TEST);
  2307. }
  2308. this._isDepthTestDirty = false;
  2309. }
  2310. if (this._isDepthFuncDirty) {
  2311. gl.depthFunc(this.depthFunc);
  2312. this._isDepthFuncDirty = false;
  2313. }
  2314. };
  2315. return _DepthCullingState;
  2316. })();
  2317. BABYLON._DepthCullingState = _DepthCullingState;
  2318. var _AlphaState = (function () {
  2319. function _AlphaState() {
  2320. this._isAlphaBlendDirty = false;
  2321. this._isBlendFunctionParametersDirty = false;
  2322. this._alphaBlend = false;
  2323. this._blendFunctionParameters = new Array(4);
  2324. }
  2325. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2326. get: function () {
  2327. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2328. },
  2329. enumerable: true,
  2330. configurable: true
  2331. });
  2332. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2333. get: function () {
  2334. return this._alphaBlend;
  2335. },
  2336. set: function (value) {
  2337. if (this._alphaBlend === value) {
  2338. return;
  2339. }
  2340. this._alphaBlend = value;
  2341. this._isAlphaBlendDirty = true;
  2342. },
  2343. enumerable: true,
  2344. configurable: true
  2345. });
  2346. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2347. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2348. return;
  2349. }
  2350. this._blendFunctionParameters[0] = value0;
  2351. this._blendFunctionParameters[1] = value1;
  2352. this._blendFunctionParameters[2] = value2;
  2353. this._blendFunctionParameters[3] = value3;
  2354. this._isBlendFunctionParametersDirty = true;
  2355. };
  2356. _AlphaState.prototype.reset = function () {
  2357. this._alphaBlend = false;
  2358. this._blendFunctionParameters[0] = null;
  2359. this._blendFunctionParameters[1] = null;
  2360. this._blendFunctionParameters[2] = null;
  2361. this._blendFunctionParameters[3] = null;
  2362. this._isAlphaBlendDirty = true;
  2363. this._isBlendFunctionParametersDirty = false;
  2364. };
  2365. _AlphaState.prototype.apply = function (gl) {
  2366. if (!this.isDirty) {
  2367. return;
  2368. }
  2369. if (this._isAlphaBlendDirty) {
  2370. if (this._alphaBlend === true) {
  2371. gl.enable(gl.BLEND);
  2372. } else if (this._alphaBlend === false) {
  2373. gl.disable(gl.BLEND);
  2374. }
  2375. this._isAlphaBlendDirty = false;
  2376. }
  2377. if (this._isBlendFunctionParametersDirty) {
  2378. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2379. this._isBlendFunctionParametersDirty = false;
  2380. }
  2381. };
  2382. return _AlphaState;
  2383. })();
  2384. BABYLON._AlphaState = _AlphaState;
  2385. var compileShader = function (gl, source, type, defines) {
  2386. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2387. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2388. gl.compileShader(shader);
  2389. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2390. throw new Error(gl.getShaderInfoLog(shader));
  2391. }
  2392. return shader;
  2393. };
  2394. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2395. var magFilter = gl.NEAREST;
  2396. var minFilter = gl.NEAREST;
  2397. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2398. magFilter = gl.LINEAR;
  2399. if (generateMipMaps) {
  2400. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2401. } else {
  2402. minFilter = gl.LINEAR;
  2403. }
  2404. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2405. magFilter = gl.LINEAR;
  2406. if (generateMipMaps) {
  2407. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2408. } else {
  2409. minFilter = gl.LINEAR;
  2410. }
  2411. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2412. magFilter = gl.NEAREST;
  2413. if (generateMipMaps) {
  2414. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2415. } else {
  2416. minFilter = gl.NEAREST;
  2417. }
  2418. }
  2419. return {
  2420. min: minFilter,
  2421. mag: magFilter
  2422. };
  2423. };
  2424. var getExponantOfTwo = function (value, max) {
  2425. var count = 1;
  2426. do {
  2427. count *= 2;
  2428. } while(count < value);
  2429. if (count > max)
  2430. count = max;
  2431. return count;
  2432. };
  2433. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2434. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2435. var engine = scene.getEngine();
  2436. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2437. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2438. gl.bindTexture(gl.TEXTURE_2D, texture);
  2439. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2440. processFunction(potWidth, potHeight);
  2441. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2442. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2443. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2444. if (!noMipmap && !isCompressed) {
  2445. gl.generateMipmap(gl.TEXTURE_2D);
  2446. }
  2447. gl.bindTexture(gl.TEXTURE_2D, null);
  2448. engine._activeTexturesCache = [];
  2449. texture._baseWidth = width;
  2450. texture._baseHeight = height;
  2451. texture._width = potWidth;
  2452. texture._height = potHeight;
  2453. texture.isReady = true;
  2454. scene._removePendingData(texture);
  2455. };
  2456. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2457. var img;
  2458. var onload = function () {
  2459. loadedImages.push(img);
  2460. scene._removePendingData(img);
  2461. if (index != extensions.length - 1) {
  2462. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2463. } else {
  2464. onfinish(loadedImages);
  2465. }
  2466. };
  2467. var onerror = function () {
  2468. scene._removePendingData(img);
  2469. };
  2470. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2471. scene._addPendingData(img);
  2472. };
  2473. var EngineCapabilities = (function () {
  2474. function EngineCapabilities() {
  2475. }
  2476. return EngineCapabilities;
  2477. })();
  2478. BABYLON.EngineCapabilities = EngineCapabilities;
  2479. var Engine = (function () {
  2480. function Engine(canvas, antialias, options) {
  2481. var _this = this;
  2482. this.isFullscreen = false;
  2483. this.isPointerLock = false;
  2484. this.forceWireframe = false;
  2485. this.cullBackFaces = true;
  2486. this.renderEvenInBackground = true;
  2487. this.scenes = new Array();
  2488. this._windowIsBackground = false;
  2489. this._runningLoop = false;
  2490. this._loadingDivBackgroundColor = "black";
  2491. this._depthCullingState = new _DepthCullingState();
  2492. this._alphaState = new _AlphaState();
  2493. this._loadedTexturesCache = new Array();
  2494. this._activeTexturesCache = new Array();
  2495. this._compiledEffects = {};
  2496. this._renderingCanvas = canvas;
  2497. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2498. options = options || {};
  2499. options.antialias = antialias;
  2500. try {
  2501. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2502. } catch (e) {
  2503. throw new Error("WebGL not supported");
  2504. }
  2505. if (!this._gl) {
  2506. throw new Error("WebGL not supported");
  2507. }
  2508. this._onBlur = function () {
  2509. _this._windowIsBackground = true;
  2510. };
  2511. this._onFocus = function () {
  2512. _this._windowIsBackground = false;
  2513. };
  2514. window.addEventListener("blur", this._onBlur);
  2515. window.addEventListener("focus", this._onFocus);
  2516. this._workingCanvas = document.createElement("canvas");
  2517. this._workingContext = this._workingCanvas.getContext("2d");
  2518. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2519. this.resize();
  2520. this._caps = new EngineCapabilities();
  2521. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2522. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2523. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2524. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2525. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2526. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2527. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2528. 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');
  2529. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2530. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2531. this.setDepthBuffer(true);
  2532. this.setDepthFunctionToLessOrEqual();
  2533. this.setDepthWrite(true);
  2534. this._onFullscreenChange = function () {
  2535. if (document.fullscreen !== undefined) {
  2536. _this.isFullscreen = document.fullscreen;
  2537. } else if (document.mozFullScreen !== undefined) {
  2538. _this.isFullscreen = document.mozFullScreen;
  2539. } else if (document.webkitIsFullScreen !== undefined) {
  2540. _this.isFullscreen = document.webkitIsFullScreen;
  2541. } else if (document.msIsFullScreen !== undefined) {
  2542. _this.isFullscreen = document.msIsFullScreen;
  2543. }
  2544. if (_this.isFullscreen && _this._pointerLockRequested) {
  2545. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2546. if (canvas.requestPointerLock) {
  2547. canvas.requestPointerLock();
  2548. }
  2549. }
  2550. };
  2551. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2552. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2553. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2554. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2555. this._onPointerLockChange = function () {
  2556. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2557. };
  2558. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2559. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2560. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2561. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2562. }
  2563. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2564. get: function () {
  2565. return Engine._ALPHA_DISABLE;
  2566. },
  2567. enumerable: true,
  2568. configurable: true
  2569. });
  2570. Object.defineProperty(Engine, "ALPHA_ADD", {
  2571. get: function () {
  2572. return Engine._ALPHA_ADD;
  2573. },
  2574. enumerable: true,
  2575. configurable: true
  2576. });
  2577. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2578. get: function () {
  2579. return Engine._ALPHA_COMBINE;
  2580. },
  2581. enumerable: true,
  2582. configurable: true
  2583. });
  2584. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2585. get: function () {
  2586. return Engine._DELAYLOADSTATE_NONE;
  2587. },
  2588. enumerable: true,
  2589. configurable: true
  2590. });
  2591. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2592. get: function () {
  2593. return Engine._DELAYLOADSTATE_LOADED;
  2594. },
  2595. enumerable: true,
  2596. configurable: true
  2597. });
  2598. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2599. get: function () {
  2600. return Engine._DELAYLOADSTATE_LOADING;
  2601. },
  2602. enumerable: true,
  2603. configurable: true
  2604. });
  2605. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2606. get: function () {
  2607. return Engine._DELAYLOADSTATE_NOTLOADED;
  2608. },
  2609. enumerable: true,
  2610. configurable: true
  2611. });
  2612. Object.defineProperty(Engine, "Version", {
  2613. get: function () {
  2614. return "1.14.0";
  2615. },
  2616. enumerable: true,
  2617. configurable: true
  2618. });
  2619. Engine.prototype.getAspectRatio = function (camera) {
  2620. var viewport = camera.viewport;
  2621. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2622. };
  2623. Engine.prototype.getRenderWidth = function () {
  2624. if (this._currentRenderTarget) {
  2625. return this._currentRenderTarget._width;
  2626. }
  2627. return this._renderingCanvas.width;
  2628. };
  2629. Engine.prototype.getRenderHeight = function () {
  2630. if (this._currentRenderTarget) {
  2631. return this._currentRenderTarget._height;
  2632. }
  2633. return this._renderingCanvas.height;
  2634. };
  2635. Engine.prototype.getRenderingCanvas = function () {
  2636. return this._renderingCanvas;
  2637. };
  2638. Engine.prototype.getRenderingCanvasClientRect = function () {
  2639. return this._renderingCanvas.getBoundingClientRect();
  2640. };
  2641. Engine.prototype.setHardwareScalingLevel = function (level) {
  2642. this._hardwareScalingLevel = level;
  2643. this.resize();
  2644. };
  2645. Engine.prototype.getHardwareScalingLevel = function () {
  2646. return this._hardwareScalingLevel;
  2647. };
  2648. Engine.prototype.getLoadedTexturesCache = function () {
  2649. return this._loadedTexturesCache;
  2650. };
  2651. Engine.prototype.getCaps = function () {
  2652. return this._caps;
  2653. };
  2654. Engine.prototype.setDepthFunctionToGreater = function () {
  2655. this._depthCullingState.depthFunc = this._gl.GREATER;
  2656. };
  2657. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2658. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2659. };
  2660. Engine.prototype.setDepthFunctionToLess = function () {
  2661. this._depthCullingState.depthFunc = this._gl.LESS;
  2662. };
  2663. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2664. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2665. };
  2666. Engine.prototype.stopRenderLoop = function () {
  2667. this._renderFunction = null;
  2668. this._runningLoop = false;
  2669. };
  2670. Engine.prototype._renderLoop = function () {
  2671. var _this = this;
  2672. var shouldRender = true;
  2673. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2674. shouldRender = false;
  2675. }
  2676. if (shouldRender) {
  2677. this.beginFrame();
  2678. if (this._renderFunction) {
  2679. this._renderFunction();
  2680. }
  2681. this.endFrame();
  2682. }
  2683. if (this._runningLoop) {
  2684. BABYLON.Tools.QueueNewFrame(function () {
  2685. _this._renderLoop();
  2686. });
  2687. }
  2688. };
  2689. Engine.prototype.runRenderLoop = function (renderFunction) {
  2690. var _this = this;
  2691. this._runningLoop = true;
  2692. this._renderFunction = renderFunction;
  2693. BABYLON.Tools.QueueNewFrame(function () {
  2694. _this._renderLoop();
  2695. });
  2696. };
  2697. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2698. if (this.isFullscreen) {
  2699. BABYLON.Tools.ExitFullscreen();
  2700. } else {
  2701. this._pointerLockRequested = requestPointerLock;
  2702. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2703. }
  2704. };
  2705. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2706. this.applyStates();
  2707. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2708. if (this._depthCullingState.depthMask) {
  2709. this._gl.clearDepth(1.0);
  2710. }
  2711. var mode = 0;
  2712. if (backBuffer)
  2713. mode |= this._gl.COLOR_BUFFER_BIT;
  2714. if (depthStencil && this._depthCullingState.depthMask)
  2715. mode |= this._gl.DEPTH_BUFFER_BIT;
  2716. this._gl.clear(mode);
  2717. };
  2718. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2719. var width = requiredWidth || this._renderingCanvas.width;
  2720. var height = requiredHeight || this._renderingCanvas.height;
  2721. var x = viewport.x || 0;
  2722. var y = viewport.y || 0;
  2723. this._cachedViewport = viewport;
  2724. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2725. };
  2726. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2727. this._cachedViewport = null;
  2728. this._gl.viewport(x, y, width, height);
  2729. };
  2730. Engine.prototype.beginFrame = function () {
  2731. BABYLON.Tools._MeasureFps();
  2732. };
  2733. Engine.prototype.endFrame = function () {
  2734. this.flushFramebuffer();
  2735. };
  2736. Engine.prototype.resize = function () {
  2737. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2738. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2739. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2740. };
  2741. Engine.prototype.bindFramebuffer = function (texture) {
  2742. this._currentRenderTarget = texture;
  2743. var gl = this._gl;
  2744. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2745. this._gl.viewport(0, 0, texture._width, texture._height);
  2746. this.wipeCaches();
  2747. };
  2748. Engine.prototype.unBindFramebuffer = function (texture) {
  2749. this._currentRenderTarget = null;
  2750. if (texture.generateMipMaps) {
  2751. var gl = this._gl;
  2752. gl.bindTexture(gl.TEXTURE_2D, texture);
  2753. gl.generateMipmap(gl.TEXTURE_2D);
  2754. gl.bindTexture(gl.TEXTURE_2D, null);
  2755. }
  2756. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2757. };
  2758. Engine.prototype.flushFramebuffer = function () {
  2759. this._gl.flush();
  2760. };
  2761. Engine.prototype.restoreDefaultFramebuffer = function () {
  2762. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2763. this.setViewport(this._cachedViewport);
  2764. this.wipeCaches();
  2765. };
  2766. Engine.prototype._resetVertexBufferBinding = function () {
  2767. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2768. this._cachedVertexBuffers = null;
  2769. };
  2770. Engine.prototype.createVertexBuffer = function (vertices) {
  2771. var vbo = this._gl.createBuffer();
  2772. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2773. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2774. this._resetVertexBufferBinding();
  2775. vbo.references = 1;
  2776. return vbo;
  2777. };
  2778. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2779. var vbo = this._gl.createBuffer();
  2780. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2781. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2782. this._resetVertexBufferBinding();
  2783. vbo.references = 1;
  2784. return vbo;
  2785. };
  2786. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2787. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2788. if (vertices instanceof Float32Array) {
  2789. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2790. } else {
  2791. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2792. }
  2793. this._resetVertexBufferBinding();
  2794. };
  2795. Engine.prototype._resetIndexBufferBinding = function () {
  2796. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2797. this._cachedIndexBuffer = null;
  2798. };
  2799. Engine.prototype.createIndexBuffer = function (indices) {
  2800. var vbo = this._gl.createBuffer();
  2801. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2802. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2803. this._resetIndexBufferBinding();
  2804. vbo.references = 1;
  2805. return vbo;
  2806. };
  2807. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2808. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2809. this._cachedVertexBuffers = vertexBuffer;
  2810. this._cachedEffectForVertexBuffers = effect;
  2811. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2812. var offset = 0;
  2813. for (var index = 0; index < vertexDeclaration.length; index++) {
  2814. var order = effect.getAttributeLocation(index);
  2815. if (order >= 0) {
  2816. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2817. }
  2818. offset += vertexDeclaration[index] * 4;
  2819. }
  2820. }
  2821. if (this._cachedIndexBuffer !== indexBuffer) {
  2822. this._cachedIndexBuffer = indexBuffer;
  2823. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2824. }
  2825. };
  2826. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2827. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2828. this._cachedVertexBuffers = vertexBuffers;
  2829. this._cachedEffectForVertexBuffers = effect;
  2830. var attributes = effect.getAttributesNames();
  2831. for (var index = 0; index < attributes.length; index++) {
  2832. var order = effect.getAttributeLocation(index);
  2833. if (order >= 0) {
  2834. var vertexBuffer = vertexBuffers[attributes[index]];
  2835. if (!vertexBuffer) {
  2836. continue;
  2837. }
  2838. var stride = vertexBuffer.getStrideSize();
  2839. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2840. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2841. }
  2842. }
  2843. }
  2844. if (this._cachedIndexBuffer !== indexBuffer) {
  2845. this._cachedIndexBuffer = indexBuffer;
  2846. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2847. }
  2848. };
  2849. Engine.prototype._releaseBuffer = function (buffer) {
  2850. buffer.references--;
  2851. if (buffer.references === 0) {
  2852. this._gl.deleteBuffer(buffer);
  2853. return true;
  2854. }
  2855. return false;
  2856. };
  2857. Engine.prototype.createInstancesBuffer = function (capacity) {
  2858. var buffer = this._gl.createBuffer();
  2859. buffer.capacity = capacity;
  2860. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2861. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2862. return buffer;
  2863. };
  2864. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2865. this._gl.deleteBuffer(buffer);
  2866. };
  2867. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2868. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2869. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2870. for (var index = 0; index < 4; index++) {
  2871. var offsetLocation = offsetLocations[index];
  2872. this._gl.enableVertexAttribArray(offsetLocation);
  2873. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2874. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2875. }
  2876. };
  2877. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2878. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2879. for (var index = 0; index < 4; index++) {
  2880. var offsetLocation = offsetLocations[index];
  2881. this._gl.disableVertexAttribArray(offsetLocation);
  2882. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2883. }
  2884. };
  2885. Engine.prototype.applyStates = function () {
  2886. this._depthCullingState.apply(this._gl);
  2887. this._alphaState.apply(this._gl);
  2888. };
  2889. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2890. this.applyStates();
  2891. if (instancesCount) {
  2892. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2893. return;
  2894. }
  2895. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2896. };
  2897. Engine.prototype._releaseEffect = function (effect) {
  2898. if (this._compiledEffects[effect._key]) {
  2899. delete this._compiledEffects[effect._key];
  2900. if (effect.getProgram()) {
  2901. this._gl.deleteProgram(effect.getProgram());
  2902. }
  2903. }
  2904. };
  2905. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2906. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2907. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2908. var name = vertex + "+" + fragment + "@" + defines;
  2909. if (this._compiledEffects[name]) {
  2910. return this._compiledEffects[name];
  2911. }
  2912. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2913. effect._key = name;
  2914. this._compiledEffects[name] = effect;
  2915. return effect;
  2916. };
  2917. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2918. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2919. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2920. var shaderProgram = this._gl.createProgram();
  2921. this._gl.attachShader(shaderProgram, vertexShader);
  2922. this._gl.attachShader(shaderProgram, fragmentShader);
  2923. this._gl.linkProgram(shaderProgram);
  2924. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2925. if (!linked) {
  2926. var error = this._gl.getProgramInfoLog(shaderProgram);
  2927. if (error) {
  2928. throw new Error(error);
  2929. }
  2930. }
  2931. this._gl.deleteShader(vertexShader);
  2932. this._gl.deleteShader(fragmentShader);
  2933. return shaderProgram;
  2934. };
  2935. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2936. var results = [];
  2937. for (var index = 0; index < uniformsNames.length; index++) {
  2938. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2939. }
  2940. return results;
  2941. };
  2942. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  2943. var results = [];
  2944. for (var index = 0; index < attributesNames.length; index++) {
  2945. try {
  2946. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2947. } catch (e) {
  2948. results.push(-1);
  2949. }
  2950. }
  2951. return results;
  2952. };
  2953. Engine.prototype.enableEffect = function (effect) {
  2954. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  2955. return;
  2956. }
  2957. this._vertexAttribArrays = this._vertexAttribArrays || [];
  2958. this._gl.useProgram(effect.getProgram());
  2959. for (var i in this._vertexAttribArrays) {
  2960. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  2961. continue;
  2962. }
  2963. this._vertexAttribArrays[i] = false;
  2964. this._gl.disableVertexAttribArray(i);
  2965. }
  2966. var attributesCount = effect.getAttributesCount();
  2967. for (var index = 0; index < attributesCount; index++) {
  2968. var order = effect.getAttributeLocation(index);
  2969. if (order >= 0) {
  2970. this._vertexAttribArrays[order] = true;
  2971. this._gl.enableVertexAttribArray(order);
  2972. }
  2973. }
  2974. this._currentEffect = effect;
  2975. };
  2976. Engine.prototype.setArray = function (uniform, array) {
  2977. if (!uniform)
  2978. return;
  2979. this._gl.uniform1fv(uniform, array);
  2980. };
  2981. Engine.prototype.setMatrices = function (uniform, matrices) {
  2982. if (!uniform)
  2983. return;
  2984. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2985. };
  2986. Engine.prototype.setMatrix = function (uniform, matrix) {
  2987. if (!uniform)
  2988. return;
  2989. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  2990. };
  2991. Engine.prototype.setFloat = function (uniform, value) {
  2992. if (!uniform)
  2993. return;
  2994. this._gl.uniform1f(uniform, value);
  2995. };
  2996. Engine.prototype.setFloat2 = function (uniform, x, y) {
  2997. if (!uniform)
  2998. return;
  2999. this._gl.uniform2f(uniform, x, y);
  3000. };
  3001. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3002. if (!uniform)
  3003. return;
  3004. this._gl.uniform3f(uniform, x, y, z);
  3005. };
  3006. Engine.prototype.setBool = function (uniform, bool) {
  3007. if (!uniform)
  3008. return;
  3009. this._gl.uniform1i(uniform, bool);
  3010. };
  3011. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3012. if (!uniform)
  3013. return;
  3014. this._gl.uniform4f(uniform, x, y, z, w);
  3015. };
  3016. Engine.prototype.setColor3 = function (uniform, color3) {
  3017. if (!uniform)
  3018. return;
  3019. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3020. };
  3021. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3022. if (!uniform)
  3023. return;
  3024. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3025. };
  3026. Engine.prototype.setState = function (culling, force) {
  3027. if (this._depthCullingState.cull !== culling || force) {
  3028. if (culling) {
  3029. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3030. this._depthCullingState.cull = true;
  3031. } else {
  3032. this._depthCullingState.cull = false;
  3033. }
  3034. }
  3035. };
  3036. Engine.prototype.setDepthBuffer = function (enable) {
  3037. this._depthCullingState.depthTest = enable;
  3038. };
  3039. Engine.prototype.getDepthWrite = function () {
  3040. return this._depthCullingState.depthMask;
  3041. };
  3042. Engine.prototype.setDepthWrite = function (enable) {
  3043. this._depthCullingState.depthMask = enable;
  3044. };
  3045. Engine.prototype.setColorWrite = function (enable) {
  3046. this._gl.colorMask(enable, enable, enable, enable);
  3047. };
  3048. Engine.prototype.setAlphaMode = function (mode) {
  3049. switch (mode) {
  3050. case BABYLON.Engine.ALPHA_DISABLE:
  3051. this.setDepthWrite(true);
  3052. this._alphaState.alphaBlend = false;
  3053. break;
  3054. case BABYLON.Engine.ALPHA_COMBINE:
  3055. this.setDepthWrite(false);
  3056. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3057. this._alphaState.alphaBlend = true;
  3058. break;
  3059. case BABYLON.Engine.ALPHA_ADD:
  3060. this.setDepthWrite(false);
  3061. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3062. this._alphaState.alphaBlend = true;
  3063. break;
  3064. }
  3065. };
  3066. Engine.prototype.setAlphaTesting = function (enable) {
  3067. this._alphaTest = enable;
  3068. };
  3069. Engine.prototype.getAlphaTesting = function () {
  3070. return this._alphaTest;
  3071. };
  3072. Engine.prototype.wipeCaches = function () {
  3073. this._activeTexturesCache = [];
  3074. this._currentEffect = null;
  3075. this._depthCullingState.reset();
  3076. this._alphaState.reset();
  3077. this._cachedVertexBuffers = null;
  3078. this._cachedIndexBuffer = null;
  3079. this._cachedEffectForVertexBuffers = null;
  3080. };
  3081. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3082. var gl = this._gl;
  3083. gl.bindTexture(gl.TEXTURE_2D, texture);
  3084. var magFilter = gl.NEAREST;
  3085. var minFilter = gl.NEAREST;
  3086. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3087. magFilter = gl.LINEAR;
  3088. minFilter = gl.LINEAR;
  3089. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3090. magFilter = gl.LINEAR;
  3091. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3092. }
  3093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3095. gl.bindTexture(gl.TEXTURE_2D, null);
  3096. };
  3097. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  3098. var _this = this;
  3099. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3100. var texture = this._gl.createTexture();
  3101. var extension = url.substr(url.length - 4, 4).toLowerCase();
  3102. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3103. var isTGA = (extension === ".tga");
  3104. scene._addPendingData(texture);
  3105. texture.url = url;
  3106. texture.noMipmap = noMipmap;
  3107. texture.references = 1;
  3108. this._loadedTexturesCache.push(texture);
  3109. if (isTGA) {
  3110. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3111. var data = new Uint8Array(arrayBuffer);
  3112. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3113. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3114. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3115. }, samplingMode);
  3116. }, null, scene.database, true);
  3117. } else if (isDDS) {
  3118. BABYLON.Tools.LoadFile(url, function (data) {
  3119. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3120. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3121. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3122. console.log("loading " + url);
  3123. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3124. }, samplingMode);
  3125. }, null, scene.database, true);
  3126. } else {
  3127. var onload = function (img) {
  3128. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3129. var isPot = (img.width == potWidth && img.height == potHeight);
  3130. if (!isPot) {
  3131. _this._workingCanvas.width = potWidth;
  3132. _this._workingCanvas.height = potHeight;
  3133. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3134. }
  3135. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3136. }, samplingMode);
  3137. };
  3138. var onerror = function () {
  3139. scene._removePendingData(texture);
  3140. };
  3141. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3142. }
  3143. return texture;
  3144. };
  3145. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3146. var texture = this._gl.createTexture();
  3147. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  3148. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  3149. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3150. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3151. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3152. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3153. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3154. this._activeTexturesCache = [];
  3155. texture._baseWidth = width;
  3156. texture._baseHeight = height;
  3157. texture._width = width;
  3158. texture._height = height;
  3159. texture.isReady = false;
  3160. texture.generateMipMaps = generateMipMaps;
  3161. texture.references = 1;
  3162. this._loadedTexturesCache.push(texture);
  3163. return texture;
  3164. };
  3165. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3166. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3167. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3168. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3169. if (texture.generateMipMaps) {
  3170. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3171. }
  3172. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3173. this._activeTexturesCache = [];
  3174. texture.isReady = true;
  3175. };
  3176. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3177. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3178. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3179. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3180. if (!texture._workingCanvas) {
  3181. texture._workingCanvas = document.createElement("canvas");
  3182. texture._workingContext = texture._workingCanvas.getContext("2d");
  3183. texture._workingCanvas.width = texture._width;
  3184. texture._workingCanvas.height = texture._height;
  3185. }
  3186. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3187. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3188. } else {
  3189. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3190. }
  3191. if (texture.generateMipMaps) {
  3192. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3193. }
  3194. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3195. this._activeTexturesCache = [];
  3196. texture.isReady = true;
  3197. };
  3198. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3199. var generateMipMaps = false;
  3200. var generateDepthBuffer = true;
  3201. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3202. if (options !== undefined) {
  3203. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3204. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3205. if (options.samplingMode !== undefined) {
  3206. samplingMode = options.samplingMode;
  3207. }
  3208. }
  3209. var gl = this._gl;
  3210. var texture = gl.createTexture();
  3211. gl.bindTexture(gl.TEXTURE_2D, texture);
  3212. var width = size.width || size;
  3213. var height = size.height || size;
  3214. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3215. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3219. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3220. var depthBuffer;
  3221. if (generateDepthBuffer) {
  3222. depthBuffer = gl.createRenderbuffer();
  3223. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3224. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3225. }
  3226. var framebuffer = gl.createFramebuffer();
  3227. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3228. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3229. if (generateDepthBuffer) {
  3230. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3231. }
  3232. gl.bindTexture(gl.TEXTURE_2D, null);
  3233. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3234. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3235. texture._framebuffer = framebuffer;
  3236. if (generateDepthBuffer) {
  3237. texture._depthBuffer = depthBuffer;
  3238. }
  3239. texture._width = width;
  3240. texture._height = height;
  3241. texture.isReady = true;
  3242. texture.generateMipMaps = generateMipMaps;
  3243. texture.references = 1;
  3244. this._activeTexturesCache = [];
  3245. this._loadedTexturesCache.push(texture);
  3246. return texture;
  3247. };
  3248. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3249. var _this = this;
  3250. var gl = this._gl;
  3251. var texture = gl.createTexture();
  3252. texture.isCube = true;
  3253. texture.url = rootUrl;
  3254. texture.references = 1;
  3255. this._loadedTexturesCache.push(texture);
  3256. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3257. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3258. if (isDDS) {
  3259. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3260. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3261. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3262. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3263. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3264. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3265. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3266. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3267. }
  3268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3270. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3271. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3272. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3273. _this._activeTexturesCache = [];
  3274. texture._width = info.width;
  3275. texture._height = info.height;
  3276. texture.isReady = true;
  3277. });
  3278. } else {
  3279. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3280. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3281. var height = width;
  3282. _this._workingCanvas.width = width;
  3283. _this._workingCanvas.height = height;
  3284. var faces = [
  3285. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3286. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3287. ];
  3288. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3289. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3290. for (var index = 0; index < faces.length; index++) {
  3291. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3292. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3293. }
  3294. if (!noMipmap) {
  3295. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3296. }
  3297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3301. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3302. _this._activeTexturesCache = [];
  3303. texture._width = width;
  3304. texture._height = height;
  3305. texture.isReady = true;
  3306. }, extensions);
  3307. }
  3308. return texture;
  3309. };
  3310. Engine.prototype._releaseTexture = function (texture) {
  3311. var gl = this._gl;
  3312. if (texture._framebuffer) {
  3313. gl.deleteFramebuffer(texture._framebuffer);
  3314. }
  3315. if (texture._depthBuffer) {
  3316. gl.deleteRenderbuffer(texture._depthBuffer);
  3317. }
  3318. gl.deleteTexture(texture);
  3319. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3320. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3321. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3322. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3323. this._activeTexturesCache[channel] = null;
  3324. }
  3325. var index = this._loadedTexturesCache.indexOf(texture);
  3326. if (index !== -1) {
  3327. this._loadedTexturesCache.splice(index, 1);
  3328. }
  3329. };
  3330. Engine.prototype.bindSamplers = function (effect) {
  3331. this._gl.useProgram(effect.getProgram());
  3332. var samplers = effect.getSamplers();
  3333. for (var index = 0; index < samplers.length; index++) {
  3334. var uniform = effect.getUniform(samplers[index]);
  3335. this._gl.uniform1i(uniform, index);
  3336. }
  3337. this._currentEffect = null;
  3338. };
  3339. Engine.prototype._bindTexture = function (channel, texture) {
  3340. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3341. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3342. this._activeTexturesCache[channel] = null;
  3343. };
  3344. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3345. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3346. };
  3347. Engine.prototype.setTexture = function (channel, texture) {
  3348. if (channel < 0) {
  3349. return;
  3350. }
  3351. if (!texture || !texture.isReady()) {
  3352. if (this._activeTexturesCache[channel] != null) {
  3353. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3354. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3355. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3356. this._activeTexturesCache[channel] = null;
  3357. }
  3358. return;
  3359. }
  3360. if (texture instanceof BABYLON.VideoTexture) {
  3361. if (texture.update()) {
  3362. this._activeTexturesCache[channel] = null;
  3363. }
  3364. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3365. texture.delayLoad();
  3366. return;
  3367. }
  3368. if (this._activeTexturesCache[channel] == texture) {
  3369. return;
  3370. }
  3371. this._activeTexturesCache[channel] = texture;
  3372. var internalTexture = texture.getInternalTexture();
  3373. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3374. if (internalTexture.isCube) {
  3375. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3376. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3377. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3378. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3379. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3380. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3381. }
  3382. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3383. } else {
  3384. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3385. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3386. internalTexture._cachedWrapU = texture.wrapU;
  3387. switch (texture.wrapU) {
  3388. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3389. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3390. break;
  3391. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3392. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3393. break;
  3394. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3395. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3396. break;
  3397. }
  3398. }
  3399. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3400. internalTexture._cachedWrapV = texture.wrapV;
  3401. switch (texture.wrapV) {
  3402. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3403. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3404. break;
  3405. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3406. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3407. break;
  3408. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3410. break;
  3411. }
  3412. }
  3413. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3414. }
  3415. };
  3416. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3417. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3418. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3419. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3420. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3421. }
  3422. };
  3423. Engine.prototype.readPixels = function (x, y, width, height) {
  3424. var data = new Uint8Array(height * width * 4);
  3425. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3426. return data;
  3427. };
  3428. Engine.prototype.dispose = function () {
  3429. this.hideLoadingUI();
  3430. this.stopRenderLoop();
  3431. while (this.scenes.length) {
  3432. this.scenes[0].dispose();
  3433. }
  3434. for (var name in this._compiledEffects) {
  3435. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3436. }
  3437. for (var i in this._vertexAttribArrays) {
  3438. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3439. continue;
  3440. }
  3441. this._gl.disableVertexAttribArray(i);
  3442. }
  3443. window.removeEventListener("blur", this._onBlur);
  3444. window.removeEventListener("focus", this._onFocus);
  3445. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3446. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3447. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3448. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3449. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3450. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3451. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3452. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3453. };
  3454. Engine.prototype.displayLoadingUI = function () {
  3455. var _this = this;
  3456. this._loadingDiv = document.createElement("div");
  3457. this._loadingDiv.style.opacity = "0";
  3458. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3459. this._loadingTextDiv = document.createElement("div");
  3460. this._loadingTextDiv.style.position = "absolute";
  3461. this._loadingTextDiv.style.left = "0";
  3462. this._loadingTextDiv.style.top = "50%";
  3463. this._loadingTextDiv.style.marginTop = "80px";
  3464. this._loadingTextDiv.style.width = "100%";
  3465. this._loadingTextDiv.style.height = "20px";
  3466. this._loadingTextDiv.style.fontFamily = "Arial";
  3467. this._loadingTextDiv.style.fontSize = "14px";
  3468. this._loadingTextDiv.style.color = "white";
  3469. this._loadingTextDiv.style.textAlign = "center";
  3470. this._loadingTextDiv.innerHTML = "Loading";
  3471. this._loadingDiv.appendChild(this._loadingTextDiv);
  3472. var imgBack = new Image();
  3473. 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==";
  3474. imgBack.style.position = "absolute";
  3475. imgBack.style.left = "50%";
  3476. imgBack.style.top = "50%";
  3477. imgBack.style.marginLeft = "-50px";
  3478. imgBack.style.marginTop = "-50px";
  3479. imgBack.style.transition = "transform 1.0s ease";
  3480. var deg = 360;
  3481. imgBack.addEventListener("transitionend", function () {
  3482. deg += 360;
  3483. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3484. });
  3485. this._loadingDiv.appendChild(imgBack);
  3486. var imgFront = new Image();
  3487. 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=";
  3488. imgFront.style.position = "absolute";
  3489. imgFront.style.left = "50%";
  3490. imgFront.style.top = "50%";
  3491. imgFront.style.marginLeft = "-50px";
  3492. imgFront.style.marginTop = "-50px";
  3493. this._loadingDiv.appendChild(imgFront);
  3494. this._resizeLoadingUI = function () {
  3495. var canvasRect = _this.getRenderingCanvasClientRect();
  3496. _this._loadingDiv.style.position = "absolute";
  3497. _this._loadingDiv.style.left = canvasRect.left + "px";
  3498. _this._loadingDiv.style.top = canvasRect.top + "px";
  3499. _this._loadingDiv.style.width = canvasRect.width + "px";
  3500. _this._loadingDiv.style.height = canvasRect.height + "px";
  3501. };
  3502. this._resizeLoadingUI();
  3503. window.addEventListener("resize", this._resizeLoadingUI);
  3504. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3505. document.body.appendChild(this._loadingDiv);
  3506. setTimeout(function () {
  3507. _this._loadingDiv.style.opacity = "1";
  3508. imgBack.style.transform = "rotateZ(360deg)";
  3509. }, 0);
  3510. };
  3511. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3512. set: function (text) {
  3513. if (!this._loadingDiv) {
  3514. return;
  3515. }
  3516. this._loadingTextDiv.innerHTML = text;
  3517. },
  3518. enumerable: true,
  3519. configurable: true
  3520. });
  3521. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3522. get: function () {
  3523. return this._loadingDivBackgroundColor;
  3524. },
  3525. set: function (color) {
  3526. this._loadingDivBackgroundColor = color;
  3527. if (!this._loadingDiv) {
  3528. return;
  3529. }
  3530. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3531. },
  3532. enumerable: true,
  3533. configurable: true
  3534. });
  3535. Engine.prototype.hideLoadingUI = function () {
  3536. var _this = this;
  3537. if (!this._loadingDiv) {
  3538. return;
  3539. }
  3540. var onTransitionEnd = function () {
  3541. if (!_this._loadingDiv) {
  3542. return;
  3543. }
  3544. document.body.removeChild(_this._loadingDiv);
  3545. window.removeEventListener("resize", _this._resizeLoadingUI);
  3546. _this._loadingDiv = null;
  3547. };
  3548. this._loadingDiv.style.opacity = "0";
  3549. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3550. };
  3551. Engine.isSupported = function () {
  3552. try {
  3553. var tempcanvas = document.createElement("canvas");
  3554. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3555. return gl != null && !!window.WebGLRenderingContext;
  3556. } catch (e) {
  3557. return false;
  3558. }
  3559. };
  3560. Engine._ALPHA_DISABLE = 0;
  3561. Engine._ALPHA_ADD = 1;
  3562. Engine._ALPHA_COMBINE = 2;
  3563. Engine._DELAYLOADSTATE_NONE = 0;
  3564. Engine._DELAYLOADSTATE_LOADED = 1;
  3565. Engine._DELAYLOADSTATE_LOADING = 2;
  3566. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3567. Engine.Epsilon = 0.001;
  3568. Engine.CollisionsEpsilon = 0.001;
  3569. Engine.ShadersRepository = "Babylon/Shaders/";
  3570. return Engine;
  3571. })();
  3572. BABYLON.Engine = Engine;
  3573. })(BABYLON || (BABYLON = {}));
  3574. var BABYLON;
  3575. (function (BABYLON) {
  3576. var Node = (function () {
  3577. function Node(name, scene) {
  3578. this.state = "";
  3579. this.animations = new Array();
  3580. this._childrenFlag = -1;
  3581. this._isEnabled = true;
  3582. this._isReady = true;
  3583. this._currentRenderId = -1;
  3584. this.name = name;
  3585. this.id = name;
  3586. this._scene = scene;
  3587. this._initCache();
  3588. }
  3589. Node.prototype.getScene = function () {
  3590. return this._scene;
  3591. };
  3592. Node.prototype.getEngine = function () {
  3593. return this._scene.getEngine();
  3594. };
  3595. Node.prototype.getWorldMatrix = function () {
  3596. return BABYLON.Matrix.Identity();
  3597. };
  3598. Node.prototype._initCache = function () {
  3599. this._cache = {};
  3600. this._cache.parent = undefined;
  3601. };
  3602. Node.prototype.updateCache = function (force) {
  3603. if (!force && this.isSynchronized())
  3604. return;
  3605. this._cache.parent = this.parent;
  3606. this._updateCache();
  3607. };
  3608. Node.prototype._updateCache = function (ignoreParentClass) {
  3609. };
  3610. Node.prototype._isSynchronized = function () {
  3611. return true;
  3612. };
  3613. Node.prototype.isSynchronizedWithParent = function () {
  3614. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3615. };
  3616. Node.prototype.isSynchronized = function (updateCache) {
  3617. var check = this.hasNewParent();
  3618. check = check || !this.isSynchronizedWithParent();
  3619. check = check || !this._isSynchronized();
  3620. if (updateCache)
  3621. this.updateCache(true);
  3622. return !check;
  3623. };
  3624. Node.prototype.hasNewParent = function (update) {
  3625. if (this._cache.parent === this.parent)
  3626. return false;
  3627. if (update)
  3628. this._cache.parent = this.parent;
  3629. return true;
  3630. };
  3631. Node.prototype.isReady = function () {
  3632. return this._isReady;
  3633. };
  3634. Node.prototype.isEnabled = function () {
  3635. if (!this._isEnabled) {
  3636. return false;
  3637. }
  3638. if (this.parent) {
  3639. return this.parent.isEnabled();
  3640. }
  3641. return true;
  3642. };
  3643. Node.prototype.setEnabled = function (value) {
  3644. this._isEnabled = value;
  3645. };
  3646. Node.prototype.isDescendantOf = function (ancestor) {
  3647. if (this.parent) {
  3648. if (this.parent === ancestor) {
  3649. return true;
  3650. }
  3651. return this.parent.isDescendantOf(ancestor);
  3652. }
  3653. return false;
  3654. };
  3655. Node.prototype._getDescendants = function (list, results) {
  3656. for (var index = 0; index < list.length; index++) {
  3657. var item = list[index];
  3658. if (item.isDescendantOf(this)) {
  3659. results.push(item);
  3660. }
  3661. }
  3662. };
  3663. Node.prototype.getDescendants = function () {
  3664. var results = [];
  3665. this._getDescendants(this._scene.meshes, results);
  3666. this._getDescendants(this._scene.lights, results);
  3667. this._getDescendants(this._scene.cameras, results);
  3668. return results;
  3669. };
  3670. Node.prototype._setReady = function (state) {
  3671. if (state == this._isReady) {
  3672. return;
  3673. }
  3674. if (!state) {
  3675. this._isReady = false;
  3676. return;
  3677. }
  3678. this._isReady = true;
  3679. if (this.onReady) {
  3680. this.onReady(this);
  3681. }
  3682. };
  3683. return Node;
  3684. })();
  3685. BABYLON.Node = Node;
  3686. })(BABYLON || (BABYLON = {}));
  3687. var BABYLON;
  3688. (function (BABYLON) {
  3689. var BoundingSphere = (function () {
  3690. function BoundingSphere(minimum, maximum) {
  3691. this.minimum = minimum;
  3692. this.maximum = maximum;
  3693. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3694. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3695. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3696. this.radius = distance * 0.5;
  3697. this.centerWorld = BABYLON.Vector3.Zero();
  3698. this._update(BABYLON.Matrix.Identity());
  3699. }
  3700. BoundingSphere.prototype._update = function (world) {
  3701. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3702. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3703. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3704. };
  3705. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3706. for (var i = 0; i < 6; i++) {
  3707. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3708. return false;
  3709. }
  3710. return true;
  3711. };
  3712. BoundingSphere.prototype.intersectsPoint = function (point) {
  3713. var x = this.centerWorld.x - point.x;
  3714. var y = this.centerWorld.y - point.y;
  3715. var z = this.centerWorld.z - point.z;
  3716. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3717. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3718. return false;
  3719. return true;
  3720. };
  3721. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3722. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3723. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3724. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3725. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3726. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3727. return false;
  3728. return true;
  3729. };
  3730. return BoundingSphere;
  3731. })();
  3732. BABYLON.BoundingSphere = BoundingSphere;
  3733. })(BABYLON || (BABYLON = {}));
  3734. var BABYLON;
  3735. (function (BABYLON) {
  3736. var BoundingBox = (function () {
  3737. function BoundingBox(minimum, maximum) {
  3738. this.minimum = minimum;
  3739. this.maximum = maximum;
  3740. this.vectors = new Array();
  3741. this.vectorsWorld = new Array();
  3742. this.vectors.push(this.minimum.clone());
  3743. this.vectors.push(this.maximum.clone());
  3744. this.vectors.push(this.minimum.clone());
  3745. this.vectors[2].x = this.maximum.x;
  3746. this.vectors.push(this.minimum.clone());
  3747. this.vectors[3].y = this.maximum.y;
  3748. this.vectors.push(this.minimum.clone());
  3749. this.vectors[4].z = this.maximum.z;
  3750. this.vectors.push(this.maximum.clone());
  3751. this.vectors[5].z = this.minimum.z;
  3752. this.vectors.push(this.maximum.clone());
  3753. this.vectors[6].x = this.minimum.x;
  3754. this.vectors.push(this.maximum.clone());
  3755. this.vectors[7].y = this.minimum.y;
  3756. this.center = this.maximum.add(this.minimum).scale(0.5);
  3757. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3758. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3759. for (var index = 0; index < this.vectors.length; index++) {
  3760. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3761. }
  3762. this.minimumWorld = BABYLON.Vector3.Zero();
  3763. this.maximumWorld = BABYLON.Vector3.Zero();
  3764. this._update(BABYLON.Matrix.Identity());
  3765. }
  3766. BoundingBox.prototype.getWorldMatrix = function () {
  3767. return this._worldMatrix;
  3768. };
  3769. BoundingBox.prototype._update = function (world) {
  3770. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3771. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3772. for (var index = 0; index < this.vectors.length; index++) {
  3773. var v = this.vectorsWorld[index];
  3774. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3775. if (v.x < this.minimumWorld.x)
  3776. this.minimumWorld.x = v.x;
  3777. if (v.y < this.minimumWorld.y)
  3778. this.minimumWorld.y = v.y;
  3779. if (v.z < this.minimumWorld.z)
  3780. this.minimumWorld.z = v.z;
  3781. if (v.x > this.maximumWorld.x)
  3782. this.maximumWorld.x = v.x;
  3783. if (v.y > this.maximumWorld.y)
  3784. this.maximumWorld.y = v.y;
  3785. if (v.z > this.maximumWorld.z)
  3786. this.maximumWorld.z = v.z;
  3787. }
  3788. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3789. this.center.scaleInPlace(0.5);
  3790. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3791. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3792. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3793. this._worldMatrix = world;
  3794. };
  3795. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3796. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3797. };
  3798. BoundingBox.prototype.intersectsPoint = function (point) {
  3799. var delta = BABYLON.Engine.Epsilon;
  3800. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3801. return false;
  3802. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3803. return false;
  3804. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3805. return false;
  3806. return true;
  3807. };
  3808. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3809. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3810. };
  3811. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3812. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3813. return false;
  3814. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3815. return false;
  3816. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3817. return false;
  3818. return true;
  3819. };
  3820. BoundingBox.Intersects = function (box0, box1) {
  3821. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3822. return false;
  3823. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3824. return false;
  3825. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3826. return false;
  3827. return true;
  3828. };
  3829. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3830. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3831. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3832. return (num <= (sphereRadius * sphereRadius));
  3833. };
  3834. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3835. for (var p = 0; p < 6; p++) {
  3836. var inCount = 8;
  3837. for (var i = 0; i < 8; i++) {
  3838. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3839. --inCount;
  3840. } else {
  3841. break;
  3842. }
  3843. }
  3844. if (inCount == 0)
  3845. return false;
  3846. }
  3847. return true;
  3848. };
  3849. return BoundingBox;
  3850. })();
  3851. BABYLON.BoundingBox = BoundingBox;
  3852. })(BABYLON || (BABYLON = {}));
  3853. var BABYLON;
  3854. (function (BABYLON) {
  3855. var computeBoxExtents = function (axis, box) {
  3856. var p = BABYLON.Vector3.Dot(box.center, axis);
  3857. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3858. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3859. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3860. var r = r0 + r1 + r2;
  3861. return {
  3862. min: p - r,
  3863. max: p + r
  3864. };
  3865. };
  3866. var extentsOverlap = function (min0, max0, min1, max1) {
  3867. return !(min0 > max1 || min1 > max0);
  3868. };
  3869. var axisOverlap = function (axis, box0, box1) {
  3870. var result0 = computeBoxExtents(axis, box0);
  3871. var result1 = computeBoxExtents(axis, box1);
  3872. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3873. };
  3874. var BoundingInfo = (function () {
  3875. function BoundingInfo(minimum, maximum) {
  3876. this.minimum = minimum;
  3877. this.maximum = maximum;
  3878. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3879. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3880. }
  3881. BoundingInfo.prototype._update = function (world) {
  3882. this.boundingBox._update(world);
  3883. this.boundingSphere._update(world);
  3884. };
  3885. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3886. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3887. return false;
  3888. return this.boundingBox.isInFrustum(frustumPlanes);
  3889. };
  3890. BoundingInfo.prototype._checkCollision = function (collider) {
  3891. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3892. };
  3893. BoundingInfo.prototype.intersectsPoint = function (point) {
  3894. if (!this.boundingSphere.centerWorld) {
  3895. return false;
  3896. }
  3897. if (!this.boundingSphere.intersectsPoint(point)) {
  3898. return false;
  3899. }
  3900. if (!this.boundingBox.intersectsPoint(point)) {
  3901. return false;
  3902. }
  3903. return true;
  3904. };
  3905. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3906. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3907. return false;
  3908. }
  3909. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3910. return false;
  3911. }
  3912. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3913. return false;
  3914. }
  3915. if (!precise) {
  3916. return true;
  3917. }
  3918. var box0 = this.boundingBox;
  3919. var box1 = boundingInfo.boundingBox;
  3920. if (!axisOverlap(box0.directions[0], box0, box1))
  3921. return false;
  3922. if (!axisOverlap(box0.directions[1], box0, box1))
  3923. return false;
  3924. if (!axisOverlap(box0.directions[2], box0, box1))
  3925. return false;
  3926. if (!axisOverlap(box1.directions[0], box0, box1))
  3927. return false;
  3928. if (!axisOverlap(box1.directions[1], box0, box1))
  3929. return false;
  3930. if (!axisOverlap(box1.directions[2], box0, box1))
  3931. return false;
  3932. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  3933. return false;
  3934. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  3935. return false;
  3936. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  3937. return false;
  3938. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  3939. return false;
  3940. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  3941. return false;
  3942. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  3943. return false;
  3944. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  3945. return false;
  3946. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  3947. return false;
  3948. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  3949. return false;
  3950. return true;
  3951. };
  3952. return BoundingInfo;
  3953. })();
  3954. BABYLON.BoundingInfo = BoundingInfo;
  3955. })(BABYLON || (BABYLON = {}));
  3956. var __extends = this.__extends || function (d, b) {
  3957. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3958. function __() { this.constructor = d; }
  3959. __.prototype = b.prototype;
  3960. d.prototype = new __();
  3961. };
  3962. var BABYLON;
  3963. (function (BABYLON) {
  3964. var Light = (function (_super) {
  3965. __extends(Light, _super);
  3966. function Light(name, scene) {
  3967. _super.call(this, name, scene);
  3968. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  3969. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  3970. this.intensity = 1.0;
  3971. this.range = Number.MAX_VALUE;
  3972. this.includedOnlyMeshes = new Array();
  3973. this.excludedMeshes = new Array();
  3974. this._excludedMeshesIds = new Array();
  3975. this._includedOnlyMeshesIds = new Array();
  3976. scene.lights.push(this);
  3977. }
  3978. Light.prototype.getShadowGenerator = function () {
  3979. return this._shadowGenerator;
  3980. };
  3981. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  3982. };
  3983. Light.prototype._getWorldMatrix = function () {
  3984. return BABYLON.Matrix.Identity();
  3985. };
  3986. Light.prototype.canAffectMesh = function (mesh) {
  3987. if (!mesh) {
  3988. return true;
  3989. }
  3990. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  3991. return false;
  3992. }
  3993. if (this.includedOnlyMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  3994. return false;
  3995. }
  3996. return true;
  3997. };
  3998. Light.prototype.getWorldMatrix = function () {
  3999. this._currentRenderId = this.getScene().getRenderId();
  4000. var worldMatrix = this._getWorldMatrix();
  4001. if (this.parent && this.parent.getWorldMatrix) {
  4002. if (!this._parentedWorldMatrix) {
  4003. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4004. }
  4005. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4006. return this._parentedWorldMatrix;
  4007. }
  4008. return worldMatrix;
  4009. };
  4010. Light.prototype.dispose = function () {
  4011. if (this._shadowGenerator) {
  4012. this._shadowGenerator.dispose();
  4013. this._shadowGenerator = null;
  4014. }
  4015. var index = this.getScene().lights.indexOf(this);
  4016. this.getScene().lights.splice(index, 1);
  4017. };
  4018. return Light;
  4019. })(BABYLON.Node);
  4020. BABYLON.Light = Light;
  4021. })(BABYLON || (BABYLON = {}));
  4022. var __extends = this.__extends || function (d, b) {
  4023. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4024. function __() { this.constructor = d; }
  4025. __.prototype = b.prototype;
  4026. d.prototype = new __();
  4027. };
  4028. var BABYLON;
  4029. (function (BABYLON) {
  4030. var PointLight = (function (_super) {
  4031. __extends(PointLight, _super);
  4032. function PointLight(name, position, scene) {
  4033. _super.call(this, name, scene);
  4034. this.position = position;
  4035. }
  4036. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4037. if (this.parent && this.parent.getWorldMatrix) {
  4038. if (!this._transformedPosition) {
  4039. this._transformedPosition = BABYLON.Vector3.Zero();
  4040. }
  4041. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4042. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4043. return;
  4044. }
  4045. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4046. };
  4047. PointLight.prototype.getShadowGenerator = function () {
  4048. return null;
  4049. };
  4050. PointLight.prototype._getWorldMatrix = function () {
  4051. if (!this._worldMatrix) {
  4052. this._worldMatrix = BABYLON.Matrix.Identity();
  4053. }
  4054. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4055. return this._worldMatrix;
  4056. };
  4057. return PointLight;
  4058. })(BABYLON.Light);
  4059. BABYLON.PointLight = PointLight;
  4060. })(BABYLON || (BABYLON = {}));
  4061. var __extends = this.__extends || function (d, b) {
  4062. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4063. function __() { this.constructor = d; }
  4064. __.prototype = b.prototype;
  4065. d.prototype = new __();
  4066. };
  4067. var BABYLON;
  4068. (function (BABYLON) {
  4069. var SpotLight = (function (_super) {
  4070. __extends(SpotLight, _super);
  4071. function SpotLight(name, position, direction, angle, exponent, scene) {
  4072. _super.call(this, name, scene);
  4073. this.position = position;
  4074. this.direction = direction;
  4075. this.angle = angle;
  4076. this.exponent = exponent;
  4077. }
  4078. SpotLight.prototype.setDirectionToTarget = function (target) {
  4079. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4080. return this.direction;
  4081. };
  4082. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4083. var normalizeDirection;
  4084. if (this.parent && this.parent.getWorldMatrix) {
  4085. if (!this._transformedDirection) {
  4086. this._transformedDirection = BABYLON.Vector3.Zero();
  4087. }
  4088. if (!this._transformedPosition) {
  4089. this._transformedPosition = BABYLON.Vector3.Zero();
  4090. }
  4091. var parentWorldMatrix = this.parent.getWorldMatrix();
  4092. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4093. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4094. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4095. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4096. } else {
  4097. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4098. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4099. }
  4100. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4101. };
  4102. SpotLight.prototype._getWorldMatrix = function () {
  4103. if (!this._worldMatrix) {
  4104. this._worldMatrix = BABYLON.Matrix.Identity();
  4105. }
  4106. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4107. return this._worldMatrix;
  4108. };
  4109. return SpotLight;
  4110. })(BABYLON.Light);
  4111. BABYLON.SpotLight = SpotLight;
  4112. })(BABYLON || (BABYLON = {}));
  4113. var __extends = this.__extends || function (d, b) {
  4114. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4115. function __() { this.constructor = d; }
  4116. __.prototype = b.prototype;
  4117. d.prototype = new __();
  4118. };
  4119. var BABYLON;
  4120. (function (BABYLON) {
  4121. var DirectionalLight = (function (_super) {
  4122. __extends(DirectionalLight, _super);
  4123. function DirectionalLight(name, direction, scene) {
  4124. _super.call(this, name, scene);
  4125. this.direction = direction;
  4126. this.position = direction.scale(-1);
  4127. }
  4128. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4129. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4130. return this.direction;
  4131. };
  4132. DirectionalLight.prototype._computeTransformedPosition = function () {
  4133. if (this.parent && this.parent.getWorldMatrix) {
  4134. if (!this._transformedPosition) {
  4135. this._transformedPosition = BABYLON.Vector3.Zero();
  4136. }
  4137. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4138. return true;
  4139. }
  4140. return false;
  4141. };
  4142. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4143. if (this.parent && this.parent.getWorldMatrix) {
  4144. if (!this._transformedDirection) {
  4145. this._transformedDirection = BABYLON.Vector3.Zero();
  4146. }
  4147. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4148. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4149. return;
  4150. }
  4151. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4152. };
  4153. DirectionalLight.prototype._getWorldMatrix = function () {
  4154. if (!this._worldMatrix) {
  4155. this._worldMatrix = BABYLON.Matrix.Identity();
  4156. }
  4157. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4158. return this._worldMatrix;
  4159. };
  4160. return DirectionalLight;
  4161. })(BABYLON.Light);
  4162. BABYLON.DirectionalLight = DirectionalLight;
  4163. })(BABYLON || (BABYLON = {}));
  4164. var BABYLON;
  4165. (function (BABYLON) {
  4166. var ShadowGenerator = (function () {
  4167. function ShadowGenerator(mapSize, light) {
  4168. var _this = this;
  4169. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4170. this._darkness = 0;
  4171. this._transparencyShadow = false;
  4172. this._viewMatrix = BABYLON.Matrix.Zero();
  4173. this._projectionMatrix = BABYLON.Matrix.Zero();
  4174. this._transformMatrix = BABYLON.Matrix.Zero();
  4175. this._worldViewProjection = BABYLON.Matrix.Zero();
  4176. this._light = light;
  4177. this._scene = light.getScene();
  4178. light._shadowGenerator = this;
  4179. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4180. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4181. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4182. this._shadowMap.renderParticles = false;
  4183. var renderSubMesh = function (subMesh) {
  4184. var mesh = subMesh.getRenderingMesh();
  4185. var scene = _this._scene;
  4186. var engine = scene.getEngine();
  4187. engine.setState(subMesh.getMaterial().backFaceCulling);
  4188. var batch = mesh._getInstancesRenderList(subMesh._id);
  4189. if (batch.mustReturn) {
  4190. return;
  4191. }
  4192. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  4193. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4194. engine.enableEffect(_this._effect);
  4195. mesh._bind(subMesh, _this._effect, false);
  4196. var material = subMesh.getMaterial();
  4197. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4198. if (material && material.needAlphaTesting()) {
  4199. var alphaTexture = material.getAlphaTestTexture();
  4200. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4201. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4202. }
  4203. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4204. if (useBones) {
  4205. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4206. }
  4207. if (hardwareInstancedRendering) {
  4208. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4209. } else {
  4210. if (batch.renderSelf[subMesh._id]) {
  4211. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4212. mesh._draw(subMesh, true);
  4213. }
  4214. if (batch.visibleInstances[subMesh._id]) {
  4215. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4216. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4217. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4218. mesh._draw(subMesh, true);
  4219. }
  4220. }
  4221. }
  4222. } else {
  4223. _this._shadowMap.resetRefreshCounter();
  4224. }
  4225. };
  4226. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4227. var index;
  4228. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4229. renderSubMesh(opaqueSubMeshes.data[index]);
  4230. }
  4231. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4232. renderSubMesh(alphaTestSubMeshes.data[index]);
  4233. }
  4234. if (_this._transparencyShadow) {
  4235. for (index = 0; index < transparentSubMeshes.length; index++) {
  4236. renderSubMesh(transparentSubMeshes.data[index]);
  4237. }
  4238. }
  4239. };
  4240. }
  4241. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4242. get: function () {
  4243. return ShadowGenerator._FILTER_NONE;
  4244. },
  4245. enumerable: true,
  4246. configurable: true
  4247. });
  4248. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4249. get: function () {
  4250. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4251. },
  4252. enumerable: true,
  4253. configurable: true
  4254. });
  4255. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4256. get: function () {
  4257. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4258. },
  4259. enumerable: true,
  4260. configurable: true
  4261. });
  4262. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4263. get: function () {
  4264. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4265. },
  4266. set: function (value) {
  4267. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4268. },
  4269. enumerable: true,
  4270. configurable: true
  4271. });
  4272. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4273. get: function () {
  4274. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4275. },
  4276. set: function (value) {
  4277. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4278. },
  4279. enumerable: true,
  4280. configurable: true
  4281. });
  4282. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4283. var defines = [];
  4284. if (this.useVarianceShadowMap) {
  4285. defines.push("#define VSM");
  4286. }
  4287. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4288. var mesh = subMesh.getMesh();
  4289. var material = subMesh.getMaterial();
  4290. if (material && material.needAlphaTesting()) {
  4291. defines.push("#define ALPHATEST");
  4292. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4293. attribs.push(BABYLON.VertexBuffer.UVKind);
  4294. defines.push("#define UV1");
  4295. }
  4296. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4297. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4298. defines.push("#define UV2");
  4299. }
  4300. }
  4301. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4302. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4303. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4304. defines.push("#define BONES");
  4305. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4306. }
  4307. if (useInstances) {
  4308. defines.push("#define INSTANCES");
  4309. attribs.push("world0");
  4310. attribs.push("world1");
  4311. attribs.push("world2");
  4312. attribs.push("world3");
  4313. }
  4314. var join = defines.join("\n");
  4315. if (this._cachedDefines != join) {
  4316. this._cachedDefines = join;
  4317. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4318. }
  4319. return this._effect.isReady();
  4320. };
  4321. ShadowGenerator.prototype.getShadowMap = function () {
  4322. return this._shadowMap;
  4323. };
  4324. ShadowGenerator.prototype.getLight = function () {
  4325. return this._light;
  4326. };
  4327. ShadowGenerator.prototype.getTransformMatrix = function () {
  4328. var lightPosition = this._light.position;
  4329. var lightDirection = this._light.direction;
  4330. if (this._light._computeTransformedPosition()) {
  4331. lightPosition = this._light._transformedPosition;
  4332. }
  4333. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4334. this._cachedPosition = lightPosition.clone();
  4335. this._cachedDirection = lightDirection.clone();
  4336. var activeCamera = this._scene.activeCamera;
  4337. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4338. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4339. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4340. }
  4341. return this._transformMatrix;
  4342. };
  4343. ShadowGenerator.prototype.getDarkness = function () {
  4344. return this._darkness;
  4345. };
  4346. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4347. if (darkness >= 1.0)
  4348. this._darkness = 1.0;
  4349. else if (darkness <= 0.0)
  4350. this._darkness = 0.0;
  4351. else
  4352. this._darkness = darkness;
  4353. };
  4354. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4355. this._transparencyShadow = hasShadow;
  4356. };
  4357. ShadowGenerator.prototype.dispose = function () {
  4358. this._shadowMap.dispose();
  4359. };
  4360. ShadowGenerator._FILTER_NONE = 0;
  4361. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4362. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4363. return ShadowGenerator;
  4364. })();
  4365. BABYLON.ShadowGenerator = ShadowGenerator;
  4366. })(BABYLON || (BABYLON = {}));
  4367. var __extends = this.__extends || function (d, b) {
  4368. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4369. function __() { this.constructor = d; }
  4370. __.prototype = b.prototype;
  4371. d.prototype = new __();
  4372. };
  4373. var BABYLON;
  4374. (function (BABYLON) {
  4375. var HemisphericLight = (function (_super) {
  4376. __extends(HemisphericLight, _super);
  4377. function HemisphericLight(name, direction, scene) {
  4378. _super.call(this, name, scene);
  4379. this.direction = direction;
  4380. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4381. }
  4382. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4383. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4384. return this.direction;
  4385. };
  4386. HemisphericLight.prototype.getShadowGenerator = function () {
  4387. return null;
  4388. };
  4389. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4390. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4391. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4392. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4393. };
  4394. HemisphericLight.prototype._getWorldMatrix = function () {
  4395. if (!this._worldMatrix) {
  4396. this._worldMatrix = BABYLON.Matrix.Identity();
  4397. }
  4398. return this._worldMatrix;
  4399. };
  4400. return HemisphericLight;
  4401. })(BABYLON.Light);
  4402. BABYLON.HemisphericLight = HemisphericLight;
  4403. })(BABYLON || (BABYLON = {}));
  4404. var BABYLON;
  4405. (function (BABYLON) {
  4406. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4407. if (boxMin.x > sphereCenter.x + sphereRadius)
  4408. return false;
  4409. if (sphereCenter.x - sphereRadius > boxMax.x)
  4410. return false;
  4411. if (boxMin.y > sphereCenter.y + sphereRadius)
  4412. return false;
  4413. if (sphereCenter.y - sphereRadius > boxMax.y)
  4414. return false;
  4415. if (boxMin.z > sphereCenter.z + sphereRadius)
  4416. return false;
  4417. if (sphereCenter.z - sphereRadius > boxMax.z)
  4418. return false;
  4419. return true;
  4420. };
  4421. var getLowestRoot = function (a, b, c, maxR) {
  4422. var determinant = b * b - 4.0 * a * c;
  4423. var result = { root: 0, found: false };
  4424. if (determinant < 0)
  4425. return result;
  4426. var sqrtD = Math.sqrt(determinant);
  4427. var r1 = (-b - sqrtD) / (2.0 * a);
  4428. var r2 = (-b + sqrtD) / (2.0 * a);
  4429. if (r1 > r2) {
  4430. var temp = r2;
  4431. r2 = r1;
  4432. r1 = temp;
  4433. }
  4434. if (r1 > 0 && r1 < maxR) {
  4435. result.root = r1;
  4436. result.found = true;
  4437. return result;
  4438. }
  4439. if (r2 > 0 && r2 < maxR) {
  4440. result.root = r2;
  4441. result.found = true;
  4442. return result;
  4443. }
  4444. return result;
  4445. };
  4446. var Collider = (function () {
  4447. function Collider() {
  4448. this.radius = new BABYLON.Vector3(1, 1, 1);
  4449. this.retry = 0;
  4450. this.basePointWorld = BABYLON.Vector3.Zero();
  4451. this.velocityWorld = BABYLON.Vector3.Zero();
  4452. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4453. this._collisionPoint = BABYLON.Vector3.Zero();
  4454. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4455. this._tempVector = BABYLON.Vector3.Zero();
  4456. this._tempVector2 = BABYLON.Vector3.Zero();
  4457. this._tempVector3 = BABYLON.Vector3.Zero();
  4458. this._tempVector4 = BABYLON.Vector3.Zero();
  4459. this._edge = BABYLON.Vector3.Zero();
  4460. this._baseToVertex = BABYLON.Vector3.Zero();
  4461. this._destinationPoint = BABYLON.Vector3.Zero();
  4462. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4463. this._displacementVector = BABYLON.Vector3.Zero();
  4464. }
  4465. Collider.prototype._initialize = function (source, dir, e) {
  4466. this.velocity = dir;
  4467. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4468. this.basePoint = source;
  4469. source.multiplyToRef(this.radius, this.basePointWorld);
  4470. dir.multiplyToRef(this.radius, this.velocityWorld);
  4471. this.velocityWorldLength = this.velocityWorld.length();
  4472. this.epsilon = e;
  4473. this.collisionFound = false;
  4474. };
  4475. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4476. pa.subtractToRef(point, this._tempVector);
  4477. pb.subtractToRef(point, this._tempVector2);
  4478. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4479. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4480. if (d < 0)
  4481. return false;
  4482. pc.subtractToRef(point, this._tempVector3);
  4483. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4484. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4485. if (d < 0)
  4486. return false;
  4487. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4488. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4489. return d >= 0;
  4490. };
  4491. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4492. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4493. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4494. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4495. return false;
  4496. }
  4497. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4498. return false;
  4499. return true;
  4500. };
  4501. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4502. var t0;
  4503. var embeddedInPlane = false;
  4504. if (!subMesh._trianglePlanes) {
  4505. subMesh._trianglePlanes = [];
  4506. }
  4507. if (!subMesh._trianglePlanes[faceIndex]) {
  4508. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4509. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4510. }
  4511. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4512. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4513. return;
  4514. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4515. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4516. if (normalDotVelocity == 0) {
  4517. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4518. return;
  4519. embeddedInPlane = true;
  4520. t0 = 0;
  4521. } else {
  4522. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4523. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4524. if (t0 > t1) {
  4525. var temp = t1;
  4526. t1 = t0;
  4527. t0 = temp;
  4528. }
  4529. if (t0 > 1.0 || t1 < 0.0)
  4530. return;
  4531. if (t0 < 0)
  4532. t0 = 0;
  4533. if (t0 > 1.0)
  4534. t0 = 1.0;
  4535. }
  4536. this._collisionPoint.copyFromFloats(0, 0, 0);
  4537. var found = false;
  4538. var t = 1.0;
  4539. if (!embeddedInPlane) {
  4540. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4541. this.velocity.scaleToRef(t0, this._tempVector);
  4542. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4543. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4544. found = true;
  4545. t = t0;
  4546. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4547. }
  4548. }
  4549. if (!found) {
  4550. var velocitySquaredLength = this.velocity.lengthSquared();
  4551. var a = velocitySquaredLength;
  4552. this.basePoint.subtractToRef(p1, this._tempVector);
  4553. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4554. var c = this._tempVector.lengthSquared() - 1.0;
  4555. var lowestRoot = getLowestRoot(a, b, c, t);
  4556. if (lowestRoot.found) {
  4557. t = lowestRoot.root;
  4558. found = true;
  4559. this._collisionPoint.copyFrom(p1);
  4560. }
  4561. this.basePoint.subtractToRef(p2, this._tempVector);
  4562. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4563. c = this._tempVector.lengthSquared() - 1.0;
  4564. lowestRoot = getLowestRoot(a, b, c, t);
  4565. if (lowestRoot.found) {
  4566. t = lowestRoot.root;
  4567. found = true;
  4568. this._collisionPoint.copyFrom(p2);
  4569. }
  4570. this.basePoint.subtractToRef(p3, this._tempVector);
  4571. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4572. c = this._tempVector.lengthSquared() - 1.0;
  4573. lowestRoot = getLowestRoot(a, b, c, t);
  4574. if (lowestRoot.found) {
  4575. t = lowestRoot.root;
  4576. found = true;
  4577. this._collisionPoint.copyFrom(p3);
  4578. }
  4579. p2.subtractToRef(p1, this._edge);
  4580. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4581. var edgeSquaredLength = this._edge.lengthSquared();
  4582. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4583. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4584. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4585. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4586. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4587. lowestRoot = getLowestRoot(a, b, c, t);
  4588. if (lowestRoot.found) {
  4589. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4590. if (f >= 0.0 && f <= 1.0) {
  4591. t = lowestRoot.root;
  4592. found = true;
  4593. this._edge.scaleInPlace(f);
  4594. p1.addToRef(this._edge, this._collisionPoint);
  4595. }
  4596. }
  4597. p3.subtractToRef(p2, this._edge);
  4598. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4599. edgeSquaredLength = this._edge.lengthSquared();
  4600. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4601. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4602. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4603. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4604. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4605. lowestRoot = getLowestRoot(a, b, c, t);
  4606. if (lowestRoot.found) {
  4607. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4608. if (f >= 0.0 && f <= 1.0) {
  4609. t = lowestRoot.root;
  4610. found = true;
  4611. this._edge.scaleInPlace(f);
  4612. p2.addToRef(this._edge, this._collisionPoint);
  4613. }
  4614. }
  4615. p1.subtractToRef(p3, this._edge);
  4616. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4617. edgeSquaredLength = this._edge.lengthSquared();
  4618. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4619. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4620. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4621. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4622. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4623. lowestRoot = getLowestRoot(a, b, c, t);
  4624. if (lowestRoot.found) {
  4625. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4626. if (f >= 0.0 && f <= 1.0) {
  4627. t = lowestRoot.root;
  4628. found = true;
  4629. this._edge.scaleInPlace(f);
  4630. p3.addToRef(this._edge, this._collisionPoint);
  4631. }
  4632. }
  4633. }
  4634. if (found) {
  4635. var distToCollision = t * this.velocity.length();
  4636. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4637. if (!this.intersectionPoint) {
  4638. this.intersectionPoint = this._collisionPoint.clone();
  4639. } else {
  4640. this.intersectionPoint.copyFrom(this._collisionPoint);
  4641. }
  4642. this.nearestDistance = distToCollision;
  4643. this.collisionFound = true;
  4644. this.collidedMesh = subMesh.getMesh();
  4645. }
  4646. }
  4647. };
  4648. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4649. for (var i = indexStart; i < indexEnd; i += 3) {
  4650. var p1 = pts[indices[i] - decal];
  4651. var p2 = pts[indices[i + 1] - decal];
  4652. var p3 = pts[indices[i + 2] - decal];
  4653. this._testTriangle(i, subMesh, p3, p2, p1);
  4654. }
  4655. };
  4656. Collider.prototype._getResponse = function (pos, vel) {
  4657. pos.addToRef(vel, this._destinationPoint);
  4658. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4659. this.basePoint.addToRef(vel, pos);
  4660. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4661. this._slidePlaneNormal.normalize();
  4662. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4663. pos.addInPlace(this._displacementVector);
  4664. this.intersectionPoint.addInPlace(this._displacementVector);
  4665. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4666. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4667. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4668. };
  4669. return Collider;
  4670. })();
  4671. BABYLON.Collider = Collider;
  4672. })(BABYLON || (BABYLON = {}));
  4673. var __extends = this.__extends || function (d, b) {
  4674. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4675. function __() { this.constructor = d; }
  4676. __.prototype = b.prototype;
  4677. d.prototype = new __();
  4678. };
  4679. var BABYLON;
  4680. (function (BABYLON) {
  4681. var Camera = (function (_super) {
  4682. __extends(Camera, _super);
  4683. function Camera(name, position, scene) {
  4684. _super.call(this, name, scene);
  4685. this.position = position;
  4686. this.upVector = BABYLON.Vector3.Up();
  4687. this.orthoLeft = null;
  4688. this.orthoRight = null;
  4689. this.orthoBottom = null;
  4690. this.orthoTop = null;
  4691. this.fov = 0.8;
  4692. this.minZ = 0.1;
  4693. this.maxZ = 1000.0;
  4694. this.inertia = 0.9;
  4695. this.mode = Camera.PERSPECTIVE_CAMERA;
  4696. this.isIntermediate = false;
  4697. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4698. this.subCameras = [];
  4699. this.layerMask = 0xFFFFFFFF;
  4700. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4701. this._projectionMatrix = new BABYLON.Matrix();
  4702. this._postProcesses = new Array();
  4703. this._postProcessesTakenIndices = [];
  4704. scene.cameras.push(this);
  4705. if (!scene.activeCamera) {
  4706. scene.activeCamera = this;
  4707. }
  4708. }
  4709. Camera.prototype._initCache = function () {
  4710. _super.prototype._initCache.call(this);
  4711. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4712. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4713. this._cache.mode = undefined;
  4714. this._cache.minZ = undefined;
  4715. this._cache.maxZ = undefined;
  4716. this._cache.fov = undefined;
  4717. this._cache.aspectRatio = undefined;
  4718. this._cache.orthoLeft = undefined;
  4719. this._cache.orthoRight = undefined;
  4720. this._cache.orthoBottom = undefined;
  4721. this._cache.orthoTop = undefined;
  4722. this._cache.renderWidth = undefined;
  4723. this._cache.renderHeight = undefined;
  4724. };
  4725. Camera.prototype._updateCache = function (ignoreParentClass) {
  4726. if (!ignoreParentClass) {
  4727. _super.prototype._updateCache.call(this);
  4728. }
  4729. var engine = this.getEngine();
  4730. this._cache.position.copyFrom(this.position);
  4731. this._cache.upVector.copyFrom(this.upVector);
  4732. this._cache.mode = this.mode;
  4733. this._cache.minZ = this.minZ;
  4734. this._cache.maxZ = this.maxZ;
  4735. this._cache.fov = this.fov;
  4736. this._cache.aspectRatio = engine.getAspectRatio(this);
  4737. this._cache.orthoLeft = this.orthoLeft;
  4738. this._cache.orthoRight = this.orthoRight;
  4739. this._cache.orthoBottom = this.orthoBottom;
  4740. this._cache.orthoTop = this.orthoTop;
  4741. this._cache.renderWidth = engine.getRenderWidth();
  4742. this._cache.renderHeight = engine.getRenderHeight();
  4743. };
  4744. Camera.prototype._updateFromScene = function () {
  4745. this.updateCache();
  4746. this._update();
  4747. };
  4748. Camera.prototype._isSynchronized = function () {
  4749. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4750. };
  4751. Camera.prototype._isSynchronizedViewMatrix = function () {
  4752. if (!_super.prototype._isSynchronized.call(this))
  4753. return false;
  4754. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4755. };
  4756. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4757. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4758. if (!check) {
  4759. return false;
  4760. }
  4761. var engine = this.getEngine();
  4762. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4763. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4764. } else {
  4765. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  4766. }
  4767. return check;
  4768. };
  4769. Camera.prototype.attachControl = function (element) {
  4770. };
  4771. Camera.prototype.detachControl = function (element) {
  4772. };
  4773. Camera.prototype._update = function () {
  4774. };
  4775. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4776. if (typeof insertAt === "undefined") { insertAt = null; }
  4777. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4778. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4779. return 0;
  4780. }
  4781. if (insertAt == null || insertAt < 0) {
  4782. this._postProcesses.push(postProcess);
  4783. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4784. return this._postProcesses.length - 1;
  4785. }
  4786. var add = 0;
  4787. if (this._postProcesses[insertAt]) {
  4788. var start = this._postProcesses.length - 1;
  4789. for (var i = start; i >= insertAt + 1; --i) {
  4790. this._postProcesses[i + 1] = this._postProcesses[i];
  4791. }
  4792. add = 1;
  4793. }
  4794. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4795. if (this._postProcessesTakenIndices[i] < insertAt) {
  4796. continue;
  4797. }
  4798. start = this._postProcessesTakenIndices.length - 1;
  4799. for (var j = start; j >= i; --j) {
  4800. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4801. }
  4802. this._postProcessesTakenIndices[i] = insertAt;
  4803. break;
  4804. }
  4805. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4806. this._postProcessesTakenIndices.push(insertAt);
  4807. }
  4808. var result = insertAt + add;
  4809. this._postProcesses[result] = postProcess;
  4810. return result;
  4811. };
  4812. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4813. if (typeof atIndices === "undefined") { atIndices = null; }
  4814. var result = [];
  4815. if (!atIndices) {
  4816. var length = this._postProcesses.length;
  4817. for (var i = 0; i < length; i++) {
  4818. if (this._postProcesses[i] !== postProcess) {
  4819. continue;
  4820. }
  4821. delete this._postProcesses[i];
  4822. var index = this._postProcessesTakenIndices.indexOf(i);
  4823. this._postProcessesTakenIndices.splice(index, 1);
  4824. }
  4825. } else {
  4826. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4827. for (i = 0; i < atIndices.length; i++) {
  4828. var foundPostProcess = this._postProcesses[atIndices[i]];
  4829. if (foundPostProcess !== postProcess) {
  4830. result.push(i);
  4831. continue;
  4832. }
  4833. delete this._postProcesses[atIndices[i]];
  4834. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4835. this._postProcessesTakenIndices.splice(index, 1);
  4836. }
  4837. }
  4838. return result;
  4839. };
  4840. Camera.prototype.getWorldMatrix = function () {
  4841. if (!this._worldMatrix) {
  4842. this._worldMatrix = BABYLON.Matrix.Identity();
  4843. }
  4844. var viewMatrix = this.getViewMatrix();
  4845. viewMatrix.invertToRef(this._worldMatrix);
  4846. return this._worldMatrix;
  4847. };
  4848. Camera.prototype._getViewMatrix = function () {
  4849. return BABYLON.Matrix.Identity();
  4850. };
  4851. Camera.prototype.getViewMatrix = function () {
  4852. this._computedViewMatrix = this._computeViewMatrix();
  4853. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4854. return this._computedViewMatrix;
  4855. }
  4856. if (!this._worldMatrix) {
  4857. this._worldMatrix = BABYLON.Matrix.Identity();
  4858. }
  4859. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4860. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4861. this._computedViewMatrix.invert();
  4862. this._currentRenderId = this.getScene().getRenderId();
  4863. return this._computedViewMatrix;
  4864. };
  4865. Camera.prototype._computeViewMatrix = function (force) {
  4866. if (!force && this._isSynchronizedViewMatrix()) {
  4867. return this._computedViewMatrix;
  4868. }
  4869. this._computedViewMatrix = this._getViewMatrix();
  4870. if (!this.parent || !this.parent.getWorldMatrix) {
  4871. this._currentRenderId = this.getScene().getRenderId();
  4872. }
  4873. return this._computedViewMatrix;
  4874. };
  4875. Camera.prototype.getProjectionMatrix = function (force) {
  4876. if (!force && this._isSynchronizedProjectionMatrix()) {
  4877. return this._projectionMatrix;
  4878. }
  4879. var engine = this.getEngine();
  4880. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4881. if (this.minZ <= 0) {
  4882. this.minZ = 0.1;
  4883. }
  4884. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4885. return this._projectionMatrix;
  4886. }
  4887. var halfWidth = engine.getRenderWidth() / 2.0;
  4888. var halfHeight = engine.getRenderHeight() / 2.0;
  4889. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4890. return this._projectionMatrix;
  4891. };
  4892. Camera.prototype.dispose = function () {
  4893. var index = this.getScene().cameras.indexOf(this);
  4894. this.getScene().cameras.splice(index, 1);
  4895. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4896. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4897. }
  4898. };
  4899. Camera.PERSPECTIVE_CAMERA = 0;
  4900. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4901. return Camera;
  4902. })(BABYLON.Node);
  4903. BABYLON.Camera = Camera;
  4904. })(BABYLON || (BABYLON = {}));
  4905. var __extends = this.__extends || function (d, b) {
  4906. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4907. function __() { this.constructor = d; }
  4908. __.prototype = b.prototype;
  4909. d.prototype = new __();
  4910. };
  4911. var BABYLON;
  4912. (function (BABYLON) {
  4913. var TargetCamera = (function (_super) {
  4914. __extends(TargetCamera, _super);
  4915. function TargetCamera(name, position, scene) {
  4916. _super.call(this, name, position, scene);
  4917. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4918. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4919. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4920. this.speed = 2.0;
  4921. this.noRotationConstraint = false;
  4922. this.lockedTarget = null;
  4923. this._currentTarget = BABYLON.Vector3.Zero();
  4924. this._viewMatrix = BABYLON.Matrix.Zero();
  4925. this._camMatrix = BABYLON.Matrix.Zero();
  4926. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4927. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4928. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4929. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4930. this._lookAtTemp = BABYLON.Matrix.Zero();
  4931. this._tempMatrix = BABYLON.Matrix.Zero();
  4932. }
  4933. TargetCamera.prototype._getLockedTargetPosition = function () {
  4934. if (!this.lockedTarget) {
  4935. return null;
  4936. }
  4937. return this.lockedTarget.position || this.lockedTarget;
  4938. };
  4939. TargetCamera.prototype._initCache = function () {
  4940. _super.prototype._initCache.call(this);
  4941. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4942. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4943. };
  4944. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  4945. if (!ignoreParentClass) {
  4946. _super.prototype._updateCache.call(this);
  4947. }
  4948. var lockedTargetPosition = this._getLockedTargetPosition();
  4949. if (!lockedTargetPosition) {
  4950. this._cache.lockedTarget = null;
  4951. } else {
  4952. if (!this._cache.lockedTarget) {
  4953. this._cache.lockedTarget = lockedTargetPosition.clone();
  4954. } else {
  4955. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  4956. }
  4957. }
  4958. this._cache.rotation.copyFrom(this.rotation);
  4959. };
  4960. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  4961. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  4962. return false;
  4963. }
  4964. var lockedTargetPosition = this._getLockedTargetPosition();
  4965. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  4966. };
  4967. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  4968. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  4969. };
  4970. TargetCamera.prototype.setTarget = function (target) {
  4971. this.upVector.normalize();
  4972. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  4973. this._camMatrix.invert();
  4974. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  4975. var vDir = target.subtract(this.position);
  4976. if (vDir.x >= 0.0) {
  4977. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  4978. } else {
  4979. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  4980. }
  4981. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  4982. if (isNaN(this.rotation.x)) {
  4983. this.rotation.x = 0;
  4984. }
  4985. if (isNaN(this.rotation.y)) {
  4986. this.rotation.y = 0;
  4987. }
  4988. if (isNaN(this.rotation.z)) {
  4989. this.rotation.z = 0;
  4990. }
  4991. };
  4992. TargetCamera.prototype.getTarget = function () {
  4993. return this._currentTarget;
  4994. };
  4995. TargetCamera.prototype._decideIfNeedsToMove = function () {
  4996. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  4997. };
  4998. TargetCamera.prototype._updatePosition = function () {
  4999. this.position.addInPlace(this.cameraDirection);
  5000. };
  5001. TargetCamera.prototype._update = function () {
  5002. var needToMove = this._decideIfNeedsToMove();
  5003. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5004. if (needToMove) {
  5005. this._updatePosition();
  5006. }
  5007. if (needToRotate) {
  5008. this.rotation.x += this.cameraRotation.x;
  5009. this.rotation.y += this.cameraRotation.y;
  5010. if (!this.noRotationConstraint) {
  5011. var limit = (Math.PI / 2) * 0.95;
  5012. if (this.rotation.x > limit)
  5013. this.rotation.x = limit;
  5014. if (this.rotation.x < -limit)
  5015. this.rotation.x = -limit;
  5016. }
  5017. }
  5018. if (needToMove) {
  5019. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5020. this.cameraDirection.x = 0;
  5021. }
  5022. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5023. this.cameraDirection.y = 0;
  5024. }
  5025. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5026. this.cameraDirection.z = 0;
  5027. }
  5028. this.cameraDirection.scaleInPlace(this.inertia);
  5029. }
  5030. if (needToRotate) {
  5031. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5032. this.cameraRotation.x = 0;
  5033. }
  5034. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5035. this.cameraRotation.y = 0;
  5036. }
  5037. this.cameraRotation.scaleInPlace(this.inertia);
  5038. }
  5039. };
  5040. TargetCamera.prototype._getViewMatrix = function () {
  5041. if (!this.lockedTarget) {
  5042. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5043. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5044. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5045. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5046. this._lookAtTemp.invert();
  5047. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5048. } else {
  5049. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5050. }
  5051. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5052. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5053. } else {
  5054. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5055. }
  5056. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5057. return this._viewMatrix;
  5058. };
  5059. return TargetCamera;
  5060. })(BABYLON.Camera);
  5061. BABYLON.TargetCamera = TargetCamera;
  5062. })(BABYLON || (BABYLON = {}));
  5063. var __extends = this.__extends || function (d, b) {
  5064. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5065. function __() { this.constructor = d; }
  5066. __.prototype = b.prototype;
  5067. d.prototype = new __();
  5068. };
  5069. var BABYLON;
  5070. (function (BABYLON) {
  5071. var FollowCamera = (function (_super) {
  5072. __extends(FollowCamera, _super);
  5073. function FollowCamera(name, position, scene) {
  5074. _super.call(this, name, position, scene);
  5075. this.radius = 12;
  5076. this.rotationOffset = 0;
  5077. this.heightOffset = 4;
  5078. this.cameraAcceleration = 0.05;
  5079. this.maxCameraSpeed = 20;
  5080. }
  5081. FollowCamera.prototype.getRadians = function (degrees) {
  5082. return degrees * Math.PI / 180;
  5083. };
  5084. FollowCamera.prototype.follow = function (cameraTarget) {
  5085. if (!cameraTarget)
  5086. return;
  5087. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5088. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5089. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5090. var dx = targetX - this.position.x;
  5091. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5092. var dz = (targetZ) - this.position.z;
  5093. var vx = dx * this.cameraAcceleration * 2;
  5094. var vy = dy * this.cameraAcceleration;
  5095. var vz = dz * this.cameraAcceleration * 2;
  5096. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5097. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5098. }
  5099. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5100. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5101. }
  5102. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5103. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5104. }
  5105. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5106. this.setTarget(cameraTarget.position);
  5107. };
  5108. FollowCamera.prototype._update = function () {
  5109. _super.prototype._update.call(this);
  5110. this.follow(this.target);
  5111. };
  5112. return FollowCamera;
  5113. })(BABYLON.TargetCamera);
  5114. BABYLON.FollowCamera = FollowCamera;
  5115. })(BABYLON || (BABYLON = {}));
  5116. var __extends = this.__extends || function (d, b) {
  5117. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5118. function __() { this.constructor = d; }
  5119. __.prototype = b.prototype;
  5120. d.prototype = new __();
  5121. };
  5122. var BABYLON;
  5123. (function (BABYLON) {
  5124. var FreeCamera = (function (_super) {
  5125. __extends(FreeCamera, _super);
  5126. function FreeCamera(name, position, scene) {
  5127. _super.call(this, name, position, scene);
  5128. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5129. this.keysUp = [38];
  5130. this.keysDown = [40];
  5131. this.keysLeft = [37];
  5132. this.keysRight = [39];
  5133. this.checkCollisions = false;
  5134. this.applyGravity = false;
  5135. this.angularSensibility = 2000.0;
  5136. this._keys = [];
  5137. this._collider = new BABYLON.Collider();
  5138. this._needMoveForGravity = true;
  5139. this._oldPosition = BABYLON.Vector3.Zero();
  5140. this._diffPosition = BABYLON.Vector3.Zero();
  5141. this._newPosition = BABYLON.Vector3.Zero();
  5142. }
  5143. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5144. var _this = this;
  5145. var previousPosition;
  5146. var engine = this.getEngine();
  5147. if (this._attachedElement) {
  5148. return;
  5149. }
  5150. this._attachedElement = element;
  5151. if (this._onMouseDown === undefined) {
  5152. this._onMouseDown = function (evt) {
  5153. previousPosition = {
  5154. x: evt.clientX,
  5155. y: evt.clientY
  5156. };
  5157. if (!noPreventDefault) {
  5158. evt.preventDefault();
  5159. }
  5160. };
  5161. this._onMouseUp = function (evt) {
  5162. previousPosition = null;
  5163. if (!noPreventDefault) {
  5164. evt.preventDefault();
  5165. }
  5166. };
  5167. this._onMouseOut = function (evt) {
  5168. previousPosition = null;
  5169. _this._keys = [];
  5170. if (!noPreventDefault) {
  5171. evt.preventDefault();
  5172. }
  5173. };
  5174. this._onMouseMove = function (evt) {
  5175. if (!previousPosition && !engine.isPointerLock) {
  5176. return;
  5177. }
  5178. var offsetX;
  5179. var offsetY;
  5180. if (!engine.isPointerLock) {
  5181. offsetX = evt.clientX - previousPosition.x;
  5182. offsetY = evt.clientY - previousPosition.y;
  5183. } else {
  5184. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5185. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5186. }
  5187. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5188. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5189. previousPosition = {
  5190. x: evt.clientX,
  5191. y: evt.clientY
  5192. };
  5193. if (!noPreventDefault) {
  5194. evt.preventDefault();
  5195. }
  5196. };
  5197. this._onKeyDown = function (evt) {
  5198. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5199. var index = _this._keys.indexOf(evt.keyCode);
  5200. if (index === -1) {
  5201. _this._keys.push(evt.keyCode);
  5202. }
  5203. if (!noPreventDefault) {
  5204. evt.preventDefault();
  5205. }
  5206. }
  5207. };
  5208. this._onKeyUp = function (evt) {
  5209. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5210. var index = _this._keys.indexOf(evt.keyCode);
  5211. if (index >= 0) {
  5212. _this._keys.splice(index, 1);
  5213. }
  5214. if (!noPreventDefault) {
  5215. evt.preventDefault();
  5216. }
  5217. }
  5218. };
  5219. this._onLostFocus = function () {
  5220. _this._keys = [];
  5221. };
  5222. this._reset = function () {
  5223. _this._keys = [];
  5224. previousPosition = null;
  5225. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5226. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5227. };
  5228. }
  5229. element.addEventListener("mousedown", this._onMouseDown, false);
  5230. element.addEventListener("mouseup", this._onMouseUp, false);
  5231. element.addEventListener("mouseout", this._onMouseOut, false);
  5232. element.addEventListener("mousemove", this._onMouseMove, false);
  5233. BABYLON.Tools.RegisterTopRootEvents([
  5234. { name: "keydown", handler: this._onKeyDown },
  5235. { name: "keyup", handler: this._onKeyUp },
  5236. { name: "blur", handler: this._onLostFocus }
  5237. ]);
  5238. };
  5239. FreeCamera.prototype.detachControl = function (element) {
  5240. if (this._attachedElement != element) {
  5241. return;
  5242. }
  5243. element.removeEventListener("mousedown", this._onMouseDown);
  5244. element.removeEventListener("mouseup", this._onMouseUp);
  5245. element.removeEventListener("mouseout", this._onMouseOut);
  5246. element.removeEventListener("mousemove", this._onMouseMove);
  5247. BABYLON.Tools.UnregisterTopRootEvents([
  5248. { name: "keydown", handler: this._onKeyDown },
  5249. { name: "keyup", handler: this._onKeyUp },
  5250. { name: "blur", handler: this._onLostFocus }
  5251. ]);
  5252. this._attachedElement = null;
  5253. if (this._reset) {
  5254. this._reset();
  5255. }
  5256. };
  5257. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5258. var globalPosition;
  5259. if (this.parent) {
  5260. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5261. } else {
  5262. globalPosition = this.position;
  5263. }
  5264. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5265. this._collider.radius = this.ellipsoid;
  5266. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5267. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5268. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5269. this.position.addInPlace(this._diffPosition);
  5270. if (this.onCollide) {
  5271. this.onCollide(this._collider.collidedMesh);
  5272. }
  5273. }
  5274. };
  5275. FreeCamera.prototype._checkInputs = function () {
  5276. if (!this._localDirection) {
  5277. this._localDirection = BABYLON.Vector3.Zero();
  5278. this._transformedDirection = BABYLON.Vector3.Zero();
  5279. }
  5280. for (var index = 0; index < this._keys.length; index++) {
  5281. var keyCode = this._keys[index];
  5282. var speed = this._computeLocalCameraSpeed();
  5283. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5284. this._localDirection.copyFromFloats(-speed, 0, 0);
  5285. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5286. this._localDirection.copyFromFloats(0, 0, speed);
  5287. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5288. this._localDirection.copyFromFloats(speed, 0, 0);
  5289. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5290. this._localDirection.copyFromFloats(0, 0, -speed);
  5291. }
  5292. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5293. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5294. this.cameraDirection.addInPlace(this._transformedDirection);
  5295. }
  5296. };
  5297. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5298. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5299. };
  5300. FreeCamera.prototype._updatePosition = function () {
  5301. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5302. this._collideWithWorld(this.cameraDirection);
  5303. if (this.applyGravity) {
  5304. var oldPosition = this.position;
  5305. this._collideWithWorld(this.getScene().gravity);
  5306. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5307. }
  5308. } else {
  5309. this.position.addInPlace(this.cameraDirection);
  5310. }
  5311. };
  5312. FreeCamera.prototype._update = function () {
  5313. this._checkInputs();
  5314. _super.prototype._update.call(this);
  5315. };
  5316. return FreeCamera;
  5317. })(BABYLON.TargetCamera);
  5318. BABYLON.FreeCamera = FreeCamera;
  5319. })(BABYLON || (BABYLON = {}));
  5320. var __extends = this.__extends || function (d, b) {
  5321. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5322. function __() { this.constructor = d; }
  5323. __.prototype = b.prototype;
  5324. d.prototype = new __();
  5325. };
  5326. var BABYLON;
  5327. (function (BABYLON) {
  5328. var TouchCamera = (function (_super) {
  5329. __extends(TouchCamera, _super);
  5330. function TouchCamera(name, position, scene) {
  5331. _super.call(this, name, position, scene);
  5332. this._offsetX = null;
  5333. this._offsetY = null;
  5334. this._pointerCount = 0;
  5335. this._pointerPressed = [];
  5336. this.angularSensibility = 200000.0;
  5337. this.moveSensibility = 500.0;
  5338. }
  5339. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5340. var _this = this;
  5341. var previousPosition;
  5342. if (this._attachedCanvas) {
  5343. return;
  5344. }
  5345. this._attachedCanvas = canvas;
  5346. if (this._onPointerDown === undefined) {
  5347. this._onPointerDown = function (evt) {
  5348. if (!noPreventDefault) {
  5349. evt.preventDefault();
  5350. }
  5351. _this._pointerPressed.push(evt.pointerId);
  5352. if (_this._pointerPressed.length !== 1) {
  5353. return;
  5354. }
  5355. previousPosition = {
  5356. x: evt.clientX,
  5357. y: evt.clientY
  5358. };
  5359. };
  5360. this._onPointerUp = function (evt) {
  5361. if (!noPreventDefault) {
  5362. evt.preventDefault();
  5363. }
  5364. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5365. if (index === -1) {
  5366. return;
  5367. }
  5368. _this._pointerPressed.splice(index, 1);
  5369. if (index != 0) {
  5370. return;
  5371. }
  5372. previousPosition = null;
  5373. _this._offsetX = null;
  5374. _this._offsetY = null;
  5375. };
  5376. this._onPointerMove = function (evt) {
  5377. if (!noPreventDefault) {
  5378. evt.preventDefault();
  5379. }
  5380. if (!previousPosition) {
  5381. return;
  5382. }
  5383. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5384. if (index != 0) {
  5385. return;
  5386. }
  5387. _this._offsetX = evt.clientX - previousPosition.x;
  5388. _this._offsetY = -(evt.clientY - previousPosition.y);
  5389. };
  5390. this._onLostFocus = function () {
  5391. _this._offsetX = null;
  5392. _this._offsetY = null;
  5393. };
  5394. }
  5395. canvas.addEventListener("pointerdown", this._onPointerDown);
  5396. canvas.addEventListener("pointerup", this._onPointerUp);
  5397. canvas.addEventListener("pointerout", this._onPointerUp);
  5398. canvas.addEventListener("pointermove", this._onPointerMove);
  5399. BABYLON.Tools.RegisterTopRootEvents([
  5400. { name: "blur", handler: this._onLostFocus }
  5401. ]);
  5402. };
  5403. TouchCamera.prototype.detachControl = function (canvas) {
  5404. if (this._attachedCanvas != canvas) {
  5405. return;
  5406. }
  5407. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5408. canvas.removeEventListener("pointerup", this._onPointerUp);
  5409. canvas.removeEventListener("pointerout", this._onPointerUp);
  5410. canvas.removeEventListener("pointermove", this._onPointerMove);
  5411. BABYLON.Tools.UnregisterTopRootEvents([
  5412. { name: "blur", handler: this._onLostFocus }
  5413. ]);
  5414. this._attachedCanvas = null;
  5415. };
  5416. TouchCamera.prototype._checkInputs = function () {
  5417. if (!this._offsetX) {
  5418. return;
  5419. }
  5420. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5421. if (this._pointerPressed.length > 1) {
  5422. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5423. } else {
  5424. var speed = this._computeLocalCameraSpeed();
  5425. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5426. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5427. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5428. }
  5429. };
  5430. return TouchCamera;
  5431. })(BABYLON.FreeCamera);
  5432. BABYLON.TouchCamera = TouchCamera;
  5433. })(BABYLON || (BABYLON = {}));
  5434. var __extends = this.__extends || function (d, b) {
  5435. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5436. function __() { this.constructor = d; }
  5437. __.prototype = b.prototype;
  5438. d.prototype = new __();
  5439. };
  5440. var BABYLON;
  5441. (function (BABYLON) {
  5442. var DeviceOrientationCamera = (function (_super) {
  5443. __extends(DeviceOrientationCamera, _super);
  5444. function DeviceOrientationCamera(name, position, scene) {
  5445. var _this = this;
  5446. _super.call(this, name, position, scene);
  5447. this._offsetX = null;
  5448. this._offsetY = null;
  5449. this._orientationGamma = 0;
  5450. this._orientationBeta = 0;
  5451. this._initialOrientationGamma = 0;
  5452. this._initialOrientationBeta = 0;
  5453. this.angularSensibility = 10000.0;
  5454. this.moveSensibility = 50.0;
  5455. window.addEventListener("resize", function () {
  5456. _this._initialOrientationGamma = null;
  5457. }, false);
  5458. }
  5459. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5460. var _this = this;
  5461. if (this._attachedCanvas) {
  5462. return;
  5463. }
  5464. this._attachedCanvas = canvas;
  5465. if (!this._orientationChanged) {
  5466. this._orientationChanged = function (evt) {
  5467. if (!_this._initialOrientationGamma) {
  5468. _this._initialOrientationGamma = evt.gamma;
  5469. _this._initialOrientationBeta = evt.beta;
  5470. }
  5471. _this._orientationGamma = evt.gamma;
  5472. _this._orientationBeta = evt.beta;
  5473. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5474. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5475. };
  5476. }
  5477. window.addEventListener("deviceorientation", this._orientationChanged);
  5478. };
  5479. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5480. if (this._attachedCanvas != canvas) {
  5481. return;
  5482. }
  5483. window.removeEventListener("deviceorientation", this._orientationChanged);
  5484. this._attachedCanvas = null;
  5485. this._orientationGamma = 0;
  5486. this._orientationBeta = 0;
  5487. this._initialOrientationGamma = 0;
  5488. this._initialOrientationBeta = 0;
  5489. };
  5490. DeviceOrientationCamera.prototype._checkInputs = function () {
  5491. if (!this._offsetX) {
  5492. return;
  5493. }
  5494. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5495. var speed = this._computeLocalCameraSpeed();
  5496. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5497. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5498. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5499. };
  5500. return DeviceOrientationCamera;
  5501. })(BABYLON.FreeCamera);
  5502. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5503. })(BABYLON || (BABYLON = {}));
  5504. var __extends = this.__extends || function (d, b) {
  5505. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5506. function __() { this.constructor = d; }
  5507. __.prototype = b.prototype;
  5508. d.prototype = new __();
  5509. };
  5510. var BABYLON;
  5511. (function (BABYLON) {
  5512. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5513. var ArcRotateCamera = (function (_super) {
  5514. __extends(ArcRotateCamera, _super);
  5515. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5516. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5517. this.alpha = alpha;
  5518. this.beta = beta;
  5519. this.radius = radius;
  5520. this.target = target;
  5521. this.inertialAlphaOffset = 0;
  5522. this.inertialBetaOffset = 0;
  5523. this.inertialRadiusOffset = 0;
  5524. this.lowerAlphaLimit = null;
  5525. this.upperAlphaLimit = null;
  5526. this.lowerBetaLimit = 0.01;
  5527. this.upperBetaLimit = Math.PI;
  5528. this.lowerRadiusLimit = null;
  5529. this.upperRadiusLimit = null;
  5530. this.angularSensibility = 1000.0;
  5531. this.wheelPrecision = 3.0;
  5532. this.keysUp = [38];
  5533. this.keysDown = [40];
  5534. this.keysLeft = [37];
  5535. this.keysRight = [39];
  5536. this.zoomOnFactor = 1;
  5537. this._keys = [];
  5538. this._viewMatrix = new BABYLON.Matrix();
  5539. this.checkCollisions = false;
  5540. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5541. this._collider = new BABYLON.Collider();
  5542. this._previousPosition = BABYLON.Vector3.Zero();
  5543. this._collisionVelocity = BABYLON.Vector3.Zero();
  5544. this._newPosition = BABYLON.Vector3.Zero();
  5545. this.getViewMatrix();
  5546. }
  5547. ArcRotateCamera.prototype._getTargetPosition = function () {
  5548. return this.target.position || this.target;
  5549. };
  5550. ArcRotateCamera.prototype._initCache = function () {
  5551. _super.prototype._initCache.call(this);
  5552. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5553. this._cache.alpha = undefined;
  5554. this._cache.beta = undefined;
  5555. this._cache.radius = undefined;
  5556. };
  5557. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5558. if (!ignoreParentClass) {
  5559. _super.prototype._updateCache.call(this);
  5560. }
  5561. this._cache.target.copyFrom(this._getTargetPosition());
  5562. this._cache.alpha = this.alpha;
  5563. this._cache.beta = this.beta;
  5564. this._cache.radius = this.radius;
  5565. };
  5566. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5567. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5568. return false;
  5569. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5570. };
  5571. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5572. var _this = this;
  5573. var previousPosition;
  5574. var pointerId;
  5575. if (this._attachedElement) {
  5576. return;
  5577. }
  5578. this._attachedElement = element;
  5579. var engine = this.getEngine();
  5580. if (this._onPointerDown === undefined) {
  5581. this._onPointerDown = function (evt) {
  5582. if (pointerId) {
  5583. return;
  5584. }
  5585. pointerId = evt.pointerId;
  5586. previousPosition = {
  5587. x: evt.clientX,
  5588. y: evt.clientY
  5589. };
  5590. if (!noPreventDefault) {
  5591. evt.preventDefault();
  5592. }
  5593. };
  5594. this._onPointerUp = function (evt) {
  5595. previousPosition = null;
  5596. pointerId = null;
  5597. if (!noPreventDefault) {
  5598. evt.preventDefault();
  5599. }
  5600. };
  5601. this._onPointerMove = function (evt) {
  5602. if (!previousPosition) {
  5603. return;
  5604. }
  5605. if (pointerId !== evt.pointerId) {
  5606. return;
  5607. }
  5608. var offsetX = evt.clientX - previousPosition.x;
  5609. var offsetY = evt.clientY - previousPosition.y;
  5610. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5611. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5612. previousPosition = {
  5613. x: evt.clientX,
  5614. y: evt.clientY
  5615. };
  5616. if (!noPreventDefault) {
  5617. evt.preventDefault();
  5618. }
  5619. };
  5620. this._onMouseMove = function (evt) {
  5621. if (!engine.isPointerLock) {
  5622. return;
  5623. }
  5624. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5625. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5626. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5627. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5628. if (!noPreventDefault) {
  5629. evt.preventDefault();
  5630. }
  5631. };
  5632. this._wheel = function (event) {
  5633. var delta = 0;
  5634. if (event.wheelDelta) {
  5635. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5636. } else if (event.detail) {
  5637. delta = -event.detail / _this.wheelPrecision;
  5638. }
  5639. if (delta)
  5640. _this.inertialRadiusOffset += delta;
  5641. if (event.preventDefault) {
  5642. if (!noPreventDefault) {
  5643. event.preventDefault();
  5644. }
  5645. }
  5646. };
  5647. this._onKeyDown = function (evt) {
  5648. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5649. var index = _this._keys.indexOf(evt.keyCode);
  5650. if (index === -1) {
  5651. _this._keys.push(evt.keyCode);
  5652. }
  5653. if (evt.preventDefault) {
  5654. if (!noPreventDefault) {
  5655. evt.preventDefault();
  5656. }
  5657. }
  5658. }
  5659. };
  5660. this._onKeyUp = function (evt) {
  5661. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5662. var index = _this._keys.indexOf(evt.keyCode);
  5663. if (index >= 0) {
  5664. _this._keys.splice(index, 1);
  5665. }
  5666. if (evt.preventDefault) {
  5667. if (!noPreventDefault) {
  5668. evt.preventDefault();
  5669. }
  5670. }
  5671. }
  5672. };
  5673. this._onLostFocus = function () {
  5674. _this._keys = [];
  5675. pointerId = null;
  5676. };
  5677. this._onGestureStart = function (e) {
  5678. if (window.MSGesture === undefined) {
  5679. return;
  5680. }
  5681. if (!_this._MSGestureHandler) {
  5682. _this._MSGestureHandler = new MSGesture();
  5683. _this._MSGestureHandler.target = element;
  5684. }
  5685. _this._MSGestureHandler.addPointer(e.pointerId);
  5686. };
  5687. this._onGesture = function (e) {
  5688. _this.radius *= e.scale;
  5689. if (e.preventDefault) {
  5690. if (!noPreventDefault) {
  5691. e.stopPropagation();
  5692. e.preventDefault();
  5693. }
  5694. }
  5695. };
  5696. this._reset = function () {
  5697. _this._keys = [];
  5698. _this.inertialAlphaOffset = 0;
  5699. _this.inertialBetaOffset = 0;
  5700. _this.inertialRadiusOffset = 0;
  5701. previousPosition = null;
  5702. pointerId = null;
  5703. };
  5704. }
  5705. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5706. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5707. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5708. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5709. element.addEventListener("mousemove", this._onMouseMove, false);
  5710. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5711. element.addEventListener("MSGestureChange", this._onGesture, false);
  5712. element.addEventListener('mousewheel', this._wheel, false);
  5713. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5714. BABYLON.Tools.RegisterTopRootEvents([
  5715. { name: "keydown", handler: this._onKeyDown },
  5716. { name: "keyup", handler: this._onKeyUp },
  5717. { name: "blur", handler: this._onLostFocus }
  5718. ]);
  5719. };
  5720. ArcRotateCamera.prototype.detachControl = function (element) {
  5721. if (this._attachedElement != element) {
  5722. return;
  5723. }
  5724. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5725. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5726. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5727. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5728. element.removeEventListener("mousemove", this._onMouseMove);
  5729. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5730. element.removeEventListener("MSGestureChange", this._onGesture);
  5731. element.removeEventListener('mousewheel', this._wheel);
  5732. element.removeEventListener('DOMMouseScroll', this._wheel);
  5733. BABYLON.Tools.UnregisterTopRootEvents([
  5734. { name: "keydown", handler: this._onKeyDown },
  5735. { name: "keyup", handler: this._onKeyUp },
  5736. { name: "blur", handler: this._onLostFocus }
  5737. ]);
  5738. this._MSGestureHandler = null;
  5739. this._attachedElement = null;
  5740. if (this._reset) {
  5741. this._reset();
  5742. }
  5743. };
  5744. ArcRotateCamera.prototype._update = function () {
  5745. for (var index = 0; index < this._keys.length; index++) {
  5746. var keyCode = this._keys[index];
  5747. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5748. this.inertialAlphaOffset -= 0.01;
  5749. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5750. this.inertialBetaOffset -= 0.01;
  5751. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5752. this.inertialAlphaOffset += 0.01;
  5753. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5754. this.inertialBetaOffset += 0.01;
  5755. }
  5756. }
  5757. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5758. this.alpha += this.inertialAlphaOffset;
  5759. this.beta += this.inertialBetaOffset;
  5760. this.radius -= this.inertialRadiusOffset;
  5761. this.inertialAlphaOffset *= this.inertia;
  5762. this.inertialBetaOffset *= this.inertia;
  5763. this.inertialRadiusOffset *= this.inertia;
  5764. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5765. this.inertialAlphaOffset = 0;
  5766. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5767. this.inertialBetaOffset = 0;
  5768. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5769. this.inertialRadiusOffset = 0;
  5770. }
  5771. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5772. this.alpha = this.lowerAlphaLimit;
  5773. }
  5774. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5775. this.alpha = this.upperAlphaLimit;
  5776. }
  5777. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5778. this.beta = this.lowerBetaLimit;
  5779. }
  5780. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5781. this.beta = this.upperBetaLimit;
  5782. }
  5783. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5784. this.radius = this.lowerRadiusLimit;
  5785. }
  5786. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5787. this.radius = this.upperRadiusLimit;
  5788. }
  5789. };
  5790. ArcRotateCamera.prototype.setPosition = function (position) {
  5791. var radiusv3 = position.subtract(this._getTargetPosition());
  5792. this.radius = radiusv3.length();
  5793. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5794. if (radiusv3.z < 0) {
  5795. this.alpha = 2 * Math.PI - this.alpha;
  5796. }
  5797. this.beta = Math.acos(radiusv3.y / this.radius);
  5798. };
  5799. ArcRotateCamera.prototype._getViewMatrix = function () {
  5800. var cosa = Math.cos(this.alpha);
  5801. var sina = Math.sin(this.alpha);
  5802. var cosb = Math.cos(this.beta);
  5803. var sinb = Math.sin(this.beta);
  5804. var target = this._getTargetPosition();
  5805. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5806. if (this.checkCollisions) {
  5807. this._collider.radius = this.collisionRadius;
  5808. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5809. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5810. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5811. this.position.copyFrom(this._previousPosition);
  5812. this.alpha = this._previousAlpha;
  5813. this.beta = this._previousBeta;
  5814. this.radius = this._previousRadius;
  5815. if (this.onCollide) {
  5816. this.onCollide(this._collider.collidedMesh);
  5817. }
  5818. }
  5819. }
  5820. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5821. this._previousAlpha = this.alpha;
  5822. this._previousBeta = this.beta;
  5823. this._previousRadius = this.radius;
  5824. this._previousPosition.copyFrom(this.position);
  5825. return this._viewMatrix;
  5826. };
  5827. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5828. meshes = meshes || this.getScene().meshes;
  5829. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5830. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5831. this.radius = distance * this.zoomOnFactor;
  5832. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5833. };
  5834. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5835. var meshesOrMinMaxVector;
  5836. var distance;
  5837. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5838. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5839. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5840. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5841. } else {
  5842. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5843. distance = meshesOrMinMaxVectorAndDistance.distance;
  5844. }
  5845. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5846. this.maxZ = distance * 2;
  5847. };
  5848. return ArcRotateCamera;
  5849. })(BABYLON.Camera);
  5850. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5851. })(BABYLON || (BABYLON = {}));
  5852. var BABYLON;
  5853. (function (BABYLON) {
  5854. var Scene = (function () {
  5855. function Scene(engine) {
  5856. this.autoClear = true;
  5857. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5858. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5859. this.forceWireframe = false;
  5860. this.cameraToUseForPointers = null;
  5861. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5862. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5863. this.fogDensity = 0.1;
  5864. this.fogStart = 0;
  5865. this.fogEnd = 1000.0;
  5866. this.lightsEnabled = true;
  5867. this.lights = new Array();
  5868. this.cameras = new Array();
  5869. this.activeCameras = new Array();
  5870. this.meshes = new Array();
  5871. this._geometries = new Array();
  5872. this.materials = new Array();
  5873. this.multiMaterials = new Array();
  5874. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5875. this.texturesEnabled = true;
  5876. this.textures = new Array();
  5877. this.particlesEnabled = true;
  5878. this.particleSystems = new Array();
  5879. this.spriteManagers = new Array();
  5880. this.layers = new Array();
  5881. this.skeletons = new Array();
  5882. this.lensFlareSystems = new Array();
  5883. this.collisionsEnabled = true;
  5884. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  5885. this.postProcessesEnabled = true;
  5886. this.renderTargetsEnabled = true;
  5887. this.customRenderTargets = new Array();
  5888. this.importedMeshesFiles = new Array();
  5889. this._actionManagers = new Array();
  5890. this._meshesForIntersections = new BABYLON.SmartArray(256);
  5891. this._totalVertices = 0;
  5892. this._activeVertices = 0;
  5893. this._activeParticles = 0;
  5894. this._lastFrameDuration = 0;
  5895. this._evaluateActiveMeshesDuration = 0;
  5896. this._renderTargetsDuration = 0;
  5897. this._particlesDuration = 0;
  5898. this._renderDuration = 0;
  5899. this._spritesDuration = 0;
  5900. this._animationRatio = 0;
  5901. this._renderId = 0;
  5902. this._executeWhenReadyTimeoutId = -1;
  5903. this._toBeDisposed = new BABYLON.SmartArray(256);
  5904. this._onReadyCallbacks = new Array();
  5905. this._pendingData = [];
  5906. this._onBeforeRenderCallbacks = new Array();
  5907. this._activeMeshes = new BABYLON.SmartArray(256);
  5908. this._processedMaterials = new BABYLON.SmartArray(256);
  5909. this._renderTargets = new BABYLON.SmartArray(256);
  5910. this._activeParticleSystems = new BABYLON.SmartArray(256);
  5911. this._activeSkeletons = new BABYLON.SmartArray(32);
  5912. this._activeAnimatables = new Array();
  5913. this._transformMatrix = BABYLON.Matrix.Zero();
  5914. this._scaledPosition = BABYLON.Vector3.Zero();
  5915. this._scaledVelocity = BABYLON.Vector3.Zero();
  5916. this._engine = engine;
  5917. engine.scenes.push(this);
  5918. this._renderingManager = new BABYLON.RenderingManager(this);
  5919. this.postProcessManager = new BABYLON.PostProcessManager(this);
  5920. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  5921. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  5922. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  5923. this.attachControl();
  5924. }
  5925. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  5926. get: function () {
  5927. return this._meshUnderPointer;
  5928. },
  5929. enumerable: true,
  5930. configurable: true
  5931. });
  5932. Object.defineProperty(Scene.prototype, "pointerX", {
  5933. get: function () {
  5934. return this._pointerX;
  5935. },
  5936. enumerable: true,
  5937. configurable: true
  5938. });
  5939. Object.defineProperty(Scene.prototype, "pointerY", {
  5940. get: function () {
  5941. return this._pointerY;
  5942. },
  5943. enumerable: true,
  5944. configurable: true
  5945. });
  5946. Scene.prototype.getBoundingBoxRenderer = function () {
  5947. return this._boundingBoxRenderer;
  5948. };
  5949. Scene.prototype.getOutlineRenderer = function () {
  5950. return this._outlineRenderer;
  5951. };
  5952. Scene.prototype.getEngine = function () {
  5953. return this._engine;
  5954. };
  5955. Scene.prototype.getTotalVertices = function () {
  5956. return this._totalVertices;
  5957. };
  5958. Scene.prototype.getActiveVertices = function () {
  5959. return this._activeVertices;
  5960. };
  5961. Scene.prototype.getActiveParticles = function () {
  5962. return this._activeParticles;
  5963. };
  5964. Scene.prototype.getLastFrameDuration = function () {
  5965. return this._lastFrameDuration;
  5966. };
  5967. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  5968. return this._evaluateActiveMeshesDuration;
  5969. };
  5970. Scene.prototype.getActiveMeshes = function () {
  5971. return this._activeMeshes;
  5972. };
  5973. Scene.prototype.getRenderTargetsDuration = function () {
  5974. return this._renderTargetsDuration;
  5975. };
  5976. Scene.prototype.getRenderDuration = function () {
  5977. return this._renderDuration;
  5978. };
  5979. Scene.prototype.getParticlesDuration = function () {
  5980. return this._particlesDuration;
  5981. };
  5982. Scene.prototype.getSpritesDuration = function () {
  5983. return this._spritesDuration;
  5984. };
  5985. Scene.prototype.getAnimationRatio = function () {
  5986. return this._animationRatio;
  5987. };
  5988. Scene.prototype.getRenderId = function () {
  5989. return this._renderId;
  5990. };
  5991. Scene.prototype._updatePointerPosition = function (evt) {
  5992. var canvasRect = this._engine.getRenderingCanvasClientRect();
  5993. this._pointerX = evt.clientX - canvasRect.left;
  5994. this._pointerY = evt.clientY - canvasRect.top;
  5995. if (this.cameraToUseForPointers) {
  5996. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  5997. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  5998. }
  5999. };
  6000. Scene.prototype.attachControl = function () {
  6001. var _this = this;
  6002. this._onPointerMove = function (evt) {
  6003. var canvas = _this._engine.getRenderingCanvas();
  6004. _this._updatePointerPosition(evt);
  6005. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6006. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6007. }, false, _this.cameraToUseForPointers);
  6008. if (pickResult.hit) {
  6009. _this._meshUnderPointer = pickResult.pickedMesh;
  6010. _this.setPointerOverMesh(pickResult.pickedMesh);
  6011. canvas.style.cursor = "pointer";
  6012. } else {
  6013. _this.setPointerOverMesh(null);
  6014. canvas.style.cursor = "";
  6015. _this._meshUnderPointer = null;
  6016. }
  6017. };
  6018. this._onPointerDown = function (evt) {
  6019. var predicate = null;
  6020. if (!_this.onPointerDown) {
  6021. predicate = function (mesh) {
  6022. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6023. };
  6024. }
  6025. _this._updatePointerPosition(evt);
  6026. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6027. if (pickResult.hit) {
  6028. if (pickResult.pickedMesh.actionManager) {
  6029. switch (evt.button) {
  6030. case 0:
  6031. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6032. break;
  6033. case 1:
  6034. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6035. break;
  6036. case 2:
  6037. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6038. break;
  6039. }
  6040. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6041. }
  6042. }
  6043. if (_this.onPointerDown) {
  6044. _this.onPointerDown(evt, pickResult);
  6045. }
  6046. };
  6047. this._onKeyDown = function (evt) {
  6048. if (_this.actionManager) {
  6049. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6050. }
  6051. };
  6052. this._onKeyUp = function (evt) {
  6053. if (_this.actionManager) {
  6054. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6055. }
  6056. };
  6057. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6058. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6059. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6060. window.addEventListener("keydown", this._onKeyDown, false);
  6061. window.addEventListener("keyup", this._onKeyUp, false);
  6062. };
  6063. Scene.prototype.detachControl = function () {
  6064. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6065. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6066. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6067. window.removeEventListener("keydown", this._onKeyDown);
  6068. window.removeEventListener("keyup", this._onKeyUp);
  6069. };
  6070. Scene.prototype.isReady = function () {
  6071. if (this._pendingData.length > 0) {
  6072. return false;
  6073. }
  6074. for (var index = 0; index < this._geometries.length; index++) {
  6075. var geometry = this._geometries[index];
  6076. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6077. return false;
  6078. }
  6079. }
  6080. for (index = 0; index < this.meshes.length; index++) {
  6081. var mesh = this.meshes[index];
  6082. if (!mesh.isReady()) {
  6083. return false;
  6084. }
  6085. var mat = mesh.material;
  6086. if (mat) {
  6087. if (!mat.isReady(mesh)) {
  6088. return false;
  6089. }
  6090. }
  6091. }
  6092. return true;
  6093. };
  6094. Scene.prototype.registerBeforeRender = function (func) {
  6095. this._onBeforeRenderCallbacks.push(func);
  6096. };
  6097. Scene.prototype.unregisterBeforeRender = function (func) {
  6098. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6099. if (index > -1) {
  6100. this._onBeforeRenderCallbacks.splice(index, 1);
  6101. }
  6102. };
  6103. Scene.prototype._addPendingData = function (data) {
  6104. this._pendingData.push(data);
  6105. };
  6106. Scene.prototype._removePendingData = function (data) {
  6107. var index = this._pendingData.indexOf(data);
  6108. if (index !== -1) {
  6109. this._pendingData.splice(index, 1);
  6110. }
  6111. };
  6112. Scene.prototype.getWaitingItemsCount = function () {
  6113. return this._pendingData.length;
  6114. };
  6115. Scene.prototype.executeWhenReady = function (func) {
  6116. var _this = this;
  6117. this._onReadyCallbacks.push(func);
  6118. if (this._executeWhenReadyTimeoutId !== -1) {
  6119. return;
  6120. }
  6121. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6122. _this._checkIsReady();
  6123. }, 150);
  6124. };
  6125. Scene.prototype._checkIsReady = function () {
  6126. var _this = this;
  6127. if (this.isReady()) {
  6128. this._onReadyCallbacks.forEach(function (func) {
  6129. func();
  6130. });
  6131. this._onReadyCallbacks = [];
  6132. this._executeWhenReadyTimeoutId = -1;
  6133. return;
  6134. }
  6135. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6136. _this._checkIsReady();
  6137. }, 150);
  6138. };
  6139. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6140. if (speedRatio === undefined) {
  6141. speedRatio = 1.0;
  6142. }
  6143. this.stopAnimation(target);
  6144. if (!animatable) {
  6145. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6146. }
  6147. if (target.animations) {
  6148. animatable.appendAnimations(target, target.animations);
  6149. }
  6150. if (target.getAnimatables) {
  6151. var animatables = target.getAnimatables();
  6152. for (var index = 0; index < animatables.length; index++) {
  6153. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6154. }
  6155. }
  6156. return animatable;
  6157. };
  6158. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6159. if (speedRatio === undefined) {
  6160. speedRatio = 1.0;
  6161. }
  6162. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6163. return animatable;
  6164. };
  6165. Scene.prototype.getAnimatableByTarget = function (target) {
  6166. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6167. if (this._activeAnimatables[index].target === target) {
  6168. return this._activeAnimatables[index];
  6169. }
  6170. }
  6171. return null;
  6172. };
  6173. Scene.prototype.stopAnimation = function (target) {
  6174. var animatable = this.getAnimatableByTarget(target);
  6175. if (animatable) {
  6176. animatable.stop();
  6177. }
  6178. };
  6179. Scene.prototype._animate = function () {
  6180. if (!this._animationStartDate) {
  6181. this._animationStartDate = new Date().getTime();
  6182. }
  6183. var now = new Date().getTime();
  6184. var delay = now - this._animationStartDate;
  6185. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6186. if (!this._activeAnimatables[index]._animate(delay)) {
  6187. this._activeAnimatables.splice(index, 1);
  6188. index--;
  6189. }
  6190. }
  6191. };
  6192. Scene.prototype.getViewMatrix = function () {
  6193. return this._viewMatrix;
  6194. };
  6195. Scene.prototype.getProjectionMatrix = function () {
  6196. return this._projectionMatrix;
  6197. };
  6198. Scene.prototype.getTransformMatrix = function () {
  6199. return this._transformMatrix;
  6200. };
  6201. Scene.prototype.setTransformMatrix = function (view, projection) {
  6202. this._viewMatrix = view;
  6203. this._projectionMatrix = projection;
  6204. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6205. };
  6206. Scene.prototype.setActiveCameraByID = function (id) {
  6207. var camera = this.getCameraByID(id);
  6208. if (camera) {
  6209. this.activeCamera = camera;
  6210. return camera;
  6211. }
  6212. return null;
  6213. };
  6214. Scene.prototype.setActiveCameraByName = function (name) {
  6215. var camera = this.getCameraByName(name);
  6216. if (camera) {
  6217. this.activeCamera = camera;
  6218. return camera;
  6219. }
  6220. return null;
  6221. };
  6222. Scene.prototype.getMaterialByID = function (id) {
  6223. for (var index = 0; index < this.materials.length; index++) {
  6224. if (this.materials[index].id === id) {
  6225. return this.materials[index];
  6226. }
  6227. }
  6228. return null;
  6229. };
  6230. Scene.prototype.getMaterialByName = function (name) {
  6231. for (var index = 0; index < this.materials.length; index++) {
  6232. if (this.materials[index].name === name) {
  6233. return this.materials[index];
  6234. }
  6235. }
  6236. return null;
  6237. };
  6238. Scene.prototype.getCameraByID = function (id) {
  6239. for (var index = 0; index < this.cameras.length; index++) {
  6240. if (this.cameras[index].id === id) {
  6241. return this.cameras[index];
  6242. }
  6243. }
  6244. return null;
  6245. };
  6246. Scene.prototype.getCameraByName = function (name) {
  6247. for (var index = 0; index < this.cameras.length; index++) {
  6248. if (this.cameras[index].name === name) {
  6249. return this.cameras[index];
  6250. }
  6251. }
  6252. return null;
  6253. };
  6254. Scene.prototype.getLightByName = function (name) {
  6255. for (var index = 0; index < this.lights.length; index++) {
  6256. if (this.lights[index].name === name) {
  6257. return this.lights[index];
  6258. }
  6259. }
  6260. return null;
  6261. };
  6262. Scene.prototype.getLightByID = function (id) {
  6263. for (var index = 0; index < this.lights.length; index++) {
  6264. if (this.lights[index].id === id) {
  6265. return this.lights[index];
  6266. }
  6267. }
  6268. return null;
  6269. };
  6270. Scene.prototype.getGeometryByID = function (id) {
  6271. for (var index = 0; index < this._geometries.length; index++) {
  6272. if (this._geometries[index].id === id) {
  6273. return this._geometries[index];
  6274. }
  6275. }
  6276. return null;
  6277. };
  6278. Scene.prototype.pushGeometry = function (geometry, force) {
  6279. if (!force && this.getGeometryByID(geometry.id)) {
  6280. return false;
  6281. }
  6282. this._geometries.push(geometry);
  6283. return true;
  6284. };
  6285. Scene.prototype.getGeometries = function () {
  6286. return this._geometries;
  6287. };
  6288. Scene.prototype.getMeshByID = function (id) {
  6289. for (var index = 0; index < this.meshes.length; index++) {
  6290. if (this.meshes[index].id === id) {
  6291. return this.meshes[index];
  6292. }
  6293. }
  6294. return null;
  6295. };
  6296. Scene.prototype.getLastMeshByID = function (id) {
  6297. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6298. if (this.meshes[index].id === id) {
  6299. return this.meshes[index];
  6300. }
  6301. }
  6302. return null;
  6303. };
  6304. Scene.prototype.getLastEntryByID = function (id) {
  6305. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6306. if (this.meshes[index].id === id) {
  6307. return this.meshes[index];
  6308. }
  6309. }
  6310. for (index = this.cameras.length - 1; index >= 0; index--) {
  6311. if (this.cameras[index].id === id) {
  6312. return this.cameras[index];
  6313. }
  6314. }
  6315. for (index = this.lights.length - 1; index >= 0; index--) {
  6316. if (this.lights[index].id === id) {
  6317. return this.lights[index];
  6318. }
  6319. }
  6320. return null;
  6321. };
  6322. Scene.prototype.getMeshByName = function (name) {
  6323. for (var index = 0; index < this.meshes.length; index++) {
  6324. if (this.meshes[index].name === name) {
  6325. return this.meshes[index];
  6326. }
  6327. }
  6328. return null;
  6329. };
  6330. Scene.prototype.getLastSkeletonByID = function (id) {
  6331. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6332. if (this.skeletons[index].id === id) {
  6333. return this.skeletons[index];
  6334. }
  6335. }
  6336. return null;
  6337. };
  6338. Scene.prototype.getSkeletonById = function (id) {
  6339. for (var index = 0; index < this.skeletons.length; index++) {
  6340. if (this.skeletons[index].id === id) {
  6341. return this.skeletons[index];
  6342. }
  6343. }
  6344. return null;
  6345. };
  6346. Scene.prototype.getSkeletonByName = function (name) {
  6347. for (var index = 0; index < this.skeletons.length; index++) {
  6348. if (this.skeletons[index].name === name) {
  6349. return this.skeletons[index];
  6350. }
  6351. }
  6352. return null;
  6353. };
  6354. Scene.prototype.isActiveMesh = function (mesh) {
  6355. return (this._activeMeshes.indexOf(mesh) !== -1);
  6356. };
  6357. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6358. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6359. var material = subMesh.getMaterial();
  6360. if (mesh.showSubMeshesBoundingBox) {
  6361. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6362. }
  6363. if (material) {
  6364. if (material.getRenderTargetTextures) {
  6365. if (this._processedMaterials.indexOf(material) === -1) {
  6366. this._processedMaterials.push(material);
  6367. this._renderTargets.concat(material.getRenderTargetTextures());
  6368. }
  6369. }
  6370. this._activeVertices += subMesh.verticesCount;
  6371. this._renderingManager.dispatch(subMesh);
  6372. }
  6373. }
  6374. };
  6375. Scene.prototype._evaluateActiveMeshes = function () {
  6376. this._activeMeshes.reset();
  6377. this._renderingManager.reset();
  6378. this._processedMaterials.reset();
  6379. this._activeParticleSystems.reset();
  6380. this._activeSkeletons.reset();
  6381. this._boundingBoxRenderer.reset();
  6382. if (!this._frustumPlanes) {
  6383. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6384. } else {
  6385. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6386. }
  6387. var meshes;
  6388. var len;
  6389. if (this._selectionOctree) {
  6390. var selection = this._selectionOctree.select(this._frustumPlanes);
  6391. meshes = selection.data;
  6392. len = selection.length;
  6393. } else {
  6394. len = this.meshes.length;
  6395. meshes = this.meshes;
  6396. }
  6397. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6398. var mesh = meshes[meshIndex];
  6399. this._totalVertices += mesh.getTotalVertices();
  6400. if (!mesh.isReady()) {
  6401. continue;
  6402. }
  6403. mesh.computeWorldMatrix();
  6404. mesh._preActivate();
  6405. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6406. this._meshesForIntersections.pushNoDuplicate(mesh);
  6407. }
  6408. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6409. this._activeMeshes.push(mesh);
  6410. mesh._activate(this._renderId);
  6411. this._activeMesh(mesh);
  6412. }
  6413. }
  6414. var beforeParticlesDate = new Date().getTime();
  6415. if (this.particlesEnabled) {
  6416. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6417. var particleSystem = this.particleSystems[particleIndex];
  6418. if (!particleSystem.isStarted()) {
  6419. continue;
  6420. }
  6421. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6422. this._activeParticleSystems.push(particleSystem);
  6423. particleSystem.animate();
  6424. }
  6425. }
  6426. }
  6427. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6428. };
  6429. Scene.prototype._activeMesh = function (mesh) {
  6430. if (mesh.skeleton) {
  6431. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6432. }
  6433. if (mesh.showBoundingBox) {
  6434. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6435. }
  6436. if (mesh.subMeshes) {
  6437. var len;
  6438. var subMeshes;
  6439. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6440. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6441. len = intersections.length;
  6442. subMeshes = intersections.data;
  6443. } else {
  6444. subMeshes = mesh.subMeshes;
  6445. len = subMeshes.length;
  6446. }
  6447. for (var subIndex = 0; subIndex < len; subIndex++) {
  6448. var subMesh = subMeshes[subIndex];
  6449. this._evaluateSubMesh(subMesh, mesh);
  6450. }
  6451. }
  6452. };
  6453. Scene.prototype.updateTransformMatrix = function (force) {
  6454. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6455. };
  6456. Scene.prototype._renderForCamera = function (camera) {
  6457. var engine = this._engine;
  6458. this.activeCamera = camera;
  6459. if (!this.activeCamera)
  6460. throw new Error("Active camera not set");
  6461. engine.setViewport(this.activeCamera.viewport);
  6462. this._renderId++;
  6463. this.updateTransformMatrix();
  6464. if (this.beforeCameraRender) {
  6465. this.beforeCameraRender(this.activeCamera);
  6466. }
  6467. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6468. this._evaluateActiveMeshes();
  6469. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6470. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6471. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6472. skeleton.prepare();
  6473. }
  6474. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6475. var renderTarget = this.customRenderTargets[customIndex];
  6476. this._renderTargets.push(renderTarget);
  6477. }
  6478. var beforeRenderTargetDate = new Date().getTime();
  6479. if (this.renderTargetsEnabled) {
  6480. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6481. renderTarget = this._renderTargets.data[renderIndex];
  6482. if (renderTarget._shouldRender()) {
  6483. this._renderId++;
  6484. renderTarget.render();
  6485. }
  6486. }
  6487. this._renderId++;
  6488. }
  6489. if (this._renderTargets.length > 0) {
  6490. engine.restoreDefaultFramebuffer();
  6491. }
  6492. this._renderTargetsDuration = new Date().getTime() - beforeRenderTargetDate;
  6493. this.postProcessManager._prepareFrame();
  6494. var beforeRenderDate = new Date().getTime();
  6495. if (this.layers.length) {
  6496. engine.setDepthBuffer(false);
  6497. var layerIndex;
  6498. var layer;
  6499. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6500. layer = this.layers[layerIndex];
  6501. if (layer.isBackground) {
  6502. layer.render();
  6503. }
  6504. }
  6505. engine.setDepthBuffer(true);
  6506. }
  6507. this._renderingManager.render(null, null, true, true);
  6508. this._boundingBoxRenderer.render();
  6509. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6510. this.lensFlareSystems[lensFlareSystemIndex].render();
  6511. }
  6512. if (this.layers.length) {
  6513. engine.setDepthBuffer(false);
  6514. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6515. layer = this.layers[layerIndex];
  6516. if (!layer.isBackground) {
  6517. layer.render();
  6518. }
  6519. }
  6520. engine.setDepthBuffer(true);
  6521. }
  6522. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6523. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6524. this.activeCamera._updateFromScene();
  6525. this._renderTargets.reset();
  6526. if (this.afterCameraRender) {
  6527. this.afterCameraRender(this.activeCamera);
  6528. }
  6529. };
  6530. Scene.prototype._processSubCameras = function (camera) {
  6531. if (camera.subCameras.length == 0) {
  6532. this._renderForCamera(camera);
  6533. return;
  6534. }
  6535. for (var index = 0; index < camera.subCameras.length; index++) {
  6536. this._renderForCamera(camera.subCameras[index]);
  6537. }
  6538. this.activeCamera = camera;
  6539. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6540. this.activeCamera._updateFromScene();
  6541. };
  6542. Scene.prototype._checkIntersections = function () {
  6543. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6544. var sourceMesh = this._meshesForIntersections.data[index];
  6545. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6546. var action = sourceMesh.actionManager.actions[actionIndex];
  6547. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6548. var otherMesh = action.getTriggerParameter();
  6549. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6550. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6551. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6552. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6553. sourceMesh._intersectionsInProgress.push(otherMesh);
  6554. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6555. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6556. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6557. if (indexOfOther > -1) {
  6558. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6559. }
  6560. }
  6561. }
  6562. }
  6563. }
  6564. };
  6565. Scene.prototype.render = function () {
  6566. var startDate = new Date().getTime();
  6567. this._particlesDuration = 0;
  6568. this._spritesDuration = 0;
  6569. this._activeParticles = 0;
  6570. this._renderDuration = 0;
  6571. this._evaluateActiveMeshesDuration = 0;
  6572. this._totalVertices = 0;
  6573. this._activeVertices = 0;
  6574. this._meshesForIntersections.reset();
  6575. if (this.actionManager) {
  6576. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6577. }
  6578. if (this.beforeRender) {
  6579. this.beforeRender();
  6580. }
  6581. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6582. this._onBeforeRenderCallbacks[callbackIndex]();
  6583. }
  6584. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6585. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6586. this._animate();
  6587. if (this._physicsEngine) {
  6588. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6589. }
  6590. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6591. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6592. var light = this.lights[lightIndex];
  6593. var shadowGenerator = light.getShadowGenerator();
  6594. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6595. this._renderTargets.push(shadowGenerator.getShadowMap());
  6596. }
  6597. }
  6598. this.postProcessRenderPipelineManager.update();
  6599. if (this.activeCameras.length > 0) {
  6600. var currentRenderId = this._renderId;
  6601. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6602. this._renderId = currentRenderId;
  6603. this._processSubCameras(this.activeCameras[cameraIndex]);
  6604. }
  6605. } else {
  6606. if (!this.activeCamera) {
  6607. throw new Error("No camera defined");
  6608. }
  6609. this._processSubCameras(this.activeCamera);
  6610. }
  6611. this._checkIntersections();
  6612. if (this.afterRender) {
  6613. this.afterRender();
  6614. }
  6615. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6616. this._toBeDisposed.data[index].dispose();
  6617. this._toBeDisposed[index] = null;
  6618. }
  6619. this._toBeDisposed.reset();
  6620. this._lastFrameDuration = new Date().getTime() - startDate;
  6621. };
  6622. Scene.prototype.dispose = function () {
  6623. this.beforeRender = null;
  6624. this.afterRender = null;
  6625. this.skeletons = [];
  6626. this._boundingBoxRenderer.dispose();
  6627. if (this.onDispose) {
  6628. this.onDispose();
  6629. }
  6630. this.detachControl();
  6631. var canvas = this._engine.getRenderingCanvas();
  6632. var index;
  6633. for (index = 0; index < this.cameras.length; index++) {
  6634. this.cameras[index].detachControl(canvas);
  6635. }
  6636. while (this.lights.length) {
  6637. this.lights[0].dispose();
  6638. }
  6639. while (this.meshes.length) {
  6640. this.meshes[0].dispose(true);
  6641. }
  6642. while (this.cameras.length) {
  6643. this.cameras[0].dispose();
  6644. }
  6645. while (this.materials.length) {
  6646. this.materials[0].dispose();
  6647. }
  6648. while (this.particleSystems.length) {
  6649. this.particleSystems[0].dispose();
  6650. }
  6651. while (this.spriteManagers.length) {
  6652. this.spriteManagers[0].dispose();
  6653. }
  6654. while (this.layers.length) {
  6655. this.layers[0].dispose();
  6656. }
  6657. while (this.textures.length) {
  6658. this.textures[0].dispose();
  6659. }
  6660. this.postProcessManager.dispose();
  6661. if (this._physicsEngine) {
  6662. this.disablePhysicsEngine();
  6663. }
  6664. index = this._engine.scenes.indexOf(this);
  6665. if (index > -1) {
  6666. this._engine.scenes.splice(index, 1);
  6667. }
  6668. this._engine.wipeCaches();
  6669. };
  6670. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6671. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6672. position.divideToRef(collider.radius, this._scaledPosition);
  6673. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6674. collider.retry = 0;
  6675. collider.initialVelocity = this._scaledVelocity;
  6676. collider.initialPosition = this._scaledPosition;
  6677. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6678. finalPosition.multiplyInPlace(collider.radius);
  6679. };
  6680. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6681. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6682. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6683. if (collider.retry >= maximumRetry) {
  6684. finalPosition.copyFrom(position);
  6685. return;
  6686. }
  6687. collider._initialize(position, velocity, closeDistance);
  6688. for (var index = 0; index < this.meshes.length; index++) {
  6689. var mesh = this.meshes[index];
  6690. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6691. mesh._checkCollision(collider);
  6692. }
  6693. }
  6694. if (!collider.collisionFound) {
  6695. position.addToRef(velocity, finalPosition);
  6696. return;
  6697. }
  6698. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6699. collider._getResponse(position, velocity);
  6700. }
  6701. if (velocity.length() <= closeDistance) {
  6702. finalPosition.copyFrom(position);
  6703. return;
  6704. }
  6705. collider.retry++;
  6706. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6707. };
  6708. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6709. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6710. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6711. if (!this._selectionOctree) {
  6712. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6713. }
  6714. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6715. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6716. for (var index = 0; index < this.meshes.length; index++) {
  6717. var mesh = this.meshes[index];
  6718. mesh.computeWorldMatrix(true);
  6719. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6720. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6721. BABYLON.Tools.CheckExtends(minBox, min, max);
  6722. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6723. }
  6724. this._selectionOctree.update(min, max, this.meshes);
  6725. return this._selectionOctree;
  6726. };
  6727. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6728. var engine = this._engine;
  6729. if (!camera) {
  6730. if (!this.activeCamera)
  6731. throw new Error("Active camera not set");
  6732. camera = this.activeCamera;
  6733. }
  6734. var cameraViewport = camera.viewport;
  6735. var viewport = cameraViewport.toGlobal(engine);
  6736. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6737. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6738. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6739. };
  6740. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6741. var pickingInfo = null;
  6742. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6743. var mesh = this.meshes[meshIndex];
  6744. if (predicate) {
  6745. if (!predicate(mesh)) {
  6746. continue;
  6747. }
  6748. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6749. continue;
  6750. }
  6751. var world = mesh.getWorldMatrix();
  6752. var ray = rayFunction(world);
  6753. var result = mesh.intersects(ray, fastCheck);
  6754. if (!result || !result.hit)
  6755. continue;
  6756. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6757. continue;
  6758. pickingInfo = result;
  6759. if (fastCheck) {
  6760. break;
  6761. }
  6762. }
  6763. return pickingInfo || new BABYLON.PickingInfo();
  6764. };
  6765. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6766. var _this = this;
  6767. return this._internalPick(function (world) {
  6768. return _this.createPickingRay(x, y, world, camera);
  6769. }, predicate, fastCheck);
  6770. };
  6771. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6772. var _this = this;
  6773. return this._internalPick(function (world) {
  6774. if (!_this._pickWithRayInverseMatrix) {
  6775. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6776. }
  6777. world.invertToRef(_this._pickWithRayInverseMatrix);
  6778. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6779. }, predicate, fastCheck);
  6780. };
  6781. Scene.prototype.setPointerOverMesh = function (mesh) {
  6782. if (this._pointerOverMesh === mesh) {
  6783. return;
  6784. }
  6785. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6786. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6787. }
  6788. this._pointerOverMesh = mesh;
  6789. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6790. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6791. }
  6792. };
  6793. Scene.prototype.getPointerOverMesh = function () {
  6794. return this._pointerOverMesh;
  6795. };
  6796. Scene.prototype.getPhysicsEngine = function () {
  6797. return this._physicsEngine;
  6798. };
  6799. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6800. if (this._physicsEngine) {
  6801. return true;
  6802. }
  6803. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6804. if (!this._physicsEngine.isSupported()) {
  6805. this._physicsEngine = null;
  6806. return false;
  6807. }
  6808. this._physicsEngine._initialize(gravity);
  6809. return true;
  6810. };
  6811. Scene.prototype.disablePhysicsEngine = function () {
  6812. if (!this._physicsEngine) {
  6813. return;
  6814. }
  6815. this._physicsEngine.dispose();
  6816. this._physicsEngine = undefined;
  6817. };
  6818. Scene.prototype.isPhysicsEnabled = function () {
  6819. return this._physicsEngine !== undefined;
  6820. };
  6821. Scene.prototype.setGravity = function (gravity) {
  6822. if (!this._physicsEngine) {
  6823. return;
  6824. }
  6825. this._physicsEngine._setGravity(gravity);
  6826. };
  6827. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6828. if (parts.parts) {
  6829. options = parts;
  6830. parts = parts.parts;
  6831. }
  6832. if (!this._physicsEngine) {
  6833. return null;
  6834. }
  6835. for (var index = 0; index < parts.length; index++) {
  6836. var mesh = parts[index].mesh;
  6837. mesh._physicImpostor = parts[index].impostor;
  6838. mesh._physicsMass = options.mass / parts.length;
  6839. mesh._physicsFriction = options.friction;
  6840. mesh._physicRestitution = options.restitution;
  6841. }
  6842. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6843. };
  6844. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6845. for (var index = 0; index < compound.parts.length; index++) {
  6846. var mesh = compound.parts[index].mesh;
  6847. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6848. this._physicsEngine._unregisterMesh(mesh);
  6849. }
  6850. };
  6851. Scene.prototype._getByTags = function (list, tagsQuery) {
  6852. if (tagsQuery === undefined) {
  6853. return list;
  6854. }
  6855. var listByTags = [];
  6856. for (var i in list) {
  6857. var item = list[i];
  6858. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6859. listByTags.push(item);
  6860. }
  6861. }
  6862. return listByTags;
  6863. };
  6864. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  6865. return this._getByTags(this.meshes, tagsQuery);
  6866. };
  6867. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  6868. return this._getByTags(this.cameras, tagsQuery);
  6869. };
  6870. Scene.prototype.getLightsByTags = function (tagsQuery) {
  6871. return this._getByTags(this.lights, tagsQuery);
  6872. };
  6873. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  6874. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  6875. };
  6876. Scene.FOGMODE_NONE = 0;
  6877. Scene.FOGMODE_EXP = 1;
  6878. Scene.FOGMODE_EXP2 = 2;
  6879. Scene.FOGMODE_LINEAR = 3;
  6880. Scene.MinDeltaTime = 1.0;
  6881. Scene.MaxDeltaTime = 1000.0;
  6882. return Scene;
  6883. })();
  6884. BABYLON.Scene = Scene;
  6885. })(BABYLON || (BABYLON = {}));
  6886. var BABYLON;
  6887. (function (BABYLON) {
  6888. var VertexBuffer = (function () {
  6889. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  6890. if (engine instanceof BABYLON.Mesh) {
  6891. this._engine = engine.getScene().getEngine();
  6892. } else {
  6893. this._engine = engine;
  6894. }
  6895. this._updatable = updatable;
  6896. this._data = data;
  6897. if (!postponeInternalCreation) {
  6898. this.create();
  6899. }
  6900. this._kind = kind;
  6901. switch (kind) {
  6902. case VertexBuffer.PositionKind:
  6903. this._strideSize = 3;
  6904. break;
  6905. case VertexBuffer.NormalKind:
  6906. this._strideSize = 3;
  6907. break;
  6908. case VertexBuffer.UVKind:
  6909. this._strideSize = 2;
  6910. break;
  6911. case VertexBuffer.UV2Kind:
  6912. this._strideSize = 2;
  6913. break;
  6914. case VertexBuffer.ColorKind:
  6915. this._strideSize = 3;
  6916. break;
  6917. case VertexBuffer.MatricesIndicesKind:
  6918. this._strideSize = 4;
  6919. break;
  6920. case VertexBuffer.MatricesWeightsKind:
  6921. this._strideSize = 4;
  6922. break;
  6923. }
  6924. }
  6925. VertexBuffer.prototype.isUpdatable = function () {
  6926. return this._updatable;
  6927. };
  6928. VertexBuffer.prototype.getData = function () {
  6929. return this._data;
  6930. };
  6931. VertexBuffer.prototype.getBuffer = function () {
  6932. return this._buffer;
  6933. };
  6934. VertexBuffer.prototype.getStrideSize = function () {
  6935. return this._strideSize;
  6936. };
  6937. VertexBuffer.prototype.create = function (data) {
  6938. if (!data && this._buffer) {
  6939. return;
  6940. }
  6941. data = data || this._data;
  6942. if (!this._buffer) {
  6943. if (this._updatable) {
  6944. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  6945. } else {
  6946. this._buffer = this._engine.createVertexBuffer(data);
  6947. }
  6948. }
  6949. if (this._updatable) {
  6950. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  6951. this._data = data;
  6952. }
  6953. };
  6954. VertexBuffer.prototype.update = function (data) {
  6955. this.create(data);
  6956. };
  6957. VertexBuffer.prototype.dispose = function () {
  6958. if (!this._buffer) {
  6959. return;
  6960. }
  6961. if (this._engine._releaseBuffer(this._buffer)) {
  6962. this._buffer = null;
  6963. }
  6964. };
  6965. Object.defineProperty(VertexBuffer, "PositionKind", {
  6966. get: function () {
  6967. return VertexBuffer._PositionKind;
  6968. },
  6969. enumerable: true,
  6970. configurable: true
  6971. });
  6972. Object.defineProperty(VertexBuffer, "NormalKind", {
  6973. get: function () {
  6974. return VertexBuffer._NormalKind;
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. Object.defineProperty(VertexBuffer, "UVKind", {
  6980. get: function () {
  6981. return VertexBuffer._UVKind;
  6982. },
  6983. enumerable: true,
  6984. configurable: true
  6985. });
  6986. Object.defineProperty(VertexBuffer, "UV2Kind", {
  6987. get: function () {
  6988. return VertexBuffer._UV2Kind;
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. Object.defineProperty(VertexBuffer, "ColorKind", {
  6994. get: function () {
  6995. return VertexBuffer._ColorKind;
  6996. },
  6997. enumerable: true,
  6998. configurable: true
  6999. });
  7000. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7001. get: function () {
  7002. return VertexBuffer._MatricesIndicesKind;
  7003. },
  7004. enumerable: true,
  7005. configurable: true
  7006. });
  7007. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7008. get: function () {
  7009. return VertexBuffer._MatricesWeightsKind;
  7010. },
  7011. enumerable: true,
  7012. configurable: true
  7013. });
  7014. VertexBuffer._PositionKind = "position";
  7015. VertexBuffer._NormalKind = "normal";
  7016. VertexBuffer._UVKind = "uv";
  7017. VertexBuffer._UV2Kind = "uv2";
  7018. VertexBuffer._ColorKind = "color";
  7019. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7020. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7021. return VertexBuffer;
  7022. })();
  7023. BABYLON.VertexBuffer = VertexBuffer;
  7024. })(BABYLON || (BABYLON = {}));
  7025. var __extends = this.__extends || function (d, b) {
  7026. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7027. function __() { this.constructor = d; }
  7028. __.prototype = b.prototype;
  7029. d.prototype = new __();
  7030. };
  7031. var BABYLON;
  7032. (function (BABYLON) {
  7033. var AbstractMesh = (function (_super) {
  7034. __extends(AbstractMesh, _super);
  7035. function AbstractMesh(name, scene) {
  7036. _super.call(this, name, scene);
  7037. this.position = new BABYLON.Vector3(0, 0, 0);
  7038. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7039. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7040. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7041. this.visibility = 1.0;
  7042. this.infiniteDistance = false;
  7043. this.isVisible = true;
  7044. this.isPickable = true;
  7045. this.showBoundingBox = false;
  7046. this.showSubMeshesBoundingBox = false;
  7047. this.onDispose = null;
  7048. this.checkCollisions = false;
  7049. this.renderingGroupId = 0;
  7050. this.receiveShadows = false;
  7051. this.renderOutline = false;
  7052. this.outlineColor = BABYLON.Color3.Red();
  7053. this.outlineWidth = 0.02;
  7054. this.useOctreeForRenderingSelection = true;
  7055. this.useOctreeForPicking = true;
  7056. this.useOctreeForCollisions = true;
  7057. this.layerMask = 0xFFFFFFFF;
  7058. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7059. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7060. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7061. this._collider = new BABYLON.Collider();
  7062. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7063. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7064. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7065. this._localScaling = BABYLON.Matrix.Zero();
  7066. this._localRotation = BABYLON.Matrix.Zero();
  7067. this._localTranslation = BABYLON.Matrix.Zero();
  7068. this._localBillboard = BABYLON.Matrix.Zero();
  7069. this._localPivotScaling = BABYLON.Matrix.Zero();
  7070. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7071. this._localWorld = BABYLON.Matrix.Zero();
  7072. this._worldMatrix = BABYLON.Matrix.Zero();
  7073. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7074. this._absolutePosition = BABYLON.Vector3.Zero();
  7075. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7076. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7077. this._isDirty = false;
  7078. this._pivotMatrix = BABYLON.Matrix.Identity();
  7079. this._isDisposed = false;
  7080. this._renderId = 0;
  7081. this._intersectionsInProgress = new Array();
  7082. scene.meshes.push(this);
  7083. }
  7084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7085. get: function () {
  7086. return AbstractMesh._BILLBOARDMODE_NONE;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7092. get: function () {
  7093. return AbstractMesh._BILLBOARDMODE_X;
  7094. },
  7095. enumerable: true,
  7096. configurable: true
  7097. });
  7098. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7099. get: function () {
  7100. return AbstractMesh._BILLBOARDMODE_Y;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7106. get: function () {
  7107. return AbstractMesh._BILLBOARDMODE_Z;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7113. get: function () {
  7114. return AbstractMesh._BILLBOARDMODE_ALL;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. AbstractMesh.prototype.getTotalVertices = function () {
  7120. return 0;
  7121. };
  7122. AbstractMesh.prototype.getIndices = function () {
  7123. return null;
  7124. };
  7125. AbstractMesh.prototype.getVerticesData = function (kind) {
  7126. return null;
  7127. };
  7128. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7129. return false;
  7130. };
  7131. AbstractMesh.prototype.getBoundingInfo = function () {
  7132. if (!this._boundingInfo) {
  7133. this._updateBoundingInfo();
  7134. }
  7135. return this._boundingInfo;
  7136. };
  7137. AbstractMesh.prototype._preActivate = function () {
  7138. };
  7139. AbstractMesh.prototype._activate = function (renderId) {
  7140. this._renderId = renderId;
  7141. };
  7142. AbstractMesh.prototype.getWorldMatrix = function () {
  7143. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7144. this.computeWorldMatrix();
  7145. }
  7146. return this._worldMatrix;
  7147. };
  7148. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7149. get: function () {
  7150. return this._worldMatrix;
  7151. },
  7152. enumerable: true,
  7153. configurable: true
  7154. });
  7155. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7156. get: function () {
  7157. return this._absolutePosition;
  7158. },
  7159. enumerable: true,
  7160. configurable: true
  7161. });
  7162. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7163. if (!this.rotationQuaternion) {
  7164. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7165. this.rotation = BABYLON.Vector3.Zero();
  7166. }
  7167. if (!space || space == 0 /* LOCAL */) {
  7168. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7169. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7170. } else {
  7171. if (this.parent) {
  7172. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7173. invertParentWorldMatrix.invert();
  7174. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7175. }
  7176. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7177. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7178. }
  7179. };
  7180. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7181. var displacementVector = axis.scale(distance);
  7182. if (!space || space == 0 /* LOCAL */) {
  7183. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7184. this.setPositionWithLocalVector(tempV3);
  7185. } else {
  7186. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7187. }
  7188. };
  7189. AbstractMesh.prototype.getAbsolutePosition = function () {
  7190. this.computeWorldMatrix();
  7191. return this._absolutePosition;
  7192. };
  7193. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7194. if (!absolutePosition) {
  7195. return;
  7196. }
  7197. var absolutePositionX;
  7198. var absolutePositionY;
  7199. var absolutePositionZ;
  7200. if (absolutePosition.x === undefined) {
  7201. if (arguments.length < 3) {
  7202. return;
  7203. }
  7204. absolutePositionX = arguments[0];
  7205. absolutePositionY = arguments[1];
  7206. absolutePositionZ = arguments[2];
  7207. } else {
  7208. absolutePositionX = absolutePosition.x;
  7209. absolutePositionY = absolutePosition.y;
  7210. absolutePositionZ = absolutePosition.z;
  7211. }
  7212. if (this.parent) {
  7213. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7214. invertParentWorldMatrix.invert();
  7215. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7216. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7217. } else {
  7218. this.position.x = absolutePositionX;
  7219. this.position.y = absolutePositionY;
  7220. this.position.z = absolutePositionZ;
  7221. }
  7222. };
  7223. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7224. this._pivotMatrix = matrix;
  7225. this._cache.pivotMatrixUpdated = true;
  7226. };
  7227. AbstractMesh.prototype.getPivotMatrix = function () {
  7228. return this._pivotMatrix;
  7229. };
  7230. AbstractMesh.prototype._isSynchronized = function () {
  7231. if (this._isDirty) {
  7232. return false;
  7233. }
  7234. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7235. return false;
  7236. if (this._cache.pivotMatrixUpdated) {
  7237. return false;
  7238. }
  7239. if (this.infiniteDistance) {
  7240. return false;
  7241. }
  7242. if (!this._cache.position.equals(this.position))
  7243. return false;
  7244. if (this.rotationQuaternion) {
  7245. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7246. return false;
  7247. } else {
  7248. if (!this._cache.rotation.equals(this.rotation))
  7249. return false;
  7250. }
  7251. if (!this._cache.scaling.equals(this.scaling))
  7252. return false;
  7253. return true;
  7254. };
  7255. AbstractMesh.prototype._initCache = function () {
  7256. _super.prototype._initCache.call(this);
  7257. this._cache.localMatrixUpdated = false;
  7258. this._cache.position = BABYLON.Vector3.Zero();
  7259. this._cache.scaling = BABYLON.Vector3.Zero();
  7260. this._cache.rotation = BABYLON.Vector3.Zero();
  7261. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7262. };
  7263. AbstractMesh.prototype.markAsDirty = function (property) {
  7264. if (property === "rotation") {
  7265. this.rotationQuaternion = null;
  7266. }
  7267. this._currentRenderId = Number.MAX_VALUE;
  7268. this._isDirty = true;
  7269. };
  7270. AbstractMesh.prototype._updateBoundingInfo = function () {
  7271. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7272. this._boundingInfo._update(this.worldMatrixFromCache);
  7273. if (!this.subMeshes) {
  7274. return;
  7275. }
  7276. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7277. var subMesh = this.subMeshes[subIndex];
  7278. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7279. }
  7280. };
  7281. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7282. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7283. return this._worldMatrix;
  7284. }
  7285. this._cache.position.copyFrom(this.position);
  7286. this._cache.scaling.copyFrom(this.scaling);
  7287. this._cache.pivotMatrixUpdated = false;
  7288. this._currentRenderId = this.getScene().getRenderId();
  7289. this._isDirty = false;
  7290. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7291. if (this.rotationQuaternion) {
  7292. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7293. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7294. } else {
  7295. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7296. this._cache.rotation.copyFrom(this.rotation);
  7297. }
  7298. if (this.infiniteDistance && !this.parent) {
  7299. var camera = this.getScene().activeCamera;
  7300. var cameraWorldMatrix = camera.getWorldMatrix();
  7301. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7302. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7303. } else {
  7304. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7305. }
  7306. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7307. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7308. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  7309. var localPosition = this.position.clone();
  7310. var zero = this.getScene().activeCamera.position.clone();
  7311. if (this.parent && this.parent.position) {
  7312. localPosition.addInPlace(this.parent.position);
  7313. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7314. }
  7315. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7316. zero = this.getScene().activeCamera.position;
  7317. } else {
  7318. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7319. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7320. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7321. zero.y = localPosition.y + 0.001;
  7322. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7323. zero.z = localPosition.z + 0.001;
  7324. }
  7325. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7326. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7327. this._localBillboard.invert();
  7328. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7329. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7330. }
  7331. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7332. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7333. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7334. } else {
  7335. this._worldMatrix.copyFrom(this._localWorld);
  7336. }
  7337. this._updateBoundingInfo();
  7338. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7339. return this._worldMatrix;
  7340. };
  7341. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7342. this.computeWorldMatrix();
  7343. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7344. };
  7345. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7346. this.computeWorldMatrix();
  7347. var invLocalWorldMatrix = this._localWorld.clone();
  7348. invLocalWorldMatrix.invert();
  7349. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7350. };
  7351. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7352. this.computeWorldMatrix();
  7353. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7354. };
  7355. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7356. yawCor = yawCor || 0;
  7357. pitchCor = pitchCor || 0;
  7358. rollCor = rollCor || 0;
  7359. var dv = targetPoint.subtract(this.position);
  7360. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7361. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7362. var pitch = Math.atan2(dv.y, len);
  7363. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7364. };
  7365. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7366. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7367. return false;
  7368. }
  7369. return true;
  7370. };
  7371. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7372. if (!this._boundingInfo || !mesh._boundingInfo) {
  7373. return false;
  7374. }
  7375. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7376. };
  7377. AbstractMesh.prototype.intersectsPoint = function (point) {
  7378. if (!this._boundingInfo) {
  7379. return false;
  7380. }
  7381. return this._boundingInfo.intersectsPoint(point);
  7382. };
  7383. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7384. var physicsEngine = this.getScene().getPhysicsEngine();
  7385. if (!physicsEngine) {
  7386. return;
  7387. }
  7388. if (impostor.impostor) {
  7389. options = impostor;
  7390. impostor = impostor.impostor;
  7391. }
  7392. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7393. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7394. physicsEngine._unregisterMesh(this);
  7395. return;
  7396. }
  7397. options.mass = options.mass || 0;
  7398. options.friction = options.friction || 0.2;
  7399. options.restitution = options.restitution || 0.9;
  7400. this._physicImpostor = impostor;
  7401. this._physicsMass = options.mass;
  7402. this._physicsFriction = options.friction;
  7403. this._physicRestitution = options.restitution;
  7404. physicsEngine._registerMesh(this, impostor, options);
  7405. };
  7406. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7407. if (!this._physicImpostor) {
  7408. return BABYLON.PhysicsEngine.NoImpostor;
  7409. }
  7410. return this._physicImpostor;
  7411. };
  7412. AbstractMesh.prototype.getPhysicsMass = function () {
  7413. if (!this._physicsMass) {
  7414. return 0;
  7415. }
  7416. return this._physicsMass;
  7417. };
  7418. AbstractMesh.prototype.getPhysicsFriction = function () {
  7419. if (!this._physicsFriction) {
  7420. return 0;
  7421. }
  7422. return this._physicsFriction;
  7423. };
  7424. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7425. if (!this._physicRestitution) {
  7426. return 0;
  7427. }
  7428. return this._physicRestitution;
  7429. };
  7430. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7431. if (!this._physicImpostor) {
  7432. return;
  7433. }
  7434. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7435. };
  7436. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7437. if (!this._physicImpostor) {
  7438. return;
  7439. }
  7440. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7441. };
  7442. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7443. if (!this._physicImpostor) {
  7444. return;
  7445. }
  7446. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7447. };
  7448. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7449. var globalPosition = this.getAbsolutePosition();
  7450. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7451. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7452. this._collider.radius = this.ellipsoid;
  7453. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7454. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7455. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7456. this.position.addInPlace(this._diffPositionForCollisions);
  7457. }
  7458. };
  7459. /**
  7460. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7461. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7462. */
  7463. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7464. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7465. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7466. if (!this._submeshesOctree) {
  7467. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7468. }
  7469. this.computeWorldMatrix(true);
  7470. var bbox = this.getBoundingInfo().boundingBox;
  7471. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7472. return this._submeshesOctree;
  7473. };
  7474. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7475. this._generatePointsArray();
  7476. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7477. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7478. subMesh._lastColliderWorldVertices = [];
  7479. subMesh._trianglePlanes = [];
  7480. var start = subMesh.verticesStart;
  7481. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7482. for (var i = start; i < end; i++) {
  7483. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7484. }
  7485. }
  7486. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7487. };
  7488. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7489. var subMeshes;
  7490. var len;
  7491. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7492. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7493. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7494. len = intersections.length;
  7495. subMeshes = intersections.data;
  7496. } else {
  7497. subMeshes = this.subMeshes;
  7498. len = subMeshes.length;
  7499. }
  7500. for (var index = 0; index < len; index++) {
  7501. var subMesh = subMeshes[index];
  7502. if (len > 1 && !subMesh._checkCollision(collider))
  7503. continue;
  7504. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7505. }
  7506. };
  7507. AbstractMesh.prototype._checkCollision = function (collider) {
  7508. if (!this._boundingInfo._checkCollision(collider))
  7509. return;
  7510. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7511. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7512. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7513. };
  7514. AbstractMesh.prototype._generatePointsArray = function () {
  7515. return false;
  7516. };
  7517. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7518. var pickingInfo = new BABYLON.PickingInfo();
  7519. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7520. return pickingInfo;
  7521. }
  7522. if (!this._generatePointsArray()) {
  7523. return pickingInfo;
  7524. }
  7525. var intersectInfo = null;
  7526. var subMeshes;
  7527. var len;
  7528. if (this._submeshesOctree && this.useOctreeForPicking) {
  7529. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7530. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7531. len = intersections.length;
  7532. subMeshes = intersections.data;
  7533. } else {
  7534. subMeshes = this.subMeshes;
  7535. len = subMeshes.length;
  7536. }
  7537. for (var index = 0; index < len; index++) {
  7538. var subMesh = subMeshes[index];
  7539. if (len > 1 && !subMesh.canIntersects(ray))
  7540. continue;
  7541. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7542. if (currentIntersectInfo) {
  7543. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7544. intersectInfo = currentIntersectInfo;
  7545. if (fastCheck) {
  7546. break;
  7547. }
  7548. }
  7549. }
  7550. }
  7551. if (intersectInfo) {
  7552. var world = this.getWorldMatrix();
  7553. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7554. var direction = ray.direction.clone();
  7555. direction.normalize();
  7556. direction = direction.scale(intersectInfo.distance);
  7557. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7558. var pickedPoint = worldOrigin.add(worldDirection);
  7559. pickingInfo.hit = true;
  7560. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7561. pickingInfo.pickedPoint = pickedPoint;
  7562. pickingInfo.pickedMesh = this;
  7563. pickingInfo.bu = intersectInfo.bu;
  7564. pickingInfo.bv = intersectInfo.bv;
  7565. pickingInfo.faceId = intersectInfo.faceId;
  7566. return pickingInfo;
  7567. }
  7568. return pickingInfo;
  7569. };
  7570. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7571. return null;
  7572. };
  7573. AbstractMesh.prototype.releaseSubMeshes = function () {
  7574. if (this.subMeshes) {
  7575. while (this.subMeshes.length) {
  7576. this.subMeshes[0].dispose();
  7577. }
  7578. } else {
  7579. this.subMeshes = new Array();
  7580. }
  7581. };
  7582. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7583. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7584. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7585. }
  7586. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7587. var other = this._intersectionsInProgress[index];
  7588. var pos = other._intersectionsInProgress.indexOf(this);
  7589. other._intersectionsInProgress.splice(pos, 1);
  7590. }
  7591. this._intersectionsInProgress = [];
  7592. this.releaseSubMeshes();
  7593. var index = this.getScene().meshes.indexOf(this);
  7594. if (index != -1) {
  7595. this.getScene().meshes.splice(index, 1);
  7596. }
  7597. if (!doNotRecurse) {
  7598. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7599. if (this.getScene().particleSystems[index].emitter == this) {
  7600. this.getScene().particleSystems[index].dispose();
  7601. index--;
  7602. }
  7603. }
  7604. var objects = this.getScene().meshes.slice(0);
  7605. for (index = 0; index < objects.length; index++) {
  7606. if (objects[index].parent == this) {
  7607. objects[index].dispose();
  7608. }
  7609. }
  7610. } else {
  7611. for (index = 0; index < this.getScene().meshes.length; index++) {
  7612. var obj = this.getScene().meshes[index];
  7613. if (obj.parent === this) {
  7614. obj.parent = null;
  7615. obj.computeWorldMatrix(true);
  7616. }
  7617. }
  7618. }
  7619. this._isDisposed = true;
  7620. if (this.onDispose) {
  7621. this.onDispose();
  7622. }
  7623. };
  7624. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7625. AbstractMesh._BILLBOARDMODE_X = 1;
  7626. AbstractMesh._BILLBOARDMODE_Y = 2;
  7627. AbstractMesh._BILLBOARDMODE_Z = 4;
  7628. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7629. return AbstractMesh;
  7630. })(BABYLON.Node);
  7631. BABYLON.AbstractMesh = AbstractMesh;
  7632. })(BABYLON || (BABYLON = {}));
  7633. var __extends = this.__extends || function (d, b) {
  7634. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7635. function __() { this.constructor = d; }
  7636. __.prototype = b.prototype;
  7637. d.prototype = new __();
  7638. };
  7639. var BABYLON;
  7640. (function (BABYLON) {
  7641. var _InstancesBatch = (function () {
  7642. function _InstancesBatch() {
  7643. this.mustReturn = false;
  7644. this.visibleInstances = new Array();
  7645. this.renderSelf = new Array();
  7646. }
  7647. return _InstancesBatch;
  7648. })();
  7649. BABYLON._InstancesBatch = _InstancesBatch;
  7650. var Mesh = (function (_super) {
  7651. __extends(Mesh, _super);
  7652. function Mesh(name, scene) {
  7653. _super.call(this, name, scene);
  7654. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7655. this.instances = new Array();
  7656. this._onBeforeRenderCallbacks = new Array();
  7657. this._onAfterRenderCallbacks = new Array();
  7658. this._visibleInstances = {};
  7659. this._renderIdForInstances = new Array();
  7660. this._batchCache = new _InstancesBatch();
  7661. this._instancesBufferSize = 32 * 16 * 4;
  7662. }
  7663. Mesh.prototype.getTotalVertices = function () {
  7664. if (!this._geometry) {
  7665. return 0;
  7666. }
  7667. return this._geometry.getTotalVertices();
  7668. };
  7669. Mesh.prototype.getVerticesData = function (kind) {
  7670. if (!this._geometry) {
  7671. return null;
  7672. }
  7673. return this._geometry.getVerticesData(kind);
  7674. };
  7675. Mesh.prototype.getVertexBuffer = function (kind) {
  7676. if (!this._geometry) {
  7677. return undefined;
  7678. }
  7679. return this._geometry.getVertexBuffer(kind);
  7680. };
  7681. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7682. if (!this._geometry) {
  7683. if (this._delayInfo) {
  7684. return this._delayInfo.indexOf(kind) !== -1;
  7685. }
  7686. return false;
  7687. }
  7688. return this._geometry.isVerticesDataPresent(kind);
  7689. };
  7690. Mesh.prototype.getVerticesDataKinds = function () {
  7691. if (!this._geometry) {
  7692. var result = [];
  7693. if (this._delayInfo) {
  7694. for (var kind in this._delayInfo) {
  7695. result.push(kind);
  7696. }
  7697. }
  7698. return result;
  7699. }
  7700. return this._geometry.getVerticesDataKinds();
  7701. };
  7702. Mesh.prototype.getTotalIndices = function () {
  7703. if (!this._geometry) {
  7704. return 0;
  7705. }
  7706. return this._geometry.getTotalIndices();
  7707. };
  7708. Mesh.prototype.getIndices = function () {
  7709. if (!this._geometry) {
  7710. return [];
  7711. }
  7712. return this._geometry.getIndices();
  7713. };
  7714. Mesh.prototype.isReady = function () {
  7715. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7716. return false;
  7717. }
  7718. return _super.prototype.isReady.call(this);
  7719. };
  7720. Mesh.prototype.isDisposed = function () {
  7721. return this._isDisposed;
  7722. };
  7723. Mesh.prototype._preActivate = function () {
  7724. var sceneRenderId = this.getScene().getRenderId();
  7725. if (this._preActivateId == sceneRenderId) {
  7726. return;
  7727. }
  7728. this._preActivateId = sceneRenderId;
  7729. this._visibleInstances = null;
  7730. };
  7731. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7732. if (!this._visibleInstances) {
  7733. this._visibleInstances = {};
  7734. this._visibleInstances.defaultRenderId = renderId;
  7735. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7736. }
  7737. if (!this._visibleInstances[renderId]) {
  7738. this._visibleInstances[renderId] = new Array();
  7739. }
  7740. this._visibleInstances[renderId].push(instance);
  7741. };
  7742. Mesh.prototype.refreshBoundingInfo = function () {
  7743. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7744. if (data) {
  7745. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7746. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7747. }
  7748. if (this.subMeshes) {
  7749. for (var index = 0; index < this.subMeshes.length; index++) {
  7750. this.subMeshes[index].refreshBoundingInfo();
  7751. }
  7752. }
  7753. this._updateBoundingInfo();
  7754. };
  7755. Mesh.prototype._createGlobalSubMesh = function () {
  7756. var totalVertices = this.getTotalVertices();
  7757. if (!totalVertices || !this.getIndices()) {
  7758. return null;
  7759. }
  7760. this.releaseSubMeshes();
  7761. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7762. };
  7763. Mesh.prototype.subdivide = function (count) {
  7764. if (count < 1) {
  7765. return;
  7766. }
  7767. var totalIndices = this.getTotalIndices();
  7768. var subdivisionSize = (totalIndices / count) | 0;
  7769. var offset = 0;
  7770. while (subdivisionSize % 3 != 0) {
  7771. subdivisionSize++;
  7772. }
  7773. this.releaseSubMeshes();
  7774. for (var index = 0; index < count; index++) {
  7775. if (offset >= totalIndices) {
  7776. break;
  7777. }
  7778. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7779. offset += subdivisionSize;
  7780. }
  7781. this.synchronizeInstances();
  7782. };
  7783. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7784. if (kind instanceof Array) {
  7785. var temp = data;
  7786. data = kind;
  7787. kind = temp;
  7788. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7789. }
  7790. if (!this._geometry) {
  7791. var vertexData = new BABYLON.VertexData();
  7792. vertexData.set(data, kind);
  7793. var scene = this.getScene();
  7794. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7795. } else {
  7796. this._geometry.setVerticesData(kind, data, updatable);
  7797. }
  7798. };
  7799. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7800. if (!this._geometry) {
  7801. return;
  7802. }
  7803. if (!makeItUnique) {
  7804. this._geometry.updateVerticesData(kind, data, updateExtends);
  7805. } else {
  7806. this.makeGeometryUnique();
  7807. this.updateVerticesData(kind, data, updateExtends, false);
  7808. }
  7809. };
  7810. Mesh.prototype.makeGeometryUnique = function () {
  7811. if (!this._geometry) {
  7812. return;
  7813. }
  7814. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7815. geometry.applyToMesh(this);
  7816. };
  7817. Mesh.prototype.setIndices = function (indices) {
  7818. if (!this._geometry) {
  7819. var vertexData = new BABYLON.VertexData();
  7820. vertexData.indices = indices;
  7821. var scene = this.getScene();
  7822. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7823. } else {
  7824. this._geometry.setIndices(indices);
  7825. }
  7826. };
  7827. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7828. var engine = this.getScene().getEngine();
  7829. var indexToBind = this._geometry.getIndexBuffer();
  7830. if (wireframe) {
  7831. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7832. }
  7833. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7834. };
  7835. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7836. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7837. return;
  7838. }
  7839. var engine = this.getScene().getEngine();
  7840. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7841. };
  7842. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7843. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7844. return;
  7845. }
  7846. var engine = this.getScene().getEngine();
  7847. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7848. };
  7849. Mesh.prototype.registerBeforeRender = function (func) {
  7850. this._onBeforeRenderCallbacks.push(func);
  7851. };
  7852. Mesh.prototype.unregisterBeforeRender = function (func) {
  7853. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7854. if (index > -1) {
  7855. this._onBeforeRenderCallbacks.splice(index, 1);
  7856. }
  7857. };
  7858. Mesh.prototype.registerAfterRender = function (func) {
  7859. this._onAfterRenderCallbacks.push(func);
  7860. };
  7861. Mesh.prototype.unregisterAfterRender = function (func) {
  7862. var index = this._onAfterRenderCallbacks.indexOf(func);
  7863. if (index > -1) {
  7864. this._onAfterRenderCallbacks.splice(index, 1);
  7865. }
  7866. };
  7867. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  7868. var scene = this.getScene();
  7869. this._batchCache.mustReturn = false;
  7870. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  7871. this._batchCache.visibleInstances[subMeshId] = null;
  7872. if (this._visibleInstances) {
  7873. var currentRenderId = scene.getRenderId();
  7874. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  7875. var selfRenderId = this._renderId;
  7876. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  7877. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  7878. currentRenderId = this._visibleInstances.defaultRenderId;
  7879. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  7880. }
  7881. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  7882. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  7883. this._batchCache.mustReturn = true;
  7884. return this._batchCache;
  7885. }
  7886. if (currentRenderId !== selfRenderId) {
  7887. this._batchCache.renderSelf[subMeshId] = false;
  7888. }
  7889. }
  7890. this._renderIdForInstances[subMeshId] = currentRenderId;
  7891. }
  7892. return this._batchCache;
  7893. };
  7894. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  7895. var matricesCount = this.instances.length + 1;
  7896. var bufferSize = matricesCount * 16 * 4;
  7897. while (this._instancesBufferSize < bufferSize) {
  7898. this._instancesBufferSize *= 2;
  7899. }
  7900. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  7901. if (this._worldMatricesInstancesBuffer) {
  7902. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  7903. }
  7904. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  7905. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  7906. }
  7907. var offset = 0;
  7908. var instancesCount = 0;
  7909. var world = this.getWorldMatrix();
  7910. if (batch.renderSelf[subMesh._id]) {
  7911. world.copyToArray(this._worldMatricesInstancesArray, offset);
  7912. offset += 16;
  7913. instancesCount++;
  7914. }
  7915. var visibleInstances = batch.visibleInstances[subMesh._id];
  7916. if (visibleInstances) {
  7917. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  7918. var instance = visibleInstances[instanceIndex];
  7919. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  7920. offset += 16;
  7921. instancesCount++;
  7922. }
  7923. }
  7924. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  7925. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  7926. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  7927. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  7928. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  7929. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  7930. this._draw(subMesh, !wireFrame, instancesCount);
  7931. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  7932. };
  7933. Mesh.prototype.render = function (subMesh) {
  7934. var scene = this.getScene();
  7935. var batch = this._getInstancesRenderList(subMesh._id);
  7936. if (batch.mustReturn) {
  7937. return;
  7938. }
  7939. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7940. return;
  7941. }
  7942. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7943. this._onBeforeRenderCallbacks[callbackIndex]();
  7944. }
  7945. var engine = scene.getEngine();
  7946. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  7947. var effectiveMaterial = subMesh.getMaterial();
  7948. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  7949. return;
  7950. }
  7951. var savedDepthWrite = engine.getDepthWrite();
  7952. if (this.renderOutline) {
  7953. engine.setDepthWrite(false);
  7954. scene.getOutlineRenderer().render(subMesh, batch);
  7955. }
  7956. effectiveMaterial._preBind();
  7957. var effect = effectiveMaterial.getEffect();
  7958. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  7959. this._bind(subMesh, effect, wireFrame);
  7960. var world = this.getWorldMatrix();
  7961. effectiveMaterial.bind(world, this);
  7962. if (hardwareInstancedRendering) {
  7963. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  7964. } else {
  7965. if (batch.renderSelf[subMesh._id]) {
  7966. this._draw(subMesh, !wireFrame);
  7967. }
  7968. if (batch.visibleInstances[subMesh._id]) {
  7969. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  7970. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  7971. world = instance.getWorldMatrix();
  7972. effectiveMaterial.bindOnlyWorldMatrix(world);
  7973. this._draw(subMesh, !wireFrame);
  7974. }
  7975. }
  7976. }
  7977. effectiveMaterial.unbind();
  7978. if (this.renderOutline && savedDepthWrite) {
  7979. engine.setDepthWrite(true);
  7980. engine.setColorWrite(false);
  7981. scene.getOutlineRenderer().render(subMesh, batch);
  7982. engine.setColorWrite(true);
  7983. }
  7984. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7985. this._onAfterRenderCallbacks[callbackIndex]();
  7986. }
  7987. };
  7988. Mesh.prototype.getEmittedParticleSystems = function () {
  7989. var results = new Array();
  7990. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  7991. var particleSystem = this.getScene().particleSystems[index];
  7992. if (particleSystem.emitter === this) {
  7993. results.push(particleSystem);
  7994. }
  7995. }
  7996. return results;
  7997. };
  7998. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  7999. var results = new Array();
  8000. var descendants = this.getDescendants();
  8001. descendants.push(this);
  8002. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8003. var particleSystem = this.getScene().particleSystems[index];
  8004. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8005. results.push(particleSystem);
  8006. }
  8007. }
  8008. return results;
  8009. };
  8010. Mesh.prototype.getChildren = function () {
  8011. var results = [];
  8012. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8013. var mesh = this.getScene().meshes[index];
  8014. if (mesh.parent == this) {
  8015. results.push(mesh);
  8016. }
  8017. }
  8018. return results;
  8019. };
  8020. Mesh.prototype._checkDelayState = function () {
  8021. var _this = this;
  8022. var that = this;
  8023. var scene = this.getScene();
  8024. if (this._geometry) {
  8025. this._geometry.load(scene);
  8026. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8027. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8028. scene._addPendingData(that);
  8029. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8030. _this._delayLoadingFunction(JSON.parse(data), _this);
  8031. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8032. scene._removePendingData(_this);
  8033. }, function () {
  8034. }, scene.database);
  8035. }
  8036. };
  8037. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8038. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8039. return false;
  8040. }
  8041. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8042. return false;
  8043. }
  8044. this._checkDelayState();
  8045. return true;
  8046. };
  8047. Mesh.prototype.setMaterialByID = function (id) {
  8048. var materials = this.getScene().materials;
  8049. for (var index = 0; index < materials.length; index++) {
  8050. if (materials[index].id == id) {
  8051. this.material = materials[index];
  8052. return;
  8053. }
  8054. }
  8055. var multiMaterials = this.getScene().multiMaterials;
  8056. for (index = 0; index < multiMaterials.length; index++) {
  8057. if (multiMaterials[index].id == id) {
  8058. this.material = multiMaterials[index];
  8059. return;
  8060. }
  8061. }
  8062. };
  8063. Mesh.prototype.getAnimatables = function () {
  8064. var results = [];
  8065. if (this.material) {
  8066. results.push(this.material);
  8067. }
  8068. return results;
  8069. };
  8070. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8071. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8072. return;
  8073. }
  8074. this._resetPointsArrayCache();
  8075. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8076. var temp = [];
  8077. for (var index = 0; index < data.length; index += 3) {
  8078. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8079. }
  8080. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8081. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8082. return;
  8083. }
  8084. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8085. for (index = 0; index < data.length; index += 3) {
  8086. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8087. }
  8088. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8089. };
  8090. Mesh.prototype._resetPointsArrayCache = function () {
  8091. this._positions = null;
  8092. };
  8093. Mesh.prototype._generatePointsArray = function () {
  8094. if (this._positions)
  8095. return true;
  8096. this._positions = [];
  8097. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8098. if (!data) {
  8099. return false;
  8100. }
  8101. for (var index = 0; index < data.length; index += 3) {
  8102. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8103. }
  8104. return true;
  8105. };
  8106. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8107. var result = new BABYLON.Mesh(name, this.getScene());
  8108. this._geometry.applyToMesh(result);
  8109. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8110. result.material = this.material;
  8111. if (newParent) {
  8112. result.parent = newParent;
  8113. }
  8114. if (!doNotCloneChildren) {
  8115. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8116. var mesh = this.getScene().meshes[index];
  8117. if (mesh.parent == this) {
  8118. mesh.clone(mesh.name, result);
  8119. }
  8120. }
  8121. }
  8122. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8123. var system = this.getScene().particleSystems[index];
  8124. if (system.emitter == this) {
  8125. system.clone(system.name, result);
  8126. }
  8127. }
  8128. result.computeWorldMatrix(true);
  8129. return result;
  8130. };
  8131. Mesh.prototype.dispose = function (doNotRecurse) {
  8132. if (this._geometry) {
  8133. this._geometry.releaseForMesh(this, true);
  8134. }
  8135. if (this._worldMatricesInstancesBuffer) {
  8136. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8137. this._worldMatricesInstancesBuffer = null;
  8138. }
  8139. while (this.instances.length) {
  8140. this.instances[0].dispose();
  8141. }
  8142. _super.prototype.dispose.call(this, doNotRecurse);
  8143. };
  8144. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8145. var _this = this;
  8146. var scene = this.getScene();
  8147. var onload = function (img) {
  8148. var canvas = document.createElement("canvas");
  8149. var context = canvas.getContext("2d");
  8150. var heightMapWidth = img.width;
  8151. var heightMapHeight = img.height;
  8152. canvas.width = heightMapWidth;
  8153. canvas.height = heightMapHeight;
  8154. context.drawImage(img, 0, 0);
  8155. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8156. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8157. };
  8158. BABYLON.Tools.LoadImage(url, onload, function () {
  8159. }, scene.database);
  8160. };
  8161. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8162. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8163. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8164. return;
  8165. }
  8166. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8167. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8168. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8169. var position = BABYLON.Vector3.Zero();
  8170. var normal = BABYLON.Vector3.Zero();
  8171. var uv = BABYLON.Vector2.Zero();
  8172. for (var index = 0; index < positions.length; index += 3) {
  8173. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8174. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8175. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8176. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8177. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8178. var pos = (u + v * heightMapWidth) * 4;
  8179. var r = buffer[pos] / 255.0;
  8180. var g = buffer[pos + 1] / 255.0;
  8181. var b = buffer[pos + 2] / 255.0;
  8182. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8183. normal.normalize();
  8184. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8185. position = position.add(normal);
  8186. position.toArray(positions, index);
  8187. }
  8188. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8189. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8190. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8191. };
  8192. Mesh.prototype.convertToFlatShadedMesh = function () {
  8193. var kinds = this.getVerticesDataKinds();
  8194. var vbs = [];
  8195. var data = [];
  8196. var newdata = [];
  8197. var updatableNormals = false;
  8198. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8199. var kind = kinds[kindIndex];
  8200. var vertexBuffer = this.getVertexBuffer(kind);
  8201. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8202. updatableNormals = vertexBuffer.isUpdatable();
  8203. kinds.splice(kindIndex, 1);
  8204. kindIndex--;
  8205. continue;
  8206. }
  8207. vbs[kind] = vertexBuffer;
  8208. data[kind] = vbs[kind].getData();
  8209. newdata[kind] = [];
  8210. }
  8211. var previousSubmeshes = this.subMeshes.slice(0);
  8212. var indices = this.getIndices();
  8213. var totalIndices = this.getTotalIndices();
  8214. for (index = 0; index < totalIndices; index++) {
  8215. var vertexIndex = indices[index];
  8216. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8217. kind = kinds[kindIndex];
  8218. var stride = vbs[kind].getStrideSize();
  8219. for (var offset = 0; offset < stride; offset++) {
  8220. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8221. }
  8222. }
  8223. }
  8224. var normals = [];
  8225. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8226. for (var index = 0; index < totalIndices; index += 3) {
  8227. indices[index] = index;
  8228. indices[index + 1] = index + 1;
  8229. indices[index + 2] = index + 2;
  8230. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8231. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8232. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8233. var p1p2 = p1.subtract(p2);
  8234. var p3p2 = p3.subtract(p2);
  8235. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8236. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8237. normals.push(normal.x);
  8238. normals.push(normal.y);
  8239. normals.push(normal.z);
  8240. }
  8241. }
  8242. this.setIndices(indices);
  8243. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8244. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8245. kind = kinds[kindIndex];
  8246. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8247. }
  8248. this.releaseSubMeshes();
  8249. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8250. var previousOne = previousSubmeshes[submeshIndex];
  8251. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8252. }
  8253. this.synchronizeInstances();
  8254. };
  8255. Mesh.prototype.createInstance = function (name) {
  8256. return new BABYLON.InstancedMesh(name, this);
  8257. };
  8258. Mesh.prototype.synchronizeInstances = function () {
  8259. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8260. var instance = this.instances[instanceIndex];
  8261. instance._syncSubMeshes();
  8262. }
  8263. };
  8264. Mesh.CreateBox = function (name, size, scene, updatable) {
  8265. var box = new BABYLON.Mesh(name, scene);
  8266. var vertexData = BABYLON.VertexData.CreateBox(size);
  8267. vertexData.applyToMesh(box, updatable);
  8268. return box;
  8269. };
  8270. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8271. var sphere = new BABYLON.Mesh(name, scene);
  8272. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8273. vertexData.applyToMesh(sphere, updatable);
  8274. return sphere;
  8275. };
  8276. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8277. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8278. if (scene !== undefined) {
  8279. updatable = scene;
  8280. }
  8281. scene = subdivisions;
  8282. subdivisions = 1;
  8283. }
  8284. var cylinder = new BABYLON.Mesh(name, scene);
  8285. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8286. vertexData.applyToMesh(cylinder, updatable);
  8287. return cylinder;
  8288. };
  8289. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8290. var torus = new BABYLON.Mesh(name, scene);
  8291. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8292. vertexData.applyToMesh(torus, updatable);
  8293. return torus;
  8294. };
  8295. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8296. var torusKnot = new BABYLON.Mesh(name, scene);
  8297. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8298. vertexData.applyToMesh(torusKnot, updatable);
  8299. return torusKnot;
  8300. };
  8301. Mesh.CreateLines = function (name, points, scene, updatable) {
  8302. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8303. var vertexData = BABYLON.VertexData.CreateLines(points);
  8304. vertexData.applyToMesh(lines, updatable);
  8305. return lines;
  8306. };
  8307. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8308. var plane = new BABYLON.Mesh(name, scene);
  8309. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8310. vertexData.applyToMesh(plane, updatable);
  8311. return plane;
  8312. };
  8313. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8314. var ground = new BABYLON.GroundMesh(name, scene);
  8315. ground._setReady(false);
  8316. ground._subdivisions = subdivisions;
  8317. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8318. vertexData.applyToMesh(ground, updatable);
  8319. ground._setReady(true);
  8320. return ground;
  8321. };
  8322. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8323. var tiledGround = new BABYLON.Mesh(name, scene);
  8324. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8325. vertexData.applyToMesh(tiledGround, updatable);
  8326. return tiledGround;
  8327. };
  8328. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8329. var ground = new BABYLON.GroundMesh(name, scene);
  8330. ground._subdivisions = subdivisions;
  8331. ground._setReady(false);
  8332. var onload = function (img) {
  8333. var canvas = document.createElement("canvas");
  8334. var context = canvas.getContext("2d");
  8335. var heightMapWidth = img.width;
  8336. var heightMapHeight = img.height;
  8337. canvas.width = heightMapWidth;
  8338. canvas.height = heightMapHeight;
  8339. context.drawImage(img, 0, 0);
  8340. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8341. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8342. vertexData.applyToMesh(ground, updatable);
  8343. ground._setReady(true);
  8344. };
  8345. BABYLON.Tools.LoadImage(url, onload, function () {
  8346. }, scene.database);
  8347. return ground;
  8348. };
  8349. Mesh.MinMax = function (meshes) {
  8350. var minVector = null;
  8351. var maxVector = null;
  8352. for (var i in meshes) {
  8353. var mesh = meshes[i];
  8354. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8355. if (!minVector) {
  8356. minVector = boundingBox.minimumWorld;
  8357. maxVector = boundingBox.maximumWorld;
  8358. continue;
  8359. }
  8360. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8361. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8362. }
  8363. return {
  8364. min: minVector,
  8365. max: maxVector
  8366. };
  8367. };
  8368. Mesh.Center = function (meshesOrMinMaxVector) {
  8369. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8370. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8371. };
  8372. return Mesh;
  8373. })(BABYLON.AbstractMesh);
  8374. BABYLON.Mesh = Mesh;
  8375. })(BABYLON || (BABYLON = {}));
  8376. var __extends = this.__extends || function (d, b) {
  8377. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8378. function __() { this.constructor = d; }
  8379. __.prototype = b.prototype;
  8380. d.prototype = new __();
  8381. };
  8382. var BABYLON;
  8383. (function (BABYLON) {
  8384. var GroundMesh = (function (_super) {
  8385. __extends(GroundMesh, _super);
  8386. function GroundMesh(name, scene) {
  8387. _super.call(this, name, scene);
  8388. this.generateOctree = false;
  8389. this._worldInverse = new BABYLON.Matrix();
  8390. }
  8391. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8392. get: function () {
  8393. return this._subdivisions;
  8394. },
  8395. enumerable: true,
  8396. configurable: true
  8397. });
  8398. GroundMesh.prototype.optimize = function (chunksCount) {
  8399. this.subdivide(this._subdivisions);
  8400. this.createOrUpdateSubmeshesOctree(32);
  8401. };
  8402. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8403. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8404. this.getWorldMatrix().invertToRef(this._worldInverse);
  8405. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8406. var pickInfo = this.intersects(ray);
  8407. if (pickInfo.hit) {
  8408. return pickInfo.pickedPoint.y;
  8409. }
  8410. return 0;
  8411. };
  8412. return GroundMesh;
  8413. })(BABYLON.Mesh);
  8414. BABYLON.GroundMesh = GroundMesh;
  8415. })(BABYLON || (BABYLON = {}));
  8416. var __extends = this.__extends || function (d, b) {
  8417. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8418. function __() { this.constructor = d; }
  8419. __.prototype = b.prototype;
  8420. d.prototype = new __();
  8421. };
  8422. var BABYLON;
  8423. (function (BABYLON) {
  8424. var InstancedMesh = (function (_super) {
  8425. __extends(InstancedMesh, _super);
  8426. function InstancedMesh(name, source) {
  8427. _super.call(this, name, source.getScene());
  8428. source.instances.push(this);
  8429. this._sourceMesh = source;
  8430. this.position.copyFrom(source.position);
  8431. this.rotation.copyFrom(source.rotation);
  8432. this.scaling.copyFrom(source.scaling);
  8433. if (source.rotationQuaternion) {
  8434. this.rotationQuaternion = source.rotationQuaternion.clone();
  8435. }
  8436. this.infiniteDistance = source.infiniteDistance;
  8437. this.setPivotMatrix(source.getPivotMatrix());
  8438. this.refreshBoundingInfo();
  8439. this._syncSubMeshes();
  8440. }
  8441. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8442. get: function () {
  8443. return this._sourceMesh.receiveShadows;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(InstancedMesh.prototype, "material", {
  8449. get: function () {
  8450. return this._sourceMesh.material;
  8451. },
  8452. enumerable: true,
  8453. configurable: true
  8454. });
  8455. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8456. get: function () {
  8457. return this._sourceMesh.visibility;
  8458. },
  8459. enumerable: true,
  8460. configurable: true
  8461. });
  8462. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8463. get: function () {
  8464. return this._sourceMesh.skeleton;
  8465. },
  8466. enumerable: true,
  8467. configurable: true
  8468. });
  8469. InstancedMesh.prototype.getTotalVertices = function () {
  8470. return this._sourceMesh.getTotalVertices();
  8471. };
  8472. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8473. get: function () {
  8474. return this._sourceMesh;
  8475. },
  8476. enumerable: true,
  8477. configurable: true
  8478. });
  8479. InstancedMesh.prototype.getVerticesData = function (kind) {
  8480. return this._sourceMesh.getVerticesData(kind);
  8481. };
  8482. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8483. return this._sourceMesh.isVerticesDataPresent(kind);
  8484. };
  8485. InstancedMesh.prototype.getIndices = function () {
  8486. return this._sourceMesh.getIndices();
  8487. };
  8488. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8489. get: function () {
  8490. return this._sourceMesh._positions;
  8491. },
  8492. enumerable: true,
  8493. configurable: true
  8494. });
  8495. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8496. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8497. if (data) {
  8498. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8499. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8500. }
  8501. this._updateBoundingInfo();
  8502. };
  8503. InstancedMesh.prototype._preActivate = function () {
  8504. this.sourceMesh._preActivate();
  8505. };
  8506. InstancedMesh.prototype._activate = function (renderId) {
  8507. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8508. };
  8509. InstancedMesh.prototype._syncSubMeshes = function () {
  8510. this.releaseSubMeshes();
  8511. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8512. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8513. }
  8514. };
  8515. InstancedMesh.prototype._generatePointsArray = function () {
  8516. return this._sourceMesh._generatePointsArray();
  8517. };
  8518. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8519. var result = this._sourceMesh.createInstance(name);
  8520. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8521. this.refreshBoundingInfo();
  8522. if (newParent) {
  8523. result.parent = newParent;
  8524. }
  8525. if (!doNotCloneChildren) {
  8526. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8527. var mesh = this.getScene().meshes[index];
  8528. if (mesh.parent == this) {
  8529. mesh.clone(mesh.name, result);
  8530. }
  8531. }
  8532. }
  8533. result.computeWorldMatrix(true);
  8534. return result;
  8535. };
  8536. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8537. var index = this._sourceMesh.instances.indexOf(this);
  8538. this._sourceMesh.instances.splice(index, 1);
  8539. _super.prototype.dispose.call(this, doNotRecurse);
  8540. };
  8541. return InstancedMesh;
  8542. })(BABYLON.AbstractMesh);
  8543. BABYLON.InstancedMesh = InstancedMesh;
  8544. })(BABYLON || (BABYLON = {}));
  8545. var BABYLON;
  8546. (function (BABYLON) {
  8547. var SubMesh = (function () {
  8548. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8549. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8550. this.materialIndex = materialIndex;
  8551. this.verticesStart = verticesStart;
  8552. this.verticesCount = verticesCount;
  8553. this.indexStart = indexStart;
  8554. this.indexCount = indexCount;
  8555. this._renderId = 0;
  8556. this._mesh = mesh;
  8557. this._renderingMesh = renderingMesh || mesh;
  8558. mesh.subMeshes.push(this);
  8559. this._id = mesh.subMeshes.length - 1;
  8560. if (createBoundingBox) {
  8561. this.refreshBoundingInfo();
  8562. }
  8563. }
  8564. SubMesh.prototype.getBoundingInfo = function () {
  8565. return this._boundingInfo;
  8566. };
  8567. SubMesh.prototype.getMesh = function () {
  8568. return this._mesh;
  8569. };
  8570. SubMesh.prototype.getRenderingMesh = function () {
  8571. return this._renderingMesh;
  8572. };
  8573. SubMesh.prototype.getMaterial = function () {
  8574. var rootMaterial = this._renderingMesh.material;
  8575. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8576. var multiMaterial = rootMaterial;
  8577. return multiMaterial.getSubMaterial(this.materialIndex);
  8578. }
  8579. if (!rootMaterial) {
  8580. return this._mesh.getScene().defaultMaterial;
  8581. }
  8582. return rootMaterial;
  8583. };
  8584. SubMesh.prototype.refreshBoundingInfo = function () {
  8585. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8586. if (!data) {
  8587. this._boundingInfo = this._mesh._boundingInfo;
  8588. return;
  8589. }
  8590. var indices = this._renderingMesh.getIndices();
  8591. var extend;
  8592. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8593. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8594. } else {
  8595. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8596. }
  8597. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8598. };
  8599. SubMesh.prototype._checkCollision = function (collider) {
  8600. return this._boundingInfo._checkCollision(collider);
  8601. };
  8602. SubMesh.prototype.updateBoundingInfo = function (world) {
  8603. if (!this._boundingInfo) {
  8604. this.refreshBoundingInfo();
  8605. }
  8606. this._boundingInfo._update(world);
  8607. };
  8608. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8609. return this._boundingInfo.isInFrustum(frustumPlanes);
  8610. };
  8611. SubMesh.prototype.render = function () {
  8612. this._renderingMesh.render(this);
  8613. };
  8614. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8615. if (!this._linesIndexBuffer) {
  8616. var linesIndices = [];
  8617. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8618. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8619. }
  8620. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8621. this.linesIndexCount = linesIndices.length;
  8622. }
  8623. return this._linesIndexBuffer;
  8624. };
  8625. SubMesh.prototype.canIntersects = function (ray) {
  8626. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8627. };
  8628. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8629. var intersectInfo = null;
  8630. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8631. var p0 = positions[indices[index]];
  8632. var p1 = positions[indices[index + 1]];
  8633. var p2 = positions[indices[index + 2]];
  8634. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8635. if (currentIntersectInfo) {
  8636. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8637. intersectInfo = currentIntersectInfo;
  8638. intersectInfo.faceId = index / 3;
  8639. if (fastCheck) {
  8640. break;
  8641. }
  8642. }
  8643. }
  8644. }
  8645. return intersectInfo;
  8646. };
  8647. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8648. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8649. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8650. return result;
  8651. };
  8652. SubMesh.prototype.dispose = function () {
  8653. if (this._linesIndexBuffer) {
  8654. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8655. this._linesIndexBuffer = null;
  8656. }
  8657. var index = this._mesh.subMeshes.indexOf(this);
  8658. this._mesh.subMeshes.splice(index, 1);
  8659. };
  8660. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8661. var minVertexIndex = Number.MAX_VALUE;
  8662. var maxVertexIndex = -Number.MAX_VALUE;
  8663. renderingMesh = renderingMesh || mesh;
  8664. var indices = renderingMesh.getIndices();
  8665. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8666. var vertexIndex = indices[index];
  8667. if (vertexIndex < minVertexIndex)
  8668. minVertexIndex = vertexIndex;
  8669. if (vertexIndex > maxVertexIndex)
  8670. maxVertexIndex = vertexIndex;
  8671. }
  8672. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8673. };
  8674. return SubMesh;
  8675. })();
  8676. BABYLON.SubMesh = SubMesh;
  8677. })(BABYLON || (BABYLON = {}));
  8678. var BABYLON;
  8679. (function (BABYLON) {
  8680. var BaseTexture = (function () {
  8681. function BaseTexture(scene) {
  8682. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8683. this.hasAlpha = false;
  8684. this.getAlphaFromRGB = false;
  8685. this.level = 1;
  8686. this.isCube = false;
  8687. this.isRenderTarget = false;
  8688. this.animations = new Array();
  8689. this.coordinatesIndex = 0;
  8690. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8691. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8692. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8693. this.anisotropicFilteringLevel = 4;
  8694. this._scene = scene;
  8695. this._scene.textures.push(this);
  8696. }
  8697. BaseTexture.prototype.getScene = function () {
  8698. return this._scene;
  8699. };
  8700. BaseTexture.prototype.getTextureMatrix = function () {
  8701. return null;
  8702. };
  8703. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8704. return null;
  8705. };
  8706. BaseTexture.prototype.getInternalTexture = function () {
  8707. return this._texture;
  8708. };
  8709. BaseTexture.prototype.isReady = function () {
  8710. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8711. return true;
  8712. }
  8713. if (this._texture) {
  8714. return this._texture.isReady;
  8715. }
  8716. return false;
  8717. };
  8718. BaseTexture.prototype.getSize = function () {
  8719. if (this._texture._width) {
  8720. return { width: this._texture._width, height: this._texture._height };
  8721. }
  8722. if (this._texture._size) {
  8723. return { width: this._texture._size, height: this._texture._size };
  8724. }
  8725. return { width: 0, height: 0 };
  8726. };
  8727. BaseTexture.prototype.getBaseSize = function () {
  8728. if (!this.isReady())
  8729. return { width: 0, height: 0 };
  8730. if (this._texture._size) {
  8731. return { width: this._texture._size, height: this._texture._size };
  8732. }
  8733. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8734. };
  8735. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8736. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8737. for (var index = 0; index < texturesCache.length; index++) {
  8738. var texturesCacheEntry = texturesCache[index];
  8739. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8740. texturesCacheEntry.references++;
  8741. return texturesCacheEntry;
  8742. }
  8743. }
  8744. return null;
  8745. };
  8746. BaseTexture.prototype.delayLoad = function () {
  8747. };
  8748. BaseTexture.prototype.releaseInternalTexture = function () {
  8749. if (!this._texture) {
  8750. return;
  8751. }
  8752. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8753. this._texture.references--;
  8754. if (this._texture.references == 0) {
  8755. var index = texturesCache.indexOf(this._texture);
  8756. texturesCache.splice(index, 1);
  8757. this._scene.getEngine()._releaseTexture(this._texture);
  8758. delete this._texture;
  8759. }
  8760. };
  8761. BaseTexture.prototype.clone = function () {
  8762. return null;
  8763. };
  8764. BaseTexture.prototype.dispose = function () {
  8765. var index = this._scene.textures.indexOf(this);
  8766. if (index >= 0) {
  8767. this._scene.textures.splice(index, 1);
  8768. }
  8769. if (this._texture === undefined) {
  8770. return;
  8771. }
  8772. this.releaseInternalTexture();
  8773. if (this.onDispose) {
  8774. this.onDispose();
  8775. }
  8776. };
  8777. return BaseTexture;
  8778. })();
  8779. BABYLON.BaseTexture = BaseTexture;
  8780. })(BABYLON || (BABYLON = {}));
  8781. var BABYLON;
  8782. (function (BABYLON) {
  8783. var RenderingGroup = (function () {
  8784. function RenderingGroup(index, scene) {
  8785. this.index = index;
  8786. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8787. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8788. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8789. this._scene = scene;
  8790. }
  8791. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8792. if (customRenderFunction) {
  8793. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8794. return true;
  8795. }
  8796. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8797. return false;
  8798. }
  8799. var engine = this._scene.getEngine();
  8800. var subIndex;
  8801. var submesh;
  8802. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8803. submesh = this._opaqueSubMeshes.data[subIndex];
  8804. this._activeVertices += submesh.verticesCount;
  8805. submesh.render();
  8806. }
  8807. engine.setAlphaTesting(true);
  8808. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8809. submesh = this._alphaTestSubMeshes.data[subIndex];
  8810. this._activeVertices += submesh.verticesCount;
  8811. submesh.render();
  8812. }
  8813. engine.setAlphaTesting(false);
  8814. if (beforeTransparents) {
  8815. beforeTransparents();
  8816. }
  8817. if (this._transparentSubMeshes.length) {
  8818. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8819. submesh = this._transparentSubMeshes.data[subIndex];
  8820. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8821. }
  8822. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8823. sortedArray.sort(function (a, b) {
  8824. if (a._distanceToCamera < b._distanceToCamera) {
  8825. return 1;
  8826. }
  8827. if (a._distanceToCamera > b._distanceToCamera) {
  8828. return -1;
  8829. }
  8830. return 0;
  8831. });
  8832. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8833. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8834. submesh = sortedArray[subIndex];
  8835. this._activeVertices += submesh.verticesCount;
  8836. submesh.render();
  8837. }
  8838. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8839. }
  8840. return true;
  8841. };
  8842. RenderingGroup.prototype.prepare = function () {
  8843. this._opaqueSubMeshes.reset();
  8844. this._transparentSubMeshes.reset();
  8845. this._alphaTestSubMeshes.reset();
  8846. };
  8847. RenderingGroup.prototype.dispatch = function (subMesh) {
  8848. var material = subMesh.getMaterial();
  8849. var mesh = subMesh.getMesh();
  8850. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8851. if (material.alpha > 0 || mesh.visibility < 1.0) {
  8852. this._transparentSubMeshes.push(subMesh);
  8853. }
  8854. } else if (material.needAlphaTesting()) {
  8855. this._alphaTestSubMeshes.push(subMesh);
  8856. } else {
  8857. this._opaqueSubMeshes.push(subMesh);
  8858. }
  8859. };
  8860. return RenderingGroup;
  8861. })();
  8862. BABYLON.RenderingGroup = RenderingGroup;
  8863. })(BABYLON || (BABYLON = {}));
  8864. var BABYLON;
  8865. (function (BABYLON) {
  8866. var RenderingManager = (function () {
  8867. function RenderingManager(scene) {
  8868. this._renderingGroups = new Array();
  8869. this._scene = scene;
  8870. }
  8871. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  8872. if (this._scene._activeParticleSystems.length === 0) {
  8873. return;
  8874. }
  8875. var beforeParticlesDate = new Date().getTime();
  8876. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  8877. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  8878. if (particleSystem.renderingGroupId !== index) {
  8879. continue;
  8880. }
  8881. this._clearDepthBuffer();
  8882. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  8883. this._scene._activeParticles += particleSystem.render();
  8884. }
  8885. }
  8886. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  8887. };
  8888. RenderingManager.prototype._renderSprites = function (index) {
  8889. if (this._scene.spriteManagers.length === 0) {
  8890. return;
  8891. }
  8892. var beforeSpritessDate = new Date().getTime();
  8893. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  8894. var spriteManager = this._scene.spriteManagers[id];
  8895. if (spriteManager.renderingGroupId === index) {
  8896. this._clearDepthBuffer();
  8897. spriteManager.render();
  8898. }
  8899. }
  8900. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  8901. };
  8902. RenderingManager.prototype._clearDepthBuffer = function () {
  8903. if (this._depthBufferAlreadyCleaned) {
  8904. return;
  8905. }
  8906. this._scene.getEngine().clear(0, false, true);
  8907. this._depthBufferAlreadyCleaned = true;
  8908. };
  8909. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  8910. var _this = this;
  8911. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  8912. this._depthBufferAlreadyCleaned = false;
  8913. var renderingGroup = this._renderingGroups[index];
  8914. if (renderingGroup) {
  8915. this._clearDepthBuffer();
  8916. if (!renderingGroup.render(customRenderFunction, function () {
  8917. if (renderSprites) {
  8918. _this._renderSprites(index);
  8919. }
  8920. })) {
  8921. this._renderingGroups.splice(index, 1);
  8922. }
  8923. } else if (renderSprites) {
  8924. this._renderSprites(index);
  8925. }
  8926. if (renderParticles) {
  8927. this._renderParticles(index, activeMeshes);
  8928. }
  8929. }
  8930. };
  8931. RenderingManager.prototype.reset = function () {
  8932. for (var index in this._renderingGroups) {
  8933. var renderingGroup = this._renderingGroups[index];
  8934. renderingGroup.prepare();
  8935. }
  8936. };
  8937. RenderingManager.prototype.dispatch = function (subMesh) {
  8938. var mesh = subMesh.getMesh();
  8939. var renderingGroupId = mesh.renderingGroupId || 0;
  8940. if (!this._renderingGroups[renderingGroupId]) {
  8941. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  8942. }
  8943. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  8944. };
  8945. RenderingManager.MAX_RENDERINGGROUPS = 4;
  8946. return RenderingManager;
  8947. })();
  8948. BABYLON.RenderingManager = RenderingManager;
  8949. })(BABYLON || (BABYLON = {}));
  8950. var __extends = this.__extends || function (d, b) {
  8951. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8952. function __() { this.constructor = d; }
  8953. __.prototype = b.prototype;
  8954. d.prototype = new __();
  8955. };
  8956. var BABYLON;
  8957. (function (BABYLON) {
  8958. var Texture = (function (_super) {
  8959. __extends(Texture, _super);
  8960. function Texture(url, scene, noMipmap, invertY, samplingMode) {
  8961. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  8962. _super.call(this, scene);
  8963. this.uOffset = 0;
  8964. this.vOffset = 0;
  8965. this.uScale = 1.0;
  8966. this.vScale = 1.0;
  8967. this.uAng = 0;
  8968. this.vAng = 0;
  8969. this.wAng = 0;
  8970. this.name = url;
  8971. this.url = url;
  8972. this._noMipmap = noMipmap;
  8973. this._invertY = invertY;
  8974. this._samplingMode = samplingMode;
  8975. if (!url) {
  8976. return;
  8977. }
  8978. this._texture = this._getFromCache(url, noMipmap);
  8979. if (!this._texture) {
  8980. if (!scene.useDelayedTextureLoading) {
  8981. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode);
  8982. } else {
  8983. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  8984. }
  8985. }
  8986. }
  8987. Texture.prototype.delayLoad = function () {
  8988. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8989. return;
  8990. }
  8991. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8992. this._texture = this._getFromCache(this.url, this._noMipmap);
  8993. if (!this._texture) {
  8994. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  8995. }
  8996. };
  8997. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  8998. x -= this.uOffset + 0.5;
  8999. y -= this.vOffset + 0.5;
  9000. z -= 0.5;
  9001. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9002. t.x *= this.uScale;
  9003. t.y *= this.vScale;
  9004. t.x += 0.5;
  9005. t.y += 0.5;
  9006. t.z += 0.5;
  9007. };
  9008. Texture.prototype.getTextureMatrix = function () {
  9009. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  9010. return this._cachedTextureMatrix;
  9011. }
  9012. this._cachedUOffset = this.uOffset;
  9013. this._cachedVOffset = this.vOffset;
  9014. this._cachedUScale = this.uScale;
  9015. this._cachedVScale = this.vScale;
  9016. this._cachedUAng = this.uAng;
  9017. this._cachedVAng = this.vAng;
  9018. this._cachedWAng = this.wAng;
  9019. if (!this._cachedTextureMatrix) {
  9020. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9021. this._rowGenerationMatrix = new BABYLON.Matrix();
  9022. this._t0 = BABYLON.Vector3.Zero();
  9023. this._t1 = BABYLON.Vector3.Zero();
  9024. this._t2 = BABYLON.Vector3.Zero();
  9025. }
  9026. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9027. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9028. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9029. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9030. this._t1.subtractInPlace(this._t0);
  9031. this._t2.subtractInPlace(this._t0);
  9032. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9033. this._cachedTextureMatrix.m[0] = this._t1.x;
  9034. this._cachedTextureMatrix.m[1] = this._t1.y;
  9035. this._cachedTextureMatrix.m[2] = this._t1.z;
  9036. this._cachedTextureMatrix.m[4] = this._t2.x;
  9037. this._cachedTextureMatrix.m[5] = this._t2.y;
  9038. this._cachedTextureMatrix.m[6] = this._t2.z;
  9039. this._cachedTextureMatrix.m[8] = this._t0.x;
  9040. this._cachedTextureMatrix.m[9] = this._t0.y;
  9041. this._cachedTextureMatrix.m[10] = this._t0.z;
  9042. return this._cachedTextureMatrix;
  9043. };
  9044. Texture.prototype.getReflectionTextureMatrix = function () {
  9045. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9046. return this._cachedTextureMatrix;
  9047. }
  9048. if (!this._cachedTextureMatrix) {
  9049. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9050. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9051. }
  9052. switch (this.coordinatesMode) {
  9053. case BABYLON.Texture.SPHERICAL_MODE:
  9054. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9055. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9056. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9057. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9058. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9059. break;
  9060. case BABYLON.Texture.PLANAR_MODE:
  9061. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9062. this._cachedTextureMatrix[0] = this.uScale;
  9063. this._cachedTextureMatrix[5] = this.vScale;
  9064. this._cachedTextureMatrix[12] = this.uOffset;
  9065. this._cachedTextureMatrix[13] = this.vOffset;
  9066. break;
  9067. case BABYLON.Texture.PROJECTION_MODE:
  9068. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9069. this._projectionModeMatrix.m[0] = 0.5;
  9070. this._projectionModeMatrix.m[5] = -0.5;
  9071. this._projectionModeMatrix.m[10] = 0.0;
  9072. this._projectionModeMatrix.m[12] = 0.5;
  9073. this._projectionModeMatrix.m[13] = 0.5;
  9074. this._projectionModeMatrix.m[14] = 1.0;
  9075. this._projectionModeMatrix.m[15] = 1.0;
  9076. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9077. break;
  9078. default:
  9079. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9080. break;
  9081. }
  9082. return this._cachedTextureMatrix;
  9083. };
  9084. Texture.prototype.clone = function () {
  9085. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9086. newTexture.hasAlpha = this.hasAlpha;
  9087. newTexture.level = this.level;
  9088. newTexture.wrapU = this.wrapU;
  9089. newTexture.wrapV = this.wrapV;
  9090. newTexture.coordinatesIndex = this.coordinatesIndex;
  9091. newTexture.coordinatesMode = this.coordinatesMode;
  9092. newTexture.uOffset = this.uOffset;
  9093. newTexture.vOffset = this.vOffset;
  9094. newTexture.uScale = this.uScale;
  9095. newTexture.vScale = this.vScale;
  9096. newTexture.uAng = this.uAng;
  9097. newTexture.vAng = this.vAng;
  9098. newTexture.wAng = this.wAng;
  9099. return newTexture;
  9100. };
  9101. Texture.NEAREST_SAMPLINGMODE = 1;
  9102. Texture.BILINEAR_SAMPLINGMODE = 2;
  9103. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9104. Texture.EXPLICIT_MODE = 0;
  9105. Texture.SPHERICAL_MODE = 1;
  9106. Texture.PLANAR_MODE = 2;
  9107. Texture.CUBIC_MODE = 3;
  9108. Texture.PROJECTION_MODE = 4;
  9109. Texture.SKYBOX_MODE = 5;
  9110. Texture.CLAMP_ADDRESSMODE = 0;
  9111. Texture.WRAP_ADDRESSMODE = 1;
  9112. Texture.MIRROR_ADDRESSMODE = 2;
  9113. return Texture;
  9114. })(BABYLON.BaseTexture);
  9115. BABYLON.Texture = Texture;
  9116. })(BABYLON || (BABYLON = {}));
  9117. var __extends = this.__extends || function (d, b) {
  9118. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9119. function __() { this.constructor = d; }
  9120. __.prototype = b.prototype;
  9121. d.prototype = new __();
  9122. };
  9123. var BABYLON;
  9124. (function (BABYLON) {
  9125. var CubeTexture = (function (_super) {
  9126. __extends(CubeTexture, _super);
  9127. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9128. _super.call(this, scene);
  9129. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9130. this.name = rootUrl;
  9131. this.url = rootUrl;
  9132. this._noMipmap = noMipmap;
  9133. this.hasAlpha = false;
  9134. this._texture = this._getFromCache(rootUrl, noMipmap);
  9135. if (!extensions) {
  9136. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9137. }
  9138. this._extensions = extensions;
  9139. if (!this._texture) {
  9140. if (!scene.useDelayedTextureLoading) {
  9141. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9142. } else {
  9143. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9144. }
  9145. }
  9146. this.isCube = true;
  9147. this._textureMatrix = BABYLON.Matrix.Identity();
  9148. }
  9149. CubeTexture.prototype.clone = function () {
  9150. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9151. newTexture.level = this.level;
  9152. newTexture.wrapU = this.wrapU;
  9153. newTexture.wrapV = this.wrapV;
  9154. newTexture.coordinatesIndex = this.coordinatesIndex;
  9155. newTexture.coordinatesMode = this.coordinatesMode;
  9156. return newTexture;
  9157. };
  9158. CubeTexture.prototype.delayLoad = function () {
  9159. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9160. return;
  9161. }
  9162. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9163. this._texture = this._getFromCache(this.url, this._noMipmap);
  9164. if (!this._texture) {
  9165. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9166. }
  9167. };
  9168. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9169. return this._textureMatrix;
  9170. };
  9171. return CubeTexture;
  9172. })(BABYLON.BaseTexture);
  9173. BABYLON.CubeTexture = CubeTexture;
  9174. })(BABYLON || (BABYLON = {}));
  9175. var __extends = this.__extends || function (d, b) {
  9176. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9177. function __() { this.constructor = d; }
  9178. __.prototype = b.prototype;
  9179. d.prototype = new __();
  9180. };
  9181. var BABYLON;
  9182. (function (BABYLON) {
  9183. var RenderTargetTexture = (function (_super) {
  9184. __extends(RenderTargetTexture, _super);
  9185. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9186. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9187. _super.call(this, null, scene, !generateMipMaps);
  9188. this.renderList = new Array();
  9189. this.renderParticles = true;
  9190. this.renderSprites = false;
  9191. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9192. this._currentRefreshId = -1;
  9193. this._refreshRate = 1;
  9194. this.name = name;
  9195. this.isRenderTarget = true;
  9196. this._size = size;
  9197. this._generateMipMaps = generateMipMaps;
  9198. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9199. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9200. this._renderingManager = new BABYLON.RenderingManager(scene);
  9201. }
  9202. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9203. this._currentRefreshId = -1;
  9204. };
  9205. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9206. get: function () {
  9207. return this._refreshRate;
  9208. },
  9209. set: function (value) {
  9210. this._refreshRate = value;
  9211. this.resetRefreshCounter();
  9212. },
  9213. enumerable: true,
  9214. configurable: true
  9215. });
  9216. RenderTargetTexture.prototype._shouldRender = function () {
  9217. if (this._currentRefreshId === -1) {
  9218. this._currentRefreshId = 1;
  9219. return true;
  9220. }
  9221. if (this.refreshRate == this._currentRefreshId) {
  9222. this._currentRefreshId = 1;
  9223. return true;
  9224. }
  9225. this._currentRefreshId++;
  9226. return false;
  9227. };
  9228. RenderTargetTexture.prototype.getRenderSize = function () {
  9229. return this._size;
  9230. };
  9231. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9232. this.releaseInternalTexture();
  9233. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9234. };
  9235. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9236. var scene = this.getScene();
  9237. var engine = scene.getEngine();
  9238. if (this._waitingRenderList) {
  9239. this.renderList = [];
  9240. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9241. var id = this._waitingRenderList[index];
  9242. this.renderList.push(scene.getMeshByID(id));
  9243. }
  9244. delete this._waitingRenderList;
  9245. }
  9246. if (!this.renderList) {
  9247. return;
  9248. }
  9249. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9250. engine.bindFramebuffer(this._texture);
  9251. }
  9252. engine.clear(scene.clearColor, true, true);
  9253. this._renderingManager.reset();
  9254. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9255. var mesh = this.renderList[meshIndex];
  9256. if (mesh) {
  9257. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9258. this.resetRefreshCounter();
  9259. continue;
  9260. }
  9261. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9262. mesh._activate(scene.getRenderId());
  9263. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9264. var subMesh = mesh.subMeshes[subIndex];
  9265. scene._activeVertices += subMesh.verticesCount;
  9266. this._renderingManager.dispatch(subMesh);
  9267. }
  9268. }
  9269. }
  9270. }
  9271. if (!this._doNotChangeAspectRatio) {
  9272. scene.updateTransformMatrix(true);
  9273. }
  9274. if (this.onBeforeRender) {
  9275. this.onBeforeRender();
  9276. }
  9277. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9278. if (useCameraPostProcess) {
  9279. scene.postProcessManager._finalizeFrame(false, this._texture);
  9280. }
  9281. if (this.onAfterRender) {
  9282. this.onAfterRender();
  9283. }
  9284. engine.unBindFramebuffer(this._texture);
  9285. if (!this._doNotChangeAspectRatio) {
  9286. scene.updateTransformMatrix(true);
  9287. }
  9288. };
  9289. RenderTargetTexture.prototype.clone = function () {
  9290. var textureSize = this.getSize();
  9291. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9292. newTexture.hasAlpha = this.hasAlpha;
  9293. newTexture.level = this.level;
  9294. newTexture.coordinatesMode = this.coordinatesMode;
  9295. newTexture.renderList = this.renderList.slice(0);
  9296. return newTexture;
  9297. };
  9298. return RenderTargetTexture;
  9299. })(BABYLON.Texture);
  9300. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9301. })(BABYLON || (BABYLON = {}));
  9302. var __extends = this.__extends || function (d, b) {
  9303. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9304. function __() { this.constructor = d; }
  9305. __.prototype = b.prototype;
  9306. d.prototype = new __();
  9307. };
  9308. var BABYLON;
  9309. (function (BABYLON) {
  9310. var MirrorTexture = (function (_super) {
  9311. __extends(MirrorTexture, _super);
  9312. function MirrorTexture(name, size, scene, generateMipMaps) {
  9313. var _this = this;
  9314. _super.call(this, name, size, scene, generateMipMaps, true);
  9315. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9316. this._transformMatrix = BABYLON.Matrix.Zero();
  9317. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9318. this.onBeforeRender = function () {
  9319. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9320. _this._savedViewMatrix = scene.getViewMatrix();
  9321. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9322. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9323. scene.clipPlane = _this.mirrorPlane;
  9324. scene.getEngine().cullBackFaces = false;
  9325. };
  9326. this.onAfterRender = function () {
  9327. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9328. scene.getEngine().cullBackFaces = true;
  9329. delete scene.clipPlane;
  9330. };
  9331. }
  9332. MirrorTexture.prototype.clone = function () {
  9333. var textureSize = this.getSize();
  9334. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9335. newTexture.hasAlpha = this.hasAlpha;
  9336. newTexture.level = this.level;
  9337. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9338. newTexture.renderList = this.renderList.slice(0);
  9339. return newTexture;
  9340. };
  9341. return MirrorTexture;
  9342. })(BABYLON.RenderTargetTexture);
  9343. BABYLON.MirrorTexture = MirrorTexture;
  9344. })(BABYLON || (BABYLON = {}));
  9345. var __extends = this.__extends || function (d, b) {
  9346. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9347. function __() { this.constructor = d; }
  9348. __.prototype = b.prototype;
  9349. d.prototype = new __();
  9350. };
  9351. var BABYLON;
  9352. (function (BABYLON) {
  9353. var DynamicTexture = (function (_super) {
  9354. __extends(DynamicTexture, _super);
  9355. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9356. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9357. _super.call(this, null, scene, !generateMipMaps);
  9358. this.name = name;
  9359. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9360. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9361. this._generateMipMaps = generateMipMaps;
  9362. if (options.getContext) {
  9363. this._canvas = options;
  9364. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9365. } else {
  9366. this._canvas = document.createElement("canvas");
  9367. if (options.width) {
  9368. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9369. } else {
  9370. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9371. }
  9372. }
  9373. var textureSize = this.getSize();
  9374. this._canvas.width = textureSize.width;
  9375. this._canvas.height = textureSize.height;
  9376. this._context = this._canvas.getContext("2d");
  9377. }
  9378. DynamicTexture.prototype.getContext = function () {
  9379. return this._context;
  9380. };
  9381. DynamicTexture.prototype.update = function (invertY) {
  9382. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9383. };
  9384. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9385. var size = this.getSize();
  9386. if (clearColor) {
  9387. this._context.fillStyle = clearColor;
  9388. this._context.fillRect(0, 0, size.width, size.height);
  9389. }
  9390. this._context.font = font;
  9391. if (x === null) {
  9392. var textSize = this._context.measureText(text);
  9393. x = (size.width - textSize.width) / 2;
  9394. }
  9395. this._context.fillStyle = color;
  9396. this._context.fillText(text, x, y);
  9397. this.update(invertY);
  9398. };
  9399. DynamicTexture.prototype.clone = function () {
  9400. var textureSize = this.getSize();
  9401. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9402. newTexture.hasAlpha = this.hasAlpha;
  9403. newTexture.level = this.level;
  9404. newTexture.wrapU = this.wrapU;
  9405. newTexture.wrapV = this.wrapV;
  9406. return newTexture;
  9407. };
  9408. return DynamicTexture;
  9409. })(BABYLON.Texture);
  9410. BABYLON.DynamicTexture = DynamicTexture;
  9411. })(BABYLON || (BABYLON = {}));
  9412. var __extends = this.__extends || function (d, b) {
  9413. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9414. function __() { this.constructor = d; }
  9415. __.prototype = b.prototype;
  9416. d.prototype = new __();
  9417. };
  9418. var BABYLON;
  9419. (function (BABYLON) {
  9420. var VideoTexture = (function (_super) {
  9421. __extends(VideoTexture, _super);
  9422. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9423. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9424. var _this = this;
  9425. _super.call(this, null, scene, !generateMipMaps, invertY);
  9426. this._autoLaunch = true;
  9427. this.name = name;
  9428. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9429. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9430. var requiredWidth = size.width || size;
  9431. var requiredHeight = size.height || size;
  9432. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9433. var textureSize = this.getSize();
  9434. this.video = document.createElement("video");
  9435. this.video.width = textureSize.width;
  9436. this.video.height = textureSize.height;
  9437. this.video.autoplay = false;
  9438. this.video.loop = true;
  9439. this.video.addEventListener("canplaythrough", function () {
  9440. if (_this._texture) {
  9441. _this._texture.isReady = true;
  9442. }
  9443. });
  9444. urls.forEach(function (url) {
  9445. var source = document.createElement("source");
  9446. source.src = url;
  9447. _this.video.appendChild(source);
  9448. });
  9449. this._lastUpdate = new Date().getTime();
  9450. }
  9451. VideoTexture.prototype.update = function () {
  9452. if (this._autoLaunch) {
  9453. this._autoLaunch = false;
  9454. this.video.play();
  9455. }
  9456. var now = new Date().getTime();
  9457. if (now - this._lastUpdate < 15) {
  9458. return false;
  9459. }
  9460. this._lastUpdate = now;
  9461. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9462. return true;
  9463. };
  9464. return VideoTexture;
  9465. })(BABYLON.Texture);
  9466. BABYLON.VideoTexture = VideoTexture;
  9467. })(BABYLON || (BABYLON = {}));
  9468. var BABYLON;
  9469. (function (BABYLON) {
  9470. var EffectFallbacks = (function () {
  9471. function EffectFallbacks() {
  9472. this._defines = {};
  9473. this._currentRank = 32;
  9474. this._maxRank = -1;
  9475. }
  9476. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9477. if (!this._defines[rank]) {
  9478. if (rank < this._currentRank) {
  9479. this._currentRank = rank;
  9480. }
  9481. if (rank > this._maxRank) {
  9482. this._maxRank = rank;
  9483. }
  9484. this._defines[rank] = new Array();
  9485. }
  9486. this._defines[rank].push(define);
  9487. };
  9488. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9489. get: function () {
  9490. return this._currentRank <= this._maxRank;
  9491. },
  9492. enumerable: true,
  9493. configurable: true
  9494. });
  9495. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9496. var currentFallbacks = this._defines[this._currentRank];
  9497. for (var index = 0; index < currentFallbacks.length; index++) {
  9498. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9499. }
  9500. this._currentRank++;
  9501. return currentDefines;
  9502. };
  9503. return EffectFallbacks;
  9504. })();
  9505. BABYLON.EffectFallbacks = EffectFallbacks;
  9506. var Effect = (function () {
  9507. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9508. var _this = this;
  9509. this._isReady = false;
  9510. this._compilationError = "";
  9511. this._valueCache = [];
  9512. this._engine = engine;
  9513. this.name = baseName;
  9514. this.defines = defines;
  9515. this._uniformsNames = uniformsNames.concat(samplers);
  9516. this._samplers = samplers;
  9517. this._attributesNames = attributesNames;
  9518. this.onError = onError;
  9519. this.onCompiled = onCompiled;
  9520. var vertexSource;
  9521. var fragmentSource;
  9522. if (baseName.vertexElement) {
  9523. vertexSource = document.getElementById(baseName.vertexElement);
  9524. } else {
  9525. vertexSource = baseName.vertex || baseName;
  9526. }
  9527. if (baseName.fragmentElement) {
  9528. fragmentSource = document.getElementById(baseName.fragmentElement);
  9529. } else {
  9530. fragmentSource = baseName.fragment || baseName;
  9531. }
  9532. this._loadVertexShader(vertexSource, function (vertexCode) {
  9533. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9534. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9535. });
  9536. });
  9537. }
  9538. Effect.prototype.isReady = function () {
  9539. return this._isReady;
  9540. };
  9541. Effect.prototype.getProgram = function () {
  9542. return this._program;
  9543. };
  9544. Effect.prototype.getAttributesNames = function () {
  9545. return this._attributesNames;
  9546. };
  9547. Effect.prototype.getAttributeLocation = function (index) {
  9548. return this._attributes[index];
  9549. };
  9550. Effect.prototype.getAttributeLocationByName = function (name) {
  9551. var index = this._attributesNames.indexOf(name);
  9552. return this._attributes[index];
  9553. };
  9554. Effect.prototype.getAttributesCount = function () {
  9555. return this._attributes.length;
  9556. };
  9557. Effect.prototype.getUniformIndex = function (uniformName) {
  9558. return this._uniformsNames.indexOf(uniformName);
  9559. };
  9560. Effect.prototype.getUniform = function (uniformName) {
  9561. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9562. };
  9563. Effect.prototype.getSamplers = function () {
  9564. return this._samplers;
  9565. };
  9566. Effect.prototype.getCompilationError = function () {
  9567. return this._compilationError;
  9568. };
  9569. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9570. if (vertex instanceof HTMLElement) {
  9571. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9572. callback(vertexCode);
  9573. return;
  9574. }
  9575. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9576. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9577. return;
  9578. }
  9579. var vertexShaderUrl;
  9580. if (vertex[0] === ".") {
  9581. vertexShaderUrl = vertex;
  9582. } else {
  9583. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9584. }
  9585. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9586. };
  9587. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9588. if (fragment instanceof HTMLElement) {
  9589. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9590. callback(fragmentCode);
  9591. return;
  9592. }
  9593. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9594. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9595. return;
  9596. }
  9597. var fragmentShaderUrl;
  9598. if (fragment[0] === ".") {
  9599. fragmentShaderUrl = fragment;
  9600. } else {
  9601. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9602. }
  9603. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9604. };
  9605. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9606. try {
  9607. var engine = this._engine;
  9608. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9609. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9610. this._attributes = engine.getAttributes(this._program, attributesNames);
  9611. for (var index = 0; index < this._samplers.length; index++) {
  9612. var sampler = this.getUniform(this._samplers[index]);
  9613. if (sampler == null) {
  9614. this._samplers.splice(index, 1);
  9615. index--;
  9616. }
  9617. }
  9618. engine.bindSamplers(this);
  9619. this._isReady = true;
  9620. if (this.onCompiled) {
  9621. this.onCompiled(this);
  9622. }
  9623. } catch (e) {
  9624. if (fallbacks && fallbacks.isMoreFallbacks) {
  9625. defines = fallbacks.reduce(defines);
  9626. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9627. } else {
  9628. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9629. BABYLON.Tools.Error("Defines: " + defines);
  9630. BABYLON.Tools.Error("Error: " + e.message);
  9631. this._compilationError = e.message;
  9632. if (this.onError) {
  9633. this.onError(this, this._compilationError);
  9634. }
  9635. }
  9636. }
  9637. };
  9638. Effect.prototype._bindTexture = function (channel, texture) {
  9639. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9640. };
  9641. Effect.prototype.setTexture = function (channel, texture) {
  9642. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9643. };
  9644. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9645. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9646. };
  9647. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9648. if (!this._valueCache[uniformName]) {
  9649. this._valueCache[uniformName] = [x, y];
  9650. return;
  9651. }
  9652. this._valueCache[uniformName][0] = x;
  9653. this._valueCache[uniformName][1] = y;
  9654. };
  9655. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9656. if (!this._valueCache[uniformName]) {
  9657. this._valueCache[uniformName] = [x, y, z];
  9658. return;
  9659. }
  9660. this._valueCache[uniformName][0] = x;
  9661. this._valueCache[uniformName][1] = y;
  9662. this._valueCache[uniformName][2] = z;
  9663. };
  9664. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9665. if (!this._valueCache[uniformName]) {
  9666. this._valueCache[uniformName] = [x, y, z, w];
  9667. return;
  9668. }
  9669. this._valueCache[uniformName][0] = x;
  9670. this._valueCache[uniformName][1] = y;
  9671. this._valueCache[uniformName][2] = z;
  9672. this._valueCache[uniformName][3] = w;
  9673. };
  9674. Effect.prototype.setArray = function (uniformName, array) {
  9675. this._engine.setArray(this.getUniform(uniformName), array);
  9676. return this;
  9677. };
  9678. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9679. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9680. return this;
  9681. };
  9682. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9683. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9684. return this;
  9685. };
  9686. Effect.prototype.setFloat = function (uniformName, value) {
  9687. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9688. return this;
  9689. this._valueCache[uniformName] = value;
  9690. this._engine.setFloat(this.getUniform(uniformName), value);
  9691. return this;
  9692. };
  9693. Effect.prototype.setBool = function (uniformName, bool) {
  9694. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9695. return this;
  9696. this._valueCache[uniformName] = bool;
  9697. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9698. return this;
  9699. };
  9700. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9701. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9702. return this;
  9703. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9704. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9705. return this;
  9706. };
  9707. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9708. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9709. return this;
  9710. this._cacheFloat2(uniformName, x, y);
  9711. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9712. return this;
  9713. };
  9714. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9715. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9716. return this;
  9717. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9718. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9719. return this;
  9720. };
  9721. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9722. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9723. return this;
  9724. this._cacheFloat3(uniformName, x, y, z);
  9725. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9726. return this;
  9727. };
  9728. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9729. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9730. return this;
  9731. this._cacheFloat4(uniformName, x, y, z, w);
  9732. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9733. return this;
  9734. };
  9735. Effect.prototype.setColor3 = function (uniformName, color3) {
  9736. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9737. return this;
  9738. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9739. this._engine.setColor3(this.getUniform(uniformName), color3);
  9740. return this;
  9741. };
  9742. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9743. 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)
  9744. return this;
  9745. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9746. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9747. return this;
  9748. };
  9749. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  9750. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  9751. blurPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  9752. colorPixelShader:"precision mediump float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9753. colorVertexShader:"precision mediump float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  9754. convolutionPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  9755. defaultPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal)\n{\n float fresnelTerm = dot(viewDirection, worldNormal);\n return clamp(1.0 - fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec3 diffuseLeftColor;\nuniform vec3 diffuseRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\n }\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW);\n diffuseBase *= diffuseLeftColor * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  9756. defaultVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  9757. displayPassPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  9758. filterPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  9759. fxaaPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  9760. layerPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  9761. layerVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  9762. legacydefaultPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  9763. legacydefaultVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  9764. lensFlarePixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  9765. lensFlareVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  9766. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\n\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  9767. outlinePixelShader:"precision mediump float;\n\nuniform vec3 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = vec4(color, 1.);\n}",
  9768. outlineVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  9769. particlesPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  9770. particlesVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  9771. passPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  9772. postprocessVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  9773. refractionPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  9774. shadowMapPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  9775. shadowMapVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  9776. spritesPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  9777. spritesVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  9778. };
  9779. return Effect;
  9780. })();
  9781. BABYLON.Effect = Effect;
  9782. })(BABYLON || (BABYLON = {}));
  9783. var BABYLON;
  9784. (function (BABYLON) {
  9785. var Material = (function () {
  9786. function Material(name, scene, doNotAdd) {
  9787. this.name = name;
  9788. this.checkReadyOnEveryCall = true;
  9789. this.checkReadyOnlyOnce = false;
  9790. this.state = "";
  9791. this.alpha = 1.0;
  9792. this.wireframe = false;
  9793. this.backFaceCulling = true;
  9794. this._wasPreviouslyReady = false;
  9795. this.id = name;
  9796. this._scene = scene;
  9797. if (!doNotAdd) {
  9798. scene.materials.push(this);
  9799. }
  9800. }
  9801. Material.prototype.isReady = function (mesh, useInstances) {
  9802. return true;
  9803. };
  9804. Material.prototype.getEffect = function () {
  9805. return this._effect;
  9806. };
  9807. Material.prototype.getScene = function () {
  9808. return this._scene;
  9809. };
  9810. Material.prototype.needAlphaBlending = function () {
  9811. return (this.alpha < 1.0);
  9812. };
  9813. Material.prototype.needAlphaTesting = function () {
  9814. return false;
  9815. };
  9816. Material.prototype.getAlphaTestTexture = function () {
  9817. return null;
  9818. };
  9819. Material.prototype.trackCreation = function (onCompiled, onError) {
  9820. };
  9821. Material.prototype._preBind = function () {
  9822. var engine = this._scene.getEngine();
  9823. engine.enableEffect(this._effect);
  9824. engine.setState(this.backFaceCulling);
  9825. };
  9826. Material.prototype.bind = function (world, mesh) {
  9827. };
  9828. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9829. };
  9830. Material.prototype.unbind = function () {
  9831. };
  9832. Material.prototype.dispose = function (forceDisposeEffect) {
  9833. var index = this._scene.materials.indexOf(this);
  9834. this._scene.materials.splice(index, 1);
  9835. if (forceDisposeEffect && this._effect) {
  9836. this._scene.getEngine()._releaseEffect(this._effect);
  9837. this._effect = null;
  9838. }
  9839. if (this.onDispose) {
  9840. this.onDispose();
  9841. }
  9842. };
  9843. return Material;
  9844. })();
  9845. BABYLON.Material = Material;
  9846. })(BABYLON || (BABYLON = {}));
  9847. var __extends = this.__extends || function (d, b) {
  9848. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9849. function __() { this.constructor = d; }
  9850. __.prototype = b.prototype;
  9851. d.prototype = new __();
  9852. };
  9853. var BABYLON;
  9854. (function (BABYLON) {
  9855. var maxSimultaneousLights = 4;
  9856. var FresnelParameters = (function () {
  9857. function FresnelParameters() {
  9858. this.isEnabled = true;
  9859. this.leftColor = BABYLON.Color3.Black();
  9860. this.rightColor = BABYLON.Color3.White();
  9861. }
  9862. return FresnelParameters;
  9863. })();
  9864. BABYLON.FresnelParameters = FresnelParameters;
  9865. var StandardMaterial = (function (_super) {
  9866. __extends(StandardMaterial, _super);
  9867. function StandardMaterial(name, scene) {
  9868. var _this = this;
  9869. _super.call(this, name, scene);
  9870. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  9871. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  9872. this.specularColor = new BABYLON.Color3(1, 1, 1);
  9873. this.specularPower = 64;
  9874. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  9875. this.useAlphaFromDiffuseTexture = false;
  9876. this._cachedDefines = null;
  9877. this._renderTargets = new BABYLON.SmartArray(16);
  9878. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  9879. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  9880. this._baseColor = new BABYLON.Color3();
  9881. this._scaledDiffuse = new BABYLON.Color3();
  9882. this._scaledSpecular = new BABYLON.Color3();
  9883. this.getRenderTargetTextures = function () {
  9884. _this._renderTargets.reset();
  9885. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  9886. _this._renderTargets.push(_this.reflectionTexture);
  9887. }
  9888. return _this._renderTargets;
  9889. };
  9890. }
  9891. StandardMaterial.prototype.needAlphaBlending = function () {
  9892. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture();
  9893. };
  9894. StandardMaterial.prototype.needAlphaTesting = function () {
  9895. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  9896. };
  9897. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  9898. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  9899. };
  9900. StandardMaterial.prototype.getAlphaTestTexture = function () {
  9901. return this.diffuseTexture;
  9902. };
  9903. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  9904. if (this.checkReadyOnlyOnce) {
  9905. if (this._wasPreviouslyReady) {
  9906. return true;
  9907. }
  9908. }
  9909. var scene = this.getScene();
  9910. if (!this.checkReadyOnEveryCall) {
  9911. if (this._renderId === scene.getRenderId()) {
  9912. return true;
  9913. }
  9914. }
  9915. var engine = scene.getEngine();
  9916. var defines = [];
  9917. var fallbacks = new BABYLON.EffectFallbacks();
  9918. if (scene.texturesEnabled) {
  9919. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  9920. if (!this.diffuseTexture.isReady()) {
  9921. return false;
  9922. } else {
  9923. defines.push("#define DIFFUSE");
  9924. }
  9925. }
  9926. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  9927. if (!this.ambientTexture.isReady()) {
  9928. return false;
  9929. } else {
  9930. defines.push("#define AMBIENT");
  9931. }
  9932. }
  9933. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  9934. if (!this.opacityTexture.isReady()) {
  9935. return false;
  9936. } else {
  9937. defines.push("#define OPACITY");
  9938. if (this.opacityTexture.getAlphaFromRGB) {
  9939. defines.push("#define OPACITYRGB");
  9940. }
  9941. }
  9942. }
  9943. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  9944. if (!this.reflectionTexture.isReady()) {
  9945. return false;
  9946. } else {
  9947. defines.push("#define REFLECTION");
  9948. fallbacks.addFallback(0, "REFLECTION");
  9949. }
  9950. }
  9951. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  9952. if (!this.emissiveTexture.isReady()) {
  9953. return false;
  9954. } else {
  9955. defines.push("#define EMISSIVE");
  9956. }
  9957. }
  9958. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  9959. if (!this.specularTexture.isReady()) {
  9960. return false;
  9961. } else {
  9962. defines.push("#define SPECULAR");
  9963. fallbacks.addFallback(0, "SPECULAR");
  9964. }
  9965. }
  9966. }
  9967. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  9968. if (!this.bumpTexture.isReady()) {
  9969. return false;
  9970. } else {
  9971. defines.push("#define BUMP");
  9972. fallbacks.addFallback(0, "BUMP");
  9973. }
  9974. }
  9975. if (scene.clipPlane) {
  9976. defines.push("#define CLIPPLANE");
  9977. }
  9978. if (engine.getAlphaTesting()) {
  9979. defines.push("#define ALPHATEST");
  9980. }
  9981. if (this._shouldUseAlphaFromDiffuseTexture()) {
  9982. defines.push("#define ALPHAFROMDIFFUSE");
  9983. }
  9984. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  9985. defines.push("#define FOG");
  9986. fallbacks.addFallback(1, "FOG");
  9987. }
  9988. var shadowsActivated = false;
  9989. var lightIndex = 0;
  9990. if (scene.lightsEnabled) {
  9991. for (var index = 0; index < scene.lights.length; index++) {
  9992. var light = scene.lights[index];
  9993. if (!light.isEnabled()) {
  9994. continue;
  9995. }
  9996. if (light._excludedMeshesIds.length > 0) {
  9997. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  9998. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  9999. if (excludedMesh) {
  10000. light.excludedMeshes.push(excludedMesh);
  10001. }
  10002. }
  10003. light._excludedMeshesIds = [];
  10004. }
  10005. if (light._includedOnlyMeshesIds.length > 0) {
  10006. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10007. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10008. if (includedOnlyMesh) {
  10009. light.includedOnlyMeshes.push(includedOnlyMesh);
  10010. }
  10011. }
  10012. light._includedOnlyMeshesIds = [];
  10013. }
  10014. if (!light.canAffectMesh(mesh)) {
  10015. continue;
  10016. }
  10017. defines.push("#define LIGHT" + lightIndex);
  10018. if (lightIndex > 0) {
  10019. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10020. }
  10021. var type;
  10022. if (light instanceof BABYLON.SpotLight) {
  10023. type = "#define SPOTLIGHT" + lightIndex;
  10024. } else if (light instanceof BABYLON.HemisphericLight) {
  10025. type = "#define HEMILIGHT" + lightIndex;
  10026. } else {
  10027. type = "#define POINTDIRLIGHT" + lightIndex;
  10028. }
  10029. defines.push(type);
  10030. if (lightIndex > 0) {
  10031. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10032. }
  10033. var shadowGenerator = light.getShadowGenerator();
  10034. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10035. defines.push("#define SHADOW" + lightIndex);
  10036. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10037. if (!shadowsActivated) {
  10038. defines.push("#define SHADOWS");
  10039. shadowsActivated = true;
  10040. }
  10041. if (shadowGenerator.useVarianceShadowMap) {
  10042. defines.push("#define SHADOWVSM" + lightIndex);
  10043. if (lightIndex > 0) {
  10044. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10045. }
  10046. }
  10047. if (shadowGenerator.usePoissonSampling) {
  10048. defines.push("#define SHADOWPCF" + lightIndex);
  10049. if (lightIndex > 0) {
  10050. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10051. }
  10052. }
  10053. }
  10054. lightIndex++;
  10055. if (lightIndex == maxSimultaneousLights)
  10056. break;
  10057. }
  10058. }
  10059. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10060. defines.push("#define FRESNEL");
  10061. defines.push("#define DIFFUSEFRESNEL");
  10062. fallbacks.addFallback(1, "FRESNEL");
  10063. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  10064. }
  10065. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10066. if (mesh) {
  10067. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10068. attribs.push(BABYLON.VertexBuffer.UVKind);
  10069. defines.push("#define UV1");
  10070. }
  10071. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10072. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10073. defines.push("#define UV2");
  10074. }
  10075. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10076. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10077. defines.push("#define VERTEXCOLOR");
  10078. }
  10079. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10082. defines.push("#define BONES");
  10083. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10084. defines.push("#define BONES4");
  10085. fallbacks.addFallback(0, "BONES4");
  10086. }
  10087. if (useInstances) {
  10088. defines.push("#define INSTANCES");
  10089. attribs.push("world0");
  10090. attribs.push("world1");
  10091. attribs.push("world2");
  10092. attribs.push("world3");
  10093. }
  10094. }
  10095. var join = defines.join("\n");
  10096. if (this._cachedDefines != join) {
  10097. this._cachedDefines = join;
  10098. var shaderName = "default";
  10099. if (!scene.getEngine().getCaps().standardDerivatives) {
  10100. shaderName = "legacydefault";
  10101. }
  10102. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10103. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10104. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10105. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10106. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10107. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10108. "vFogInfos", "vFogColor",
  10109. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10110. "mBones",
  10111. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10112. "darkness0", "darkness1", "darkness2", "darkness3",
  10113. "diffuseLeftColor", "diffuseRightColor"
  10114. ], [
  10115. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10116. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10117. ], join, fallbacks, this.onCompiled, this.onError);
  10118. }
  10119. if (!this._effect.isReady()) {
  10120. return false;
  10121. }
  10122. this._renderId = scene.getRenderId();
  10123. this._wasPreviouslyReady = true;
  10124. return true;
  10125. };
  10126. StandardMaterial.prototype.unbind = function () {
  10127. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10128. this._effect.setTexture("reflection2DSampler", null);
  10129. }
  10130. };
  10131. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10132. this._effect.setMatrix("world", world);
  10133. };
  10134. StandardMaterial.prototype.bind = function (world, mesh) {
  10135. var scene = this.getScene();
  10136. this._baseColor.copyFrom(this.diffuseColor);
  10137. this.bindOnlyWorldMatrix(world);
  10138. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10139. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10140. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10141. }
  10142. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10143. this._effect.setColor3("diffuseLeftColor", this.diffuseFresnelParameters.leftColor);
  10144. this._effect.setColor3("diffuseRightColor", this.diffuseFresnelParameters.rightColor);
  10145. }
  10146. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10147. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10148. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10149. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10150. this._baseColor.copyFromFloats(1, 1, 1);
  10151. }
  10152. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10153. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10154. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10155. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10156. }
  10157. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10158. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10159. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10160. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10161. }
  10162. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10163. if (this.reflectionTexture.isCube) {
  10164. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10165. } else {
  10166. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10167. }
  10168. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10169. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10170. }
  10171. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10172. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10173. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10174. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10175. }
  10176. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10177. this._effect.setTexture("specularSampler", this.specularTexture);
  10178. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10179. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10180. }
  10181. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10182. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10183. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10184. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10185. }
  10186. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10187. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10188. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10189. this._effect.setColor4("vDiffuseColor", this._baseColor, this.alpha * mesh.visibility);
  10190. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10191. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10192. if (scene.lightsEnabled) {
  10193. var lightIndex = 0;
  10194. for (var index = 0; index < scene.lights.length; index++) {
  10195. var light = scene.lights[index];
  10196. if (!light.isEnabled()) {
  10197. continue;
  10198. }
  10199. if (!light.canAffectMesh(mesh)) {
  10200. continue;
  10201. }
  10202. if (light instanceof BABYLON.PointLight) {
  10203. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10204. } else if (light instanceof BABYLON.DirectionalLight) {
  10205. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10206. } else if (light instanceof BABYLON.SpotLight) {
  10207. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10208. } else if (light instanceof BABYLON.HemisphericLight) {
  10209. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10210. }
  10211. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10212. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10213. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10214. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10215. var shadowGenerator = light.getShadowGenerator();
  10216. if (mesh.receiveShadows && shadowGenerator) {
  10217. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10218. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10219. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10220. }
  10221. lightIndex++;
  10222. if (lightIndex == maxSimultaneousLights)
  10223. break;
  10224. }
  10225. }
  10226. if (scene.clipPlane) {
  10227. var clipPlane = scene.clipPlane;
  10228. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10229. }
  10230. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10231. this._effect.setMatrix("view", scene.getViewMatrix());
  10232. }
  10233. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10234. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10235. this._effect.setColor3("vFogColor", scene.fogColor);
  10236. }
  10237. };
  10238. StandardMaterial.prototype.getAnimatables = function () {
  10239. var results = [];
  10240. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10241. results.push(this.diffuseTexture);
  10242. }
  10243. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10244. results.push(this.ambientTexture);
  10245. }
  10246. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10247. results.push(this.opacityTexture);
  10248. }
  10249. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10250. results.push(this.reflectionTexture);
  10251. }
  10252. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10253. results.push(this.emissiveTexture);
  10254. }
  10255. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10256. results.push(this.specularTexture);
  10257. }
  10258. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10259. results.push(this.bumpTexture);
  10260. }
  10261. return results;
  10262. };
  10263. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10264. if (this.diffuseTexture) {
  10265. this.diffuseTexture.dispose();
  10266. }
  10267. if (this.ambientTexture) {
  10268. this.ambientTexture.dispose();
  10269. }
  10270. if (this.opacityTexture) {
  10271. this.opacityTexture.dispose();
  10272. }
  10273. if (this.reflectionTexture) {
  10274. this.reflectionTexture.dispose();
  10275. }
  10276. if (this.emissiveTexture) {
  10277. this.emissiveTexture.dispose();
  10278. }
  10279. if (this.specularTexture) {
  10280. this.specularTexture.dispose();
  10281. }
  10282. if (this.bumpTexture) {
  10283. this.bumpTexture.dispose();
  10284. }
  10285. _super.prototype.dispose.call(this, forceDisposeEffect);
  10286. };
  10287. StandardMaterial.prototype.clone = function (name) {
  10288. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10289. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10290. newStandardMaterial.alpha = this.alpha;
  10291. newStandardMaterial.wireframe = this.wireframe;
  10292. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10293. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10294. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10295. }
  10296. if (this.ambientTexture && this.ambientTexture.clone) {
  10297. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10298. }
  10299. if (this.opacityTexture && this.opacityTexture.clone) {
  10300. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10301. }
  10302. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10303. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10304. }
  10305. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10306. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10307. }
  10308. if (this.specularTexture && this.specularTexture.clone) {
  10309. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10310. }
  10311. if (this.bumpTexture && this.bumpTexture.clone) {
  10312. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10313. }
  10314. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10315. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10316. newStandardMaterial.specularColor = this.specularColor.clone();
  10317. newStandardMaterial.specularPower = this.specularPower;
  10318. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10319. return newStandardMaterial;
  10320. };
  10321. StandardMaterial.DiffuseTextureEnabled = true;
  10322. StandardMaterial.AmbientTextureEnabled = true;
  10323. StandardMaterial.OpacityTextureEnabled = true;
  10324. StandardMaterial.ReflectionTextureEnabled = true;
  10325. StandardMaterial.EmissiveTextureEnabled = true;
  10326. StandardMaterial.SpecularTextureEnabled = true;
  10327. StandardMaterial.BumpTextureEnabled = true;
  10328. return StandardMaterial;
  10329. })(BABYLON.Material);
  10330. BABYLON.StandardMaterial = StandardMaterial;
  10331. })(BABYLON || (BABYLON = {}));
  10332. var __extends = this.__extends || function (d, b) {
  10333. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10334. function __() { this.constructor = d; }
  10335. __.prototype = b.prototype;
  10336. d.prototype = new __();
  10337. };
  10338. var BABYLON;
  10339. (function (BABYLON) {
  10340. var MultiMaterial = (function (_super) {
  10341. __extends(MultiMaterial, _super);
  10342. function MultiMaterial(name, scene) {
  10343. _super.call(this, name, scene, true);
  10344. this.subMaterials = new Array();
  10345. scene.multiMaterials.push(this);
  10346. }
  10347. MultiMaterial.prototype.getSubMaterial = function (index) {
  10348. if (index < 0 || index >= this.subMaterials.length) {
  10349. return this.getScene().defaultMaterial;
  10350. }
  10351. return this.subMaterials[index];
  10352. };
  10353. MultiMaterial.prototype.isReady = function (mesh) {
  10354. for (var index = 0; index < this.subMaterials.length; index++) {
  10355. var subMaterial = this.subMaterials[index];
  10356. if (subMaterial) {
  10357. if (!this.subMaterials[index].isReady(mesh)) {
  10358. return false;
  10359. }
  10360. }
  10361. }
  10362. return true;
  10363. };
  10364. return MultiMaterial;
  10365. })(BABYLON.Material);
  10366. BABYLON.MultiMaterial = MultiMaterial;
  10367. })(BABYLON || (BABYLON = {}));
  10368. var BABYLON;
  10369. (function (BABYLON) {
  10370. var Database = (function () {
  10371. function Database(urlToScene, callbackManifestChecked) {
  10372. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10373. this.callbackManifestChecked = callbackManifestChecked;
  10374. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10375. this.db = null;
  10376. this.enableSceneOffline = false;
  10377. this.enableTexturesOffline = false;
  10378. this.manifestVersionFound = 0;
  10379. this.mustUpdateRessources = false;
  10380. this.hasReachedQuota = false;
  10381. this.checkManifestFile();
  10382. }
  10383. Database.prototype.checkManifestFile = function () {
  10384. var _this = this;
  10385. function noManifestFile() {
  10386. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10387. that.enableSceneOffline = false;
  10388. that.enableTexturesOffline = false;
  10389. that.callbackManifestChecked(false);
  10390. }
  10391. var that = this;
  10392. var manifestURL = this.currentSceneUrl + ".manifest";
  10393. var xhr = new XMLHttpRequest();
  10394. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10395. xhr.open("GET", manifestURLTimeStamped, true);
  10396. xhr.addEventListener("load", function () {
  10397. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10398. try {
  10399. var manifestFile = JSON.parse(xhr.response);
  10400. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10401. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10402. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10403. _this.manifestVersionFound = manifestFile.version;
  10404. }
  10405. if (_this.callbackManifestChecked) {
  10406. _this.callbackManifestChecked(true);
  10407. }
  10408. } catch (ex) {
  10409. noManifestFile();
  10410. }
  10411. } else {
  10412. noManifestFile();
  10413. }
  10414. }, false);
  10415. xhr.addEventListener("error", function (event) {
  10416. noManifestFile();
  10417. }, false);
  10418. try {
  10419. xhr.send();
  10420. } catch (ex) {
  10421. BABYLON.Tools.Error("Error on XHR send request.");
  10422. that.callbackManifestChecked(false);
  10423. }
  10424. };
  10425. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10426. var _this = this;
  10427. function handleError() {
  10428. that.isSupported = false;
  10429. if (errorCallback)
  10430. errorCallback();
  10431. }
  10432. var that = this;
  10433. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10434. this.isSupported = false;
  10435. if (errorCallback)
  10436. errorCallback();
  10437. } else {
  10438. if (!this.db) {
  10439. this.hasReachedQuota = false;
  10440. this.isSupported = true;
  10441. var request = this.idbFactory.open("babylonjs", 1);
  10442. request.onerror = function (event) {
  10443. handleError();
  10444. };
  10445. request.onblocked = function (event) {
  10446. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10447. handleError();
  10448. };
  10449. request.onsuccess = function (event) {
  10450. _this.db = request.result;
  10451. successCallback();
  10452. };
  10453. request.onupgradeneeded = function (event) {
  10454. _this.db = (event.target).result;
  10455. try {
  10456. if (event.oldVersion > 0) {
  10457. _this.db.deleteObjectStore("scenes");
  10458. _this.db.deleteObjectStore("versions");
  10459. _this.db.deleteObjectStore("textures");
  10460. }
  10461. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10462. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10463. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10464. } catch (ex) {
  10465. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10466. handleError();
  10467. }
  10468. };
  10469. } else {
  10470. if (successCallback)
  10471. successCallback();
  10472. }
  10473. }
  10474. };
  10475. Database.prototype.loadImageFromDB = function (url, image) {
  10476. var _this = this;
  10477. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10478. var saveAndLoadImage = function () {
  10479. if (!_this.hasReachedQuota && _this.db !== null) {
  10480. _this._saveImageIntoDBAsync(completeURL, image);
  10481. } else {
  10482. image.src = url;
  10483. }
  10484. };
  10485. if (!this.mustUpdateRessources) {
  10486. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10487. } else {
  10488. saveAndLoadImage();
  10489. }
  10490. };
  10491. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10492. if (this.isSupported && this.db !== null) {
  10493. var texture;
  10494. var transaction = this.db.transaction(["textures"]);
  10495. transaction.onabort = function (event) {
  10496. image.src = url;
  10497. };
  10498. transaction.oncomplete = function (event) {
  10499. var blobTextureURL;
  10500. if (texture) {
  10501. var URL = window.URL || window.webkitURL;
  10502. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10503. image.onerror = function () {
  10504. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10505. image.src = url;
  10506. };
  10507. image.src = blobTextureURL;
  10508. } else {
  10509. notInDBCallback();
  10510. }
  10511. };
  10512. var getRequest = transaction.objectStore("textures").get(url);
  10513. getRequest.onsuccess = function (event) {
  10514. texture = (event.target).result;
  10515. };
  10516. getRequest.onerror = function (event) {
  10517. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10518. image.src = url;
  10519. };
  10520. } else {
  10521. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10522. image.src = url;
  10523. }
  10524. };
  10525. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10526. var _this = this;
  10527. if (this.isSupported) {
  10528. var generateBlobUrl = function () {
  10529. var blobTextureURL;
  10530. if (blob) {
  10531. var URL = window.URL || window.webkitURL;
  10532. try {
  10533. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10534. } catch (ex) {
  10535. blobTextureURL = URL.createObjectURL(blob);
  10536. }
  10537. }
  10538. image.src = blobTextureURL;
  10539. };
  10540. if (BABYLON.Database.isUASupportingBlobStorage) {
  10541. var xhr = new XMLHttpRequest(), blob;
  10542. xhr.open("GET", url, true);
  10543. xhr.responseType = "blob";
  10544. xhr.addEventListener("load", function () {
  10545. if (xhr.status === 200) {
  10546. blob = xhr.response;
  10547. var transaction = _this.db.transaction(["textures"], "readwrite");
  10548. transaction.onabort = function (event) {
  10549. try {
  10550. if (event.srcElement.error.name === "QuotaExceededError") {
  10551. this.hasReachedQuota = true;
  10552. }
  10553. } catch (ex) {
  10554. }
  10555. generateBlobUrl();
  10556. };
  10557. transaction.oncomplete = function (event) {
  10558. generateBlobUrl();
  10559. };
  10560. var newTexture = { textureUrl: url, data: blob };
  10561. try {
  10562. var addRequest = transaction.objectStore("textures").put(newTexture);
  10563. addRequest.onsuccess = function (event) {
  10564. };
  10565. addRequest.onerror = function (event) {
  10566. generateBlobUrl();
  10567. };
  10568. } catch (ex) {
  10569. if (ex.code === 25) {
  10570. BABYLON.Database.isUASupportingBlobStorage = false;
  10571. }
  10572. image.src = url;
  10573. }
  10574. } else {
  10575. image.src = url;
  10576. }
  10577. }, false);
  10578. xhr.addEventListener("error", function (event) {
  10579. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10580. image.src = url;
  10581. }, false);
  10582. xhr.send();
  10583. } else {
  10584. image.src = url;
  10585. }
  10586. } else {
  10587. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10588. image.src = url;
  10589. }
  10590. };
  10591. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10592. var _this = this;
  10593. var updateVersion = function (event) {
  10594. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10595. };
  10596. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10597. };
  10598. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10599. var _this = this;
  10600. if (this.isSupported) {
  10601. var version;
  10602. try {
  10603. var transaction = this.db.transaction(["versions"]);
  10604. transaction.oncomplete = function (event) {
  10605. if (version) {
  10606. if (_this.manifestVersionFound > version.data) {
  10607. _this.mustUpdateRessources = true;
  10608. updateInDBCallback();
  10609. } else {
  10610. callback(version.data);
  10611. }
  10612. } else {
  10613. _this.mustUpdateRessources = true;
  10614. updateInDBCallback();
  10615. }
  10616. };
  10617. transaction.onabort = function (event) {
  10618. callback(-1);
  10619. };
  10620. var getRequest = transaction.objectStore("versions").get(url);
  10621. getRequest.onsuccess = function (event) {
  10622. version = (event.target).result;
  10623. };
  10624. getRequest.onerror = function (event) {
  10625. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10626. callback(-1);
  10627. };
  10628. } catch (ex) {
  10629. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10630. callback(-1);
  10631. }
  10632. } else {
  10633. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10634. callback(-1);
  10635. }
  10636. };
  10637. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10638. var _this = this;
  10639. if (this.isSupported && !this.hasReachedQuota) {
  10640. try {
  10641. var transaction = this.db.transaction(["versions"], "readwrite");
  10642. transaction.onabort = function (event) {
  10643. try {
  10644. if (event.srcElement.error.name === "QuotaExceededError") {
  10645. _this.hasReachedQuota = true;
  10646. }
  10647. } catch (ex) {
  10648. }
  10649. callback(-1);
  10650. };
  10651. transaction.oncomplete = function (event) {
  10652. callback(_this.manifestVersionFound);
  10653. };
  10654. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10655. var addRequest = transaction.objectStore("versions").put(newVersion);
  10656. addRequest.onsuccess = function (event) {
  10657. };
  10658. addRequest.onerror = function (event) {
  10659. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10660. };
  10661. } catch (ex) {
  10662. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10663. callback(-1);
  10664. }
  10665. } else {
  10666. callback(-1);
  10667. }
  10668. };
  10669. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10670. var _this = this;
  10671. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10672. var saveAndLoadFile = function (event) {
  10673. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10674. };
  10675. this._checkVersionFromDB(completeUrl, function (version) {
  10676. if (version !== -1) {
  10677. if (!_this.mustUpdateRessources) {
  10678. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10679. } else {
  10680. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10681. }
  10682. } else {
  10683. errorCallback();
  10684. }
  10685. });
  10686. };
  10687. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10688. if (this.isSupported) {
  10689. var targetStore;
  10690. if (url.indexOf(".babylon") !== -1) {
  10691. targetStore = "scenes";
  10692. } else {
  10693. targetStore = "textures";
  10694. }
  10695. var file;
  10696. var transaction = this.db.transaction([targetStore]);
  10697. transaction.oncomplete = function (event) {
  10698. if (file) {
  10699. callback(file.data);
  10700. } else {
  10701. notInDBCallback();
  10702. }
  10703. };
  10704. transaction.onabort = function (event) {
  10705. notInDBCallback();
  10706. };
  10707. var getRequest = transaction.objectStore(targetStore).get(url);
  10708. getRequest.onsuccess = function (event) {
  10709. file = (event.target).result;
  10710. };
  10711. getRequest.onerror = function (event) {
  10712. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10713. notInDBCallback();
  10714. };
  10715. } else {
  10716. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10717. callback();
  10718. }
  10719. };
  10720. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10721. var _this = this;
  10722. if (this.isSupported) {
  10723. var targetStore;
  10724. if (url.indexOf(".babylon") !== -1) {
  10725. targetStore = "scenes";
  10726. } else {
  10727. targetStore = "textures";
  10728. }
  10729. var xhr = new XMLHttpRequest(), fileData;
  10730. xhr.open("GET", url, true);
  10731. if (useArrayBuffer) {
  10732. xhr.responseType = "arraybuffer";
  10733. }
  10734. xhr.onprogress = progressCallback;
  10735. xhr.addEventListener("load", function () {
  10736. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10737. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10738. if (!_this.hasReachedQuota) {
  10739. var transaction = _this.db.transaction([targetStore], "readwrite");
  10740. transaction.onabort = function (event) {
  10741. try {
  10742. if (event.srcElement.error.name === "QuotaExceededError") {
  10743. this.hasReachedQuota = true;
  10744. }
  10745. } catch (ex) {
  10746. }
  10747. callback(fileData);
  10748. };
  10749. transaction.oncomplete = function (event) {
  10750. callback(fileData);
  10751. };
  10752. var newFile;
  10753. if (targetStore === "scenes") {
  10754. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10755. } else {
  10756. newFile = { textureUrl: url, data: fileData };
  10757. }
  10758. try {
  10759. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10760. addRequest.onsuccess = function (event) {
  10761. };
  10762. addRequest.onerror = function (event) {
  10763. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10764. };
  10765. } catch (ex) {
  10766. callback(fileData);
  10767. }
  10768. } else {
  10769. callback(fileData);
  10770. }
  10771. } else {
  10772. callback();
  10773. }
  10774. }, false);
  10775. xhr.addEventListener("error", function (event) {
  10776. BABYLON.Tools.Error("error on XHR request.");
  10777. callback();
  10778. }, false);
  10779. xhr.send();
  10780. } else {
  10781. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10782. callback();
  10783. }
  10784. };
  10785. Database.isUASupportingBlobStorage = true;
  10786. Database.parseURL = function (url) {
  10787. var a = document.createElement('a');
  10788. a.href = url;
  10789. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10790. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10791. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10792. return absLocation;
  10793. };
  10794. Database.ReturnFullUrlLocation = function (url) {
  10795. if (url.indexOf("http:/") === -1) {
  10796. return (BABYLON.Database.parseURL(window.location.href) + url);
  10797. } else {
  10798. return url;
  10799. }
  10800. };
  10801. return Database;
  10802. })();
  10803. BABYLON.Database = Database;
  10804. })(BABYLON || (BABYLON = {}));
  10805. var BABYLON;
  10806. (function (BABYLON) {
  10807. var SpriteManager = (function () {
  10808. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10809. this.name = name;
  10810. this.cellSize = cellSize;
  10811. this.sprites = new Array();
  10812. this.renderingGroupId = 0;
  10813. this._vertexDeclaration = [3, 4, 4, 4];
  10814. this._vertexStrideSize = 15 * 4;
  10815. this._capacity = capacity;
  10816. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  10817. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10818. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10819. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  10820. this._scene = scene;
  10821. this._scene.spriteManagers.push(this);
  10822. this._vertexDeclaration = [3, 4, 4, 4];
  10823. this._vertexStrideSize = 15 * 4;
  10824. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  10825. var indices = [];
  10826. var index = 0;
  10827. for (var count = 0; count < capacity; count++) {
  10828. indices.push(index);
  10829. indices.push(index + 1);
  10830. indices.push(index + 2);
  10831. indices.push(index);
  10832. indices.push(index + 2);
  10833. indices.push(index + 3);
  10834. index += 4;
  10835. }
  10836. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10837. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  10838. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  10839. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  10840. }
  10841. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  10842. var arrayOffset = index * 15;
  10843. if (offsetX == 0)
  10844. offsetX = this._epsilon;
  10845. else if (offsetX == 1)
  10846. offsetX = 1 - this._epsilon;
  10847. if (offsetY == 0)
  10848. offsetY = this._epsilon;
  10849. else if (offsetY == 1)
  10850. offsetY = 1 - this._epsilon;
  10851. this._vertices[arrayOffset] = sprite.position.x;
  10852. this._vertices[arrayOffset + 1] = sprite.position.y;
  10853. this._vertices[arrayOffset + 2] = sprite.position.z;
  10854. this._vertices[arrayOffset + 3] = sprite.angle;
  10855. this._vertices[arrayOffset + 4] = sprite.size;
  10856. this._vertices[arrayOffset + 5] = offsetX;
  10857. this._vertices[arrayOffset + 6] = offsetY;
  10858. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  10859. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  10860. var offset = (sprite.cellIndex / rowSize) >> 0;
  10861. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  10862. this._vertices[arrayOffset + 10] = offset;
  10863. this._vertices[arrayOffset + 11] = sprite.color.r;
  10864. this._vertices[arrayOffset + 12] = sprite.color.g;
  10865. this._vertices[arrayOffset + 13] = sprite.color.b;
  10866. this._vertices[arrayOffset + 14] = sprite.color.a;
  10867. };
  10868. SpriteManager.prototype.render = function () {
  10869. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  10870. return;
  10871. var engine = this._scene.getEngine();
  10872. var baseSize = this._spriteTexture.getBaseSize();
  10873. var deltaTime = BABYLON.Tools.GetDeltaTime();
  10874. var max = Math.min(this._capacity, this.sprites.length);
  10875. var rowSize = baseSize.width / this.cellSize;
  10876. var offset = 0;
  10877. for (var index = 0; index < max; index++) {
  10878. var sprite = this.sprites[index];
  10879. if (!sprite) {
  10880. continue;
  10881. }
  10882. sprite._animate(deltaTime);
  10883. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  10884. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  10885. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  10886. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  10887. }
  10888. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  10889. var effect = this._effectBase;
  10890. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10891. effect = this._effectFog;
  10892. }
  10893. engine.enableEffect(effect);
  10894. var viewMatrix = this._scene.getViewMatrix();
  10895. effect.setTexture("diffuseSampler", this._spriteTexture);
  10896. effect.setMatrix("view", viewMatrix);
  10897. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  10898. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  10899. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10900. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  10901. effect.setColor3("vFogColor", this._scene.fogColor);
  10902. }
  10903. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  10904. effect.setBool("alphaTest", true);
  10905. engine.setColorWrite(false);
  10906. engine.draw(true, 0, max * 6);
  10907. engine.setColorWrite(true);
  10908. effect.setBool("alphaTest", false);
  10909. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10910. engine.draw(true, 0, max * 6);
  10911. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10912. };
  10913. SpriteManager.prototype.dispose = function () {
  10914. if (this._vertexBuffer) {
  10915. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  10916. this._vertexBuffer = null;
  10917. }
  10918. if (this._indexBuffer) {
  10919. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  10920. this._indexBuffer = null;
  10921. }
  10922. if (this._spriteTexture) {
  10923. this._spriteTexture.dispose();
  10924. this._spriteTexture = null;
  10925. }
  10926. var index = this._scene.spriteManagers.indexOf(this);
  10927. this._scene.spriteManagers.splice(index, 1);
  10928. if (this.onDispose) {
  10929. this.onDispose();
  10930. }
  10931. };
  10932. return SpriteManager;
  10933. })();
  10934. BABYLON.SpriteManager = SpriteManager;
  10935. })(BABYLON || (BABYLON = {}));
  10936. var BABYLON;
  10937. (function (BABYLON) {
  10938. var Sprite = (function () {
  10939. function Sprite(name, manager) {
  10940. this.name = name;
  10941. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  10942. this.size = 1.0;
  10943. this.angle = 0;
  10944. this.cellIndex = 0;
  10945. this.invertU = 0;
  10946. this.invertV = 0;
  10947. this.animations = new Array();
  10948. this._animationStarted = false;
  10949. this._loopAnimation = false;
  10950. this._fromIndex = 0;
  10951. this._toIndex = 0;
  10952. this._delay = 0;
  10953. this._direction = 1;
  10954. this._frameCount = 0;
  10955. this._time = 0;
  10956. this._manager = manager;
  10957. this._manager.sprites.push(this);
  10958. this.position = BABYLON.Vector3.Zero();
  10959. }
  10960. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  10961. this._fromIndex = from;
  10962. this._toIndex = to;
  10963. this._loopAnimation = loop;
  10964. this._delay = delay;
  10965. this._animationStarted = true;
  10966. this._direction = from < to ? 1 : -1;
  10967. this.cellIndex = from;
  10968. this._time = 0;
  10969. };
  10970. Sprite.prototype.stopAnimation = function () {
  10971. this._animationStarted = false;
  10972. };
  10973. Sprite.prototype._animate = function (deltaTime) {
  10974. if (!this._animationStarted)
  10975. return;
  10976. this._time += deltaTime;
  10977. if (this._time > this._delay) {
  10978. this._time = this._time % this._delay;
  10979. this.cellIndex += this._direction;
  10980. if (this.cellIndex == this._toIndex) {
  10981. if (this._loopAnimation) {
  10982. this.cellIndex = this._fromIndex;
  10983. } else {
  10984. this._animationStarted = false;
  10985. if (this.disposeWhenFinishedAnimating) {
  10986. this.dispose();
  10987. }
  10988. }
  10989. }
  10990. }
  10991. };
  10992. Sprite.prototype.dispose = function () {
  10993. for (var i = 0; i < this._manager.sprites.length; i++) {
  10994. if (this._manager.sprites[i] == this) {
  10995. this._manager.sprites.splice(i, 1);
  10996. }
  10997. }
  10998. };
  10999. return Sprite;
  11000. })();
  11001. BABYLON.Sprite = Sprite;
  11002. })(BABYLON || (BABYLON = {}));
  11003. var BABYLON;
  11004. (function (BABYLON) {
  11005. var Layer = (function () {
  11006. function Layer(name, imgUrl, scene, isBackground, color) {
  11007. this.name = name;
  11008. this._vertexDeclaration = [2];
  11009. this._vertexStrideSize = 2 * 4;
  11010. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11011. this.isBackground = isBackground === undefined ? true : isBackground;
  11012. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11013. this._scene = scene;
  11014. this._scene.layers.push(this);
  11015. var vertices = [];
  11016. vertices.push(1, 1);
  11017. vertices.push(-1, 1);
  11018. vertices.push(-1, -1);
  11019. vertices.push(1, -1);
  11020. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11021. var indices = [];
  11022. indices.push(0);
  11023. indices.push(1);
  11024. indices.push(2);
  11025. indices.push(0);
  11026. indices.push(2);
  11027. indices.push(3);
  11028. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11029. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11030. }
  11031. Layer.prototype.render = function () {
  11032. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11033. return;
  11034. var engine = this._scene.getEngine();
  11035. engine.enableEffect(this._effect);
  11036. engine.setState(false);
  11037. this._effect.setTexture("textureSampler", this.texture);
  11038. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11039. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11040. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11041. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11042. engine.draw(true, 0, 6);
  11043. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11044. };
  11045. Layer.prototype.dispose = function () {
  11046. if (this._vertexBuffer) {
  11047. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11048. this._vertexBuffer = null;
  11049. }
  11050. if (this._indexBuffer) {
  11051. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11052. this._indexBuffer = null;
  11053. }
  11054. if (this.texture) {
  11055. this.texture.dispose();
  11056. this.texture = null;
  11057. }
  11058. var index = this._scene.layers.indexOf(this);
  11059. this._scene.layers.splice(index, 1);
  11060. if (this.onDispose) {
  11061. this.onDispose();
  11062. }
  11063. };
  11064. return Layer;
  11065. })();
  11066. BABYLON.Layer = Layer;
  11067. })(BABYLON || (BABYLON = {}));
  11068. var BABYLON;
  11069. (function (BABYLON) {
  11070. var Particle = (function () {
  11071. function Particle() {
  11072. this.position = BABYLON.Vector3.Zero();
  11073. this.direction = BABYLON.Vector3.Zero();
  11074. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11075. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11076. this.lifeTime = 1.0;
  11077. this.age = 0;
  11078. this.size = 0;
  11079. this.angle = 0;
  11080. this.angularSpeed = 0;
  11081. }
  11082. return Particle;
  11083. })();
  11084. BABYLON.Particle = Particle;
  11085. })(BABYLON || (BABYLON = {}));
  11086. var BABYLON;
  11087. (function (BABYLON) {
  11088. var randomNumber = function (min, max) {
  11089. if (min == max) {
  11090. return (min);
  11091. }
  11092. var random = Math.random();
  11093. return ((random * (max - min)) + min);
  11094. };
  11095. var ParticleSystem = (function () {
  11096. function ParticleSystem(name, capacity, scene, fragmentElement) {
  11097. var _this = this;
  11098. this.name = name;
  11099. this.fragmentElement = fragmentElement;
  11100. this.renderingGroupId = 0;
  11101. this.emitter = null;
  11102. this.emitRate = 10;
  11103. this.manualEmitCount = -1;
  11104. this.updateSpeed = 0.01;
  11105. this.targetStopDuration = 0;
  11106. this.disposeOnStop = false;
  11107. this.minEmitPower = 1;
  11108. this.maxEmitPower = 1;
  11109. this.minLifeTime = 1;
  11110. this.maxLifeTime = 1;
  11111. this.minSize = 1;
  11112. this.maxSize = 1;
  11113. this.minAngularSpeed = 0;
  11114. this.maxAngularSpeed = 0;
  11115. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11116. this.forceDepthWrite = false;
  11117. this.gravity = BABYLON.Vector3.Zero();
  11118. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11119. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11120. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11121. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11122. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11123. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11124. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11125. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11126. this.particles = new Array();
  11127. this._vertexDeclaration = [3, 4, 4];
  11128. this._vertexStrideSize = 11 * 4;
  11129. this._stockParticles = new Array();
  11130. this._newPartsExcess = 0;
  11131. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11132. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11133. this._scaledDirection = BABYLON.Vector3.Zero();
  11134. this._scaledGravity = BABYLON.Vector3.Zero();
  11135. this._currentRenderId = -1;
  11136. this._started = false;
  11137. this._stopped = false;
  11138. this._actualFrame = 0;
  11139. this.id = name;
  11140. this._capacity = capacity;
  11141. this._scene = scene;
  11142. scene.particleSystems.push(this);
  11143. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11144. var indices = [];
  11145. var index = 0;
  11146. for (var count = 0; count < capacity; count++) {
  11147. indices.push(index);
  11148. indices.push(index + 1);
  11149. indices.push(index + 2);
  11150. indices.push(index);
  11151. indices.push(index + 2);
  11152. indices.push(index + 3);
  11153. index += 4;
  11154. }
  11155. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11156. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11157. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11158. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11159. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11160. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11161. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11162. };
  11163. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11164. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11165. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11166. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11167. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11168. };
  11169. }
  11170. ParticleSystem.prototype.getCapacity = function () {
  11171. return this._capacity;
  11172. };
  11173. ParticleSystem.prototype.isAlive = function () {
  11174. return this._alive;
  11175. };
  11176. ParticleSystem.prototype.isStarted = function () {
  11177. return this._started;
  11178. };
  11179. ParticleSystem.prototype.start = function () {
  11180. this._started = true;
  11181. this._stopped = false;
  11182. this._actualFrame = 0;
  11183. };
  11184. ParticleSystem.prototype.stop = function () {
  11185. this._stopped = true;
  11186. };
  11187. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11188. var offset = index * 11;
  11189. this._vertices[offset] = particle.position.x;
  11190. this._vertices[offset + 1] = particle.position.y;
  11191. this._vertices[offset + 2] = particle.position.z;
  11192. this._vertices[offset + 3] = particle.color.r;
  11193. this._vertices[offset + 4] = particle.color.g;
  11194. this._vertices[offset + 5] = particle.color.b;
  11195. this._vertices[offset + 6] = particle.color.a;
  11196. this._vertices[offset + 7] = particle.angle;
  11197. this._vertices[offset + 8] = particle.size;
  11198. this._vertices[offset + 9] = offsetX;
  11199. this._vertices[offset + 10] = offsetY;
  11200. };
  11201. ParticleSystem.prototype._update = function (newParticles) {
  11202. this._alive = this.particles.length > 0;
  11203. for (var index = 0; index < this.particles.length; index++) {
  11204. var particle = this.particles[index];
  11205. particle.age += this._scaledUpdateSpeed;
  11206. if (particle.age >= particle.lifeTime) {
  11207. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11208. index--;
  11209. continue;
  11210. } else {
  11211. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11212. particle.color.addInPlace(this._scaledColorStep);
  11213. if (particle.color.a < 0)
  11214. particle.color.a = 0;
  11215. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11216. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11217. particle.position.addInPlace(this._scaledDirection);
  11218. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11219. particle.direction.addInPlace(this._scaledGravity);
  11220. }
  11221. }
  11222. var worldMatrix;
  11223. if (this.emitter.position) {
  11224. worldMatrix = this.emitter.getWorldMatrix();
  11225. } else {
  11226. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11227. }
  11228. for (index = 0; index < newParticles; index++) {
  11229. if (this.particles.length == this._capacity) {
  11230. break;
  11231. }
  11232. if (this._stockParticles.length !== 0) {
  11233. particle = this._stockParticles.pop();
  11234. particle.age = 0;
  11235. } else {
  11236. particle = new BABYLON.Particle();
  11237. }
  11238. this.particles.push(particle);
  11239. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11240. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11241. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11242. particle.size = randomNumber(this.minSize, this.maxSize);
  11243. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11244. this.startPositionFunction(worldMatrix, particle.position);
  11245. var step = randomNumber(0, 1.0);
  11246. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11247. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11248. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11249. }
  11250. };
  11251. ParticleSystem.prototype._getEffect = function () {
  11252. var defines = [];
  11253. if (this._scene.clipPlane) {
  11254. defines.push("#define CLIPPLANE");
  11255. }
  11256. var join = defines.join("\n");
  11257. if (this._cachedDefines != join) {
  11258. this._cachedDefines = join;
  11259. var baseName;
  11260. if (this.fragmentElement) {
  11261. baseName = {
  11262. vertex: "particles",
  11263. fragmentElement: this.fragmentElement
  11264. };
  11265. } else {
  11266. baseName = "particles";
  11267. }
  11268. this._effect = this._scene.getEngine().createEffect(baseName, ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11269. }
  11270. return this._effect;
  11271. };
  11272. ParticleSystem.prototype.animate = function () {
  11273. if (!this._started)
  11274. return;
  11275. var effect = this._getEffect();
  11276. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11277. return;
  11278. if (this._currentRenderId === this._scene.getRenderId()) {
  11279. return;
  11280. }
  11281. this._currentRenderId = this._scene.getRenderId();
  11282. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11283. var emitCout;
  11284. if (this.manualEmitCount > -1) {
  11285. emitCout = this.manualEmitCount;
  11286. this.manualEmitCount = 0;
  11287. } else {
  11288. emitCout = this.emitRate;
  11289. }
  11290. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11291. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11292. if (this._newPartsExcess > 1.0) {
  11293. newParticles += this._newPartsExcess >> 0;
  11294. this._newPartsExcess -= this._newPartsExcess >> 0;
  11295. }
  11296. this._alive = false;
  11297. if (!this._stopped) {
  11298. this._actualFrame += this._scaledUpdateSpeed;
  11299. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11300. this.stop();
  11301. } else {
  11302. newParticles = 0;
  11303. }
  11304. this._update(newParticles);
  11305. if (this._stopped) {
  11306. if (!this._alive) {
  11307. this._started = false;
  11308. if (this.disposeOnStop) {
  11309. this._scene._toBeDisposed.push(this);
  11310. }
  11311. }
  11312. }
  11313. var offset = 0;
  11314. for (var index = 0; index < this.particles.length; index++) {
  11315. var particle = this.particles[index];
  11316. this._appendParticleVertex(offset++, particle, 0, 0);
  11317. this._appendParticleVertex(offset++, particle, 1, 0);
  11318. this._appendParticleVertex(offset++, particle, 1, 1);
  11319. this._appendParticleVertex(offset++, particle, 0, 1);
  11320. }
  11321. var engine = this._scene.getEngine();
  11322. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11323. };
  11324. ParticleSystem.prototype.render = function () {
  11325. var effect = this._getEffect();
  11326. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11327. return 0;
  11328. var engine = this._scene.getEngine();
  11329. engine.enableEffect(effect);
  11330. var viewMatrix = this._scene.getViewMatrix();
  11331. effect.setTexture("diffuseSampler", this.particleTexture);
  11332. effect.setMatrix("view", viewMatrix);
  11333. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11334. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11335. if (this._scene.clipPlane) {
  11336. var clipPlane = this._scene.clipPlane;
  11337. var invView = viewMatrix.clone();
  11338. invView.invert();
  11339. effect.setMatrix("invView", invView);
  11340. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11341. }
  11342. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11343. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11344. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11345. } else {
  11346. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11347. }
  11348. if (this.forceDepthWrite) {
  11349. engine.setDepthWrite(true);
  11350. }
  11351. engine.draw(true, 0, this.particles.length * 6);
  11352. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11353. return this.particles.length;
  11354. };
  11355. ParticleSystem.prototype.dispose = function () {
  11356. if (this._vertexBuffer) {
  11357. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11358. this._vertexBuffer = null;
  11359. }
  11360. if (this._indexBuffer) {
  11361. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11362. this._indexBuffer = null;
  11363. }
  11364. if (this.particleTexture) {
  11365. this.particleTexture.dispose();
  11366. this.particleTexture = null;
  11367. }
  11368. var index = this._scene.particleSystems.indexOf(this);
  11369. this._scene.particleSystems.splice(index, 1);
  11370. if (this.onDispose) {
  11371. this.onDispose();
  11372. }
  11373. };
  11374. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11375. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11376. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11377. if (newEmitter === undefined) {
  11378. newEmitter = this.emitter;
  11379. }
  11380. result.emitter = newEmitter;
  11381. if (this.particleTexture) {
  11382. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11383. }
  11384. result.start();
  11385. return result;
  11386. };
  11387. ParticleSystem.BLENDMODE_ONEONE = 0;
  11388. ParticleSystem.BLENDMODE_STANDARD = 1;
  11389. return ParticleSystem;
  11390. })();
  11391. BABYLON.ParticleSystem = ParticleSystem;
  11392. })(BABYLON || (BABYLON = {}));
  11393. var BABYLON;
  11394. (function (BABYLON) {
  11395. var Animation = (function () {
  11396. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11397. this.name = name;
  11398. this.targetProperty = targetProperty;
  11399. this.framePerSecond = framePerSecond;
  11400. this.dataType = dataType;
  11401. this.loopMode = loopMode;
  11402. this._offsetsCache = {};
  11403. this._highLimitsCache = {};
  11404. this._stopped = false;
  11405. this.targetPropertyPath = targetProperty.split(".");
  11406. this.dataType = dataType;
  11407. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11408. }
  11409. Animation.prototype.isStopped = function () {
  11410. return this._stopped;
  11411. };
  11412. Animation.prototype.getKeys = function () {
  11413. return this._keys;
  11414. };
  11415. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11416. return startValue + (endValue - startValue) * gradient;
  11417. };
  11418. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11419. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11420. };
  11421. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11422. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11423. };
  11424. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11425. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11426. };
  11427. Animation.prototype.clone = function () {
  11428. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11429. clone.setKeys(this._keys);
  11430. return clone;
  11431. };
  11432. Animation.prototype.setKeys = function (values) {
  11433. this._keys = values.slice(0);
  11434. this._offsetsCache = {};
  11435. this._highLimitsCache = {};
  11436. };
  11437. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11438. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11439. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11440. }
  11441. this.currentFrame = currentFrame;
  11442. for (var key = 0; key < this._keys.length; key++) {
  11443. if (this._keys[key + 1].frame >= currentFrame) {
  11444. var startValue = this._keys[key].value;
  11445. var endValue = this._keys[key + 1].value;
  11446. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11447. switch (this.dataType) {
  11448. case Animation.ANIMATIONTYPE_FLOAT:
  11449. switch (loopMode) {
  11450. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11451. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11452. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11453. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11454. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11455. }
  11456. break;
  11457. case Animation.ANIMATIONTYPE_QUATERNION:
  11458. var quaternion = null;
  11459. switch (loopMode) {
  11460. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11461. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11462. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11463. break;
  11464. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11465. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11466. break;
  11467. }
  11468. return quaternion;
  11469. case Animation.ANIMATIONTYPE_VECTOR3:
  11470. switch (loopMode) {
  11471. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11472. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11473. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11474. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11475. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11476. }
  11477. case Animation.ANIMATIONTYPE_COLOR3:
  11478. switch (loopMode) {
  11479. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11480. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11481. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11482. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11483. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11484. }
  11485. case Animation.ANIMATIONTYPE_MATRIX:
  11486. switch (loopMode) {
  11487. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11488. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11489. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11490. return startValue;
  11491. }
  11492. default:
  11493. break;
  11494. }
  11495. break;
  11496. }
  11497. }
  11498. return this._keys[this._keys.length - 1].value;
  11499. };
  11500. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11501. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11502. this._stopped = true;
  11503. return false;
  11504. }
  11505. var returnValue = true;
  11506. if (this._keys[0].frame != 0) {
  11507. var newKey = {
  11508. frame: 0,
  11509. value: this._keys[0].value
  11510. };
  11511. this._keys.splice(0, 0, newKey);
  11512. }
  11513. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11514. from = this._keys[0].frame;
  11515. }
  11516. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11517. to = this._keys[this._keys.length - 1].frame;
  11518. }
  11519. var range = to - from;
  11520. var offsetValue;
  11521. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11522. if (ratio > range && !loop) {
  11523. returnValue = false;
  11524. highLimitValue = this._keys[this._keys.length - 1].value;
  11525. } else {
  11526. var highLimitValue = 0;
  11527. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11528. var keyOffset = to.toString() + from.toString();
  11529. if (!this._offsetsCache[keyOffset]) {
  11530. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11531. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11532. switch (this.dataType) {
  11533. case Animation.ANIMATIONTYPE_FLOAT:
  11534. this._offsetsCache[keyOffset] = toValue - fromValue;
  11535. break;
  11536. case Animation.ANIMATIONTYPE_QUATERNION:
  11537. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11538. break;
  11539. case Animation.ANIMATIONTYPE_VECTOR3:
  11540. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11541. case Animation.ANIMATIONTYPE_COLOR3:
  11542. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11543. default:
  11544. break;
  11545. }
  11546. this._highLimitsCache[keyOffset] = toValue;
  11547. }
  11548. highLimitValue = this._highLimitsCache[keyOffset];
  11549. offsetValue = this._offsetsCache[keyOffset];
  11550. }
  11551. }
  11552. if (offsetValue === undefined) {
  11553. switch (this.dataType) {
  11554. case Animation.ANIMATIONTYPE_FLOAT:
  11555. offsetValue = 0;
  11556. break;
  11557. case Animation.ANIMATIONTYPE_QUATERNION:
  11558. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11559. break;
  11560. case Animation.ANIMATIONTYPE_VECTOR3:
  11561. offsetValue = BABYLON.Vector3.Zero();
  11562. break;
  11563. case Animation.ANIMATIONTYPE_COLOR3:
  11564. offsetValue = BABYLON.Color3.Black();
  11565. }
  11566. }
  11567. var repeatCount = (ratio / range) >> 0;
  11568. var currentFrame = returnValue ? from + ratio % range : to;
  11569. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11570. if (this.targetPropertyPath.length > 1) {
  11571. var property = this._target[this.targetPropertyPath[0]];
  11572. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11573. property = property[this.targetPropertyPath[index]];
  11574. }
  11575. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11576. } else {
  11577. this._target[this.targetPropertyPath[0]] = currentValue;
  11578. }
  11579. if (this._target.markAsDirty) {
  11580. this._target.markAsDirty(this.targetProperty);
  11581. }
  11582. if (!returnValue) {
  11583. this._stopped = true;
  11584. }
  11585. return returnValue;
  11586. };
  11587. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11588. get: function () {
  11589. return Animation._ANIMATIONTYPE_FLOAT;
  11590. },
  11591. enumerable: true,
  11592. configurable: true
  11593. });
  11594. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11595. get: function () {
  11596. return Animation._ANIMATIONTYPE_VECTOR3;
  11597. },
  11598. enumerable: true,
  11599. configurable: true
  11600. });
  11601. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11602. get: function () {
  11603. return Animation._ANIMATIONTYPE_QUATERNION;
  11604. },
  11605. enumerable: true,
  11606. configurable: true
  11607. });
  11608. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11609. get: function () {
  11610. return Animation._ANIMATIONTYPE_MATRIX;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11616. get: function () {
  11617. return Animation._ANIMATIONTYPE_COLOR3;
  11618. },
  11619. enumerable: true,
  11620. configurable: true
  11621. });
  11622. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11623. get: function () {
  11624. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11625. },
  11626. enumerable: true,
  11627. configurable: true
  11628. });
  11629. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11630. get: function () {
  11631. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11637. get: function () {
  11638. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11639. },
  11640. enumerable: true,
  11641. configurable: true
  11642. });
  11643. Animation._ANIMATIONTYPE_FLOAT = 0;
  11644. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11645. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11646. Animation._ANIMATIONTYPE_MATRIX = 3;
  11647. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11648. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11649. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11650. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11651. return Animation;
  11652. })();
  11653. BABYLON.Animation = Animation;
  11654. })(BABYLON || (BABYLON = {}));
  11655. var BABYLON;
  11656. (function (BABYLON) {
  11657. var Animatable = (function () {
  11658. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11659. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11660. if (typeof toFrame === "undefined") { toFrame = 100; }
  11661. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11662. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11663. this.target = target;
  11664. this.fromFrame = fromFrame;
  11665. this.toFrame = toFrame;
  11666. this.loopAnimation = loopAnimation;
  11667. this.speedRatio = speedRatio;
  11668. this.onAnimationEnd = onAnimationEnd;
  11669. this._animations = new Array();
  11670. this._paused = false;
  11671. this.animationStarted = false;
  11672. if (animations) {
  11673. this.appendAnimations(target, animations);
  11674. }
  11675. this._scene = scene;
  11676. scene._activeAnimatables.push(this);
  11677. }
  11678. Animatable.prototype.appendAnimations = function (target, animations) {
  11679. for (var index = 0; index < animations.length; index++) {
  11680. var animation = animations[index];
  11681. animation._target = target;
  11682. this._animations.push(animation);
  11683. }
  11684. };
  11685. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11686. var animations = this._animations;
  11687. for (var index = 0; index < animations.length; index++) {
  11688. if (animations[index].targetProperty === property) {
  11689. return animations[index];
  11690. }
  11691. }
  11692. return null;
  11693. };
  11694. Animatable.prototype.pause = function () {
  11695. this._paused = true;
  11696. };
  11697. Animatable.prototype.restart = function () {
  11698. this._paused = false;
  11699. };
  11700. Animatable.prototype.stop = function () {
  11701. var index = this._scene._activeAnimatables.indexOf(this);
  11702. if (index > -1) {
  11703. this._scene._activeAnimatables.splice(index, 1);
  11704. }
  11705. if (this.onAnimationEnd) {
  11706. this.onAnimationEnd();
  11707. }
  11708. };
  11709. Animatable.prototype._animate = function (delay) {
  11710. if (this._paused) {
  11711. return true;
  11712. }
  11713. if (!this._localDelayOffset) {
  11714. this._localDelayOffset = delay;
  11715. }
  11716. var running = false;
  11717. var animations = this._animations;
  11718. for (var index = 0; index < animations.length; index++) {
  11719. var animation = animations[index];
  11720. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11721. running = running || isRunning;
  11722. }
  11723. if (!running && this.onAnimationEnd) {
  11724. this.onAnimationEnd();
  11725. }
  11726. return running;
  11727. };
  11728. return Animatable;
  11729. })();
  11730. BABYLON.Animatable = Animatable;
  11731. })(BABYLON || (BABYLON = {}));
  11732. var BABYLON;
  11733. (function (BABYLON) {
  11734. var Octree = (function () {
  11735. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11736. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11737. this.maxDepth = maxDepth;
  11738. this.dynamicContent = new Array();
  11739. this._maxBlockCapacity = maxBlockCapacity || 64;
  11740. this._selectionContent = new BABYLON.SmartArray(1024);
  11741. this._creationFunc = creationFunc;
  11742. }
  11743. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11744. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11745. };
  11746. Octree.prototype.addMesh = function (entry) {
  11747. for (var index = 0; index < this.blocks.length; index++) {
  11748. var block = this.blocks[index];
  11749. block.addEntry(entry);
  11750. }
  11751. };
  11752. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11753. this._selectionContent.reset();
  11754. for (var index = 0; index < this.blocks.length; index++) {
  11755. var block = this.blocks[index];
  11756. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11757. }
  11758. if (allowDuplicate) {
  11759. this._selectionContent.concat(this.dynamicContent);
  11760. } else {
  11761. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11762. }
  11763. return this._selectionContent;
  11764. };
  11765. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11766. this._selectionContent.reset();
  11767. for (var index = 0; index < this.blocks.length; index++) {
  11768. var block = this.blocks[index];
  11769. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11770. }
  11771. if (allowDuplicate) {
  11772. this._selectionContent.concat(this.dynamicContent);
  11773. } else {
  11774. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11775. }
  11776. return this._selectionContent;
  11777. };
  11778. Octree.prototype.intersectsRay = function (ray) {
  11779. this._selectionContent.reset();
  11780. for (var index = 0; index < this.blocks.length; index++) {
  11781. var block = this.blocks[index];
  11782. block.intersectsRay(ray, this._selectionContent);
  11783. }
  11784. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11785. return this._selectionContent;
  11786. };
  11787. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11788. target.blocks = new Array();
  11789. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11790. for (var x = 0; x < 2; x++) {
  11791. for (var y = 0; y < 2; y++) {
  11792. for (var z = 0; z < 2; z++) {
  11793. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11794. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11795. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11796. block.addEntries(entries);
  11797. target.blocks.push(block);
  11798. }
  11799. }
  11800. }
  11801. };
  11802. Octree.CreationFuncForMeshes = function (entry, block) {
  11803. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11804. block.entries.push(entry);
  11805. }
  11806. };
  11807. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11808. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11809. block.entries.push(entry);
  11810. }
  11811. };
  11812. return Octree;
  11813. })();
  11814. BABYLON.Octree = Octree;
  11815. })(BABYLON || (BABYLON = {}));
  11816. var BABYLON;
  11817. (function (BABYLON) {
  11818. var OctreeBlock = (function () {
  11819. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  11820. this.entries = new Array();
  11821. this._boundingVectors = new Array();
  11822. this._capacity = capacity;
  11823. this._depth = depth;
  11824. this._maxDepth = maxDepth;
  11825. this._creationFunc = creationFunc;
  11826. this._minPoint = minPoint;
  11827. this._maxPoint = maxPoint;
  11828. this._boundingVectors.push(minPoint.clone());
  11829. this._boundingVectors.push(maxPoint.clone());
  11830. this._boundingVectors.push(minPoint.clone());
  11831. this._boundingVectors[2].x = maxPoint.x;
  11832. this._boundingVectors.push(minPoint.clone());
  11833. this._boundingVectors[3].y = maxPoint.y;
  11834. this._boundingVectors.push(minPoint.clone());
  11835. this._boundingVectors[4].z = maxPoint.z;
  11836. this._boundingVectors.push(maxPoint.clone());
  11837. this._boundingVectors[5].z = minPoint.z;
  11838. this._boundingVectors.push(maxPoint.clone());
  11839. this._boundingVectors[6].x = minPoint.x;
  11840. this._boundingVectors.push(maxPoint.clone());
  11841. this._boundingVectors[7].y = minPoint.y;
  11842. }
  11843. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  11844. get: function () {
  11845. return this._capacity;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  11851. get: function () {
  11852. return this._minPoint;
  11853. },
  11854. enumerable: true,
  11855. configurable: true
  11856. });
  11857. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  11858. get: function () {
  11859. return this._maxPoint;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. OctreeBlock.prototype.addEntry = function (entry) {
  11865. if (this.blocks) {
  11866. for (var index = 0; index < this.blocks.length; index++) {
  11867. var block = this.blocks[index];
  11868. block.addEntry(entry);
  11869. }
  11870. return;
  11871. }
  11872. this._creationFunc(entry, this);
  11873. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  11874. this.createInnerBlocks();
  11875. }
  11876. };
  11877. OctreeBlock.prototype.addEntries = function (entries) {
  11878. for (var index = 0; index < entries.length; index++) {
  11879. var mesh = entries[index];
  11880. this.addEntry(mesh);
  11881. }
  11882. };
  11883. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  11884. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  11885. if (this.blocks) {
  11886. for (var index = 0; index < this.blocks.length; index++) {
  11887. var block = this.blocks[index];
  11888. block.select(frustumPlanes, selection, allowDuplicate);
  11889. }
  11890. return;
  11891. }
  11892. if (allowDuplicate) {
  11893. selection.concat(this.entries);
  11894. } else {
  11895. selection.concatWithNoDuplicate(this.entries);
  11896. }
  11897. }
  11898. };
  11899. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  11900. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  11901. if (this.blocks) {
  11902. for (var index = 0; index < this.blocks.length; index++) {
  11903. var block = this.blocks[index];
  11904. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  11905. }
  11906. return;
  11907. }
  11908. if (allowDuplicate) {
  11909. selection.concat(this.entries);
  11910. } else {
  11911. selection.concatWithNoDuplicate(this.entries);
  11912. }
  11913. }
  11914. };
  11915. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  11916. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  11917. if (this.blocks) {
  11918. for (var index = 0; index < this.blocks.length; index++) {
  11919. var block = this.blocks[index];
  11920. block.intersectsRay(ray, selection);
  11921. }
  11922. return;
  11923. }
  11924. selection.concatWithNoDuplicate(this.entries);
  11925. }
  11926. };
  11927. OctreeBlock.prototype.createInnerBlocks = function () {
  11928. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  11929. };
  11930. return OctreeBlock;
  11931. })();
  11932. BABYLON.OctreeBlock = OctreeBlock;
  11933. })(BABYLON || (BABYLON = {}));
  11934. var BABYLON;
  11935. (function (BABYLON) {
  11936. var Bone = (function () {
  11937. function Bone(name, skeleton, parentBone, matrix) {
  11938. this.name = name;
  11939. this.children = new Array();
  11940. this.animations = new Array();
  11941. this._worldTransform = new BABYLON.Matrix();
  11942. this._absoluteTransform = new BABYLON.Matrix();
  11943. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  11944. this._skeleton = skeleton;
  11945. this._matrix = matrix;
  11946. this._baseMatrix = matrix;
  11947. skeleton.bones.push(this);
  11948. if (parentBone) {
  11949. this._parent = parentBone;
  11950. parentBone.children.push(this);
  11951. } else {
  11952. this._parent = null;
  11953. }
  11954. this._updateDifferenceMatrix();
  11955. }
  11956. Bone.prototype.getParent = function () {
  11957. return this._parent;
  11958. };
  11959. Bone.prototype.getLocalMatrix = function () {
  11960. return this._matrix;
  11961. };
  11962. Bone.prototype.getBaseMatrix = function () {
  11963. return this._baseMatrix;
  11964. };
  11965. Bone.prototype.getWorldMatrix = function () {
  11966. return this._worldTransform;
  11967. };
  11968. Bone.prototype.getInvertedAbsoluteTransform = function () {
  11969. return this._invertedAbsoluteTransform;
  11970. };
  11971. Bone.prototype.getAbsoluteMatrix = function () {
  11972. var matrix = this._matrix.clone();
  11973. var parent = this._parent;
  11974. while (parent) {
  11975. matrix = matrix.multiply(parent.getLocalMatrix());
  11976. parent = parent.getParent();
  11977. }
  11978. return matrix;
  11979. };
  11980. Bone.prototype.updateMatrix = function (matrix) {
  11981. this._matrix = matrix;
  11982. this._skeleton._markAsDirty();
  11983. this._updateDifferenceMatrix();
  11984. };
  11985. Bone.prototype._updateDifferenceMatrix = function () {
  11986. if (this._parent) {
  11987. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  11988. } else {
  11989. this._absoluteTransform.copyFrom(this._matrix);
  11990. }
  11991. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  11992. for (var index = 0; index < this.children.length; index++) {
  11993. this.children[index]._updateDifferenceMatrix();
  11994. }
  11995. };
  11996. Bone.prototype.markAsDirty = function () {
  11997. this._skeleton._markAsDirty();
  11998. };
  11999. return Bone;
  12000. })();
  12001. BABYLON.Bone = Bone;
  12002. })(BABYLON || (BABYLON = {}));
  12003. var BABYLON;
  12004. (function (BABYLON) {
  12005. var Skeleton = (function () {
  12006. function Skeleton(name, id, scene) {
  12007. this.name = name;
  12008. this.id = id;
  12009. this.bones = new Array();
  12010. this._isDirty = true;
  12011. this._identity = BABYLON.Matrix.Identity();
  12012. this.bones = [];
  12013. this._scene = scene;
  12014. scene.skeletons.push(this);
  12015. }
  12016. Skeleton.prototype.getTransformMatrices = function () {
  12017. return this._transformMatrices;
  12018. };
  12019. Skeleton.prototype._markAsDirty = function () {
  12020. this._isDirty = true;
  12021. };
  12022. Skeleton.prototype.prepare = function () {
  12023. if (!this._isDirty) {
  12024. return;
  12025. }
  12026. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12027. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12028. }
  12029. for (var index = 0; index < this.bones.length; index++) {
  12030. var bone = this.bones[index];
  12031. var parentBone = bone.getParent();
  12032. if (parentBone) {
  12033. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12034. } else {
  12035. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12036. }
  12037. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12038. }
  12039. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12040. this._isDirty = false;
  12041. };
  12042. Skeleton.prototype.getAnimatables = function () {
  12043. if (!this._animatables || this._animatables.length != this.bones.length) {
  12044. this._animatables = [];
  12045. for (var index = 0; index < this.bones.length; index++) {
  12046. this._animatables.push(this.bones[index]);
  12047. }
  12048. }
  12049. return this._animatables;
  12050. };
  12051. Skeleton.prototype.clone = function (name, id) {
  12052. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12053. for (var index = 0; index < this.bones.length; index++) {
  12054. var source = this.bones[index];
  12055. var parentBone = null;
  12056. if (source.getParent()) {
  12057. var parentIndex = this.bones.indexOf(source.getParent());
  12058. parentBone = result.bones[parentIndex];
  12059. }
  12060. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12061. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12062. }
  12063. return result;
  12064. };
  12065. return Skeleton;
  12066. })();
  12067. BABYLON.Skeleton = Skeleton;
  12068. })(BABYLON || (BABYLON = {}));
  12069. var BABYLON;
  12070. (function (BABYLON) {
  12071. var PostProcess = (function () {
  12072. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12073. this.name = name;
  12074. this.width = -1;
  12075. this.height = -1;
  12076. this._reusable = false;
  12077. this._textures = new BABYLON.SmartArray(2);
  12078. this._currentRenderTextureInd = 0;
  12079. if (camera != null) {
  12080. this._camera = camera;
  12081. this._scene = camera.getScene();
  12082. camera.attachPostProcess(this);
  12083. this._engine = this._scene.getEngine();
  12084. } else {
  12085. this._engine = engine;
  12086. }
  12087. this._renderRatio = ratio;
  12088. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12089. this._reusable = reusable || false;
  12090. samplers = samplers || [];
  12091. samplers.push("textureSampler");
  12092. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12093. }
  12094. PostProcess.prototype.isReusable = function () {
  12095. return this._reusable;
  12096. };
  12097. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12098. camera = camera || this._camera;
  12099. var scene = camera.getScene();
  12100. var desiredWidth = (sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio;
  12101. var desiredHeight = (sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio;
  12102. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12103. if (this._textures.length > 0) {
  12104. for (var i = 0; i < this._textures.length; i++) {
  12105. this._engine._releaseTexture(this._textures.data[i]);
  12106. }
  12107. this._textures.reset();
  12108. }
  12109. this.width = desiredWidth;
  12110. this.height = desiredHeight;
  12111. 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 }));
  12112. if (this._reusable) {
  12113. 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 }));
  12114. }
  12115. if (this.onSizeChanged) {
  12116. this.onSizeChanged();
  12117. }
  12118. }
  12119. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12120. if (this.onActivate) {
  12121. this.onActivate(camera);
  12122. }
  12123. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12124. if (this._reusable) {
  12125. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12126. }
  12127. };
  12128. PostProcess.prototype.apply = function () {
  12129. if (!this._effect.isReady())
  12130. return null;
  12131. this._engine.enableEffect(this._effect);
  12132. this._engine.setState(false);
  12133. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12134. this._engine.setDepthBuffer(false);
  12135. this._engine.setDepthWrite(false);
  12136. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12137. if (this.onApply) {
  12138. this.onApply(this._effect);
  12139. }
  12140. return this._effect;
  12141. };
  12142. PostProcess.prototype.dispose = function (camera) {
  12143. camera = camera || this._camera;
  12144. if (this._textures.length > 0) {
  12145. for (var i = 0; i < this._textures.length; i++) {
  12146. this._engine._releaseTexture(this._textures.data[i]);
  12147. }
  12148. this._textures.reset();
  12149. }
  12150. camera.detachPostProcess(this);
  12151. var index = camera._postProcesses.indexOf(this);
  12152. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12153. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12154. }
  12155. };
  12156. return PostProcess;
  12157. })();
  12158. BABYLON.PostProcess = PostProcess;
  12159. })(BABYLON || (BABYLON = {}));
  12160. var BABYLON;
  12161. (function (BABYLON) {
  12162. var PostProcessManager = (function () {
  12163. function PostProcessManager(scene) {
  12164. this._vertexDeclaration = [2];
  12165. this._vertexStrideSize = 2 * 4;
  12166. this._scene = scene;
  12167. var vertices = [];
  12168. vertices.push(1, 1);
  12169. vertices.push(-1, 1);
  12170. vertices.push(-1, -1);
  12171. vertices.push(1, -1);
  12172. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12173. var indices = [];
  12174. indices.push(0);
  12175. indices.push(1);
  12176. indices.push(2);
  12177. indices.push(0);
  12178. indices.push(2);
  12179. indices.push(3);
  12180. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12181. }
  12182. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12183. var postProcesses = this._scene.activeCamera._postProcesses;
  12184. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12185. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12186. return false;
  12187. }
  12188. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12189. return true;
  12190. };
  12191. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12192. var postProcesses = this._scene.activeCamera._postProcesses;
  12193. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12194. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12195. return;
  12196. }
  12197. var engine = this._scene.getEngine();
  12198. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12199. if (index < postProcessesTakenIndices.length - 1) {
  12200. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12201. } else {
  12202. if (targetTexture) {
  12203. engine.bindFramebuffer(targetTexture);
  12204. } else {
  12205. engine.restoreDefaultFramebuffer();
  12206. }
  12207. }
  12208. if (doNotPresent) {
  12209. break;
  12210. }
  12211. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12212. if (effect) {
  12213. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12214. engine.draw(true, 0, 6);
  12215. }
  12216. }
  12217. engine.setDepthBuffer(true);
  12218. engine.setDepthWrite(true);
  12219. };
  12220. PostProcessManager.prototype.dispose = function () {
  12221. if (this._vertexBuffer) {
  12222. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12223. this._vertexBuffer = null;
  12224. }
  12225. if (this._indexBuffer) {
  12226. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12227. this._indexBuffer = null;
  12228. }
  12229. };
  12230. return PostProcessManager;
  12231. })();
  12232. BABYLON.PostProcessManager = PostProcessManager;
  12233. })(BABYLON || (BABYLON = {}));
  12234. var __extends = this.__extends || function (d, b) {
  12235. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12236. function __() { this.constructor = d; }
  12237. __.prototype = b.prototype;
  12238. d.prototype = new __();
  12239. };
  12240. var BABYLON;
  12241. (function (BABYLON) {
  12242. var PassPostProcess = (function (_super) {
  12243. __extends(PassPostProcess, _super);
  12244. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12245. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12246. }
  12247. return PassPostProcess;
  12248. })(BABYLON.PostProcess);
  12249. BABYLON.PassPostProcess = PassPostProcess;
  12250. })(BABYLON || (BABYLON = {}));
  12251. var __extends = this.__extends || function (d, b) {
  12252. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12253. function __() { this.constructor = d; }
  12254. __.prototype = b.prototype;
  12255. d.prototype = new __();
  12256. };
  12257. var BABYLON;
  12258. (function (BABYLON) {
  12259. var BlurPostProcess = (function (_super) {
  12260. __extends(BlurPostProcess, _super);
  12261. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12262. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12263. var _this = this;
  12264. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12265. this.direction = direction;
  12266. this.blurWidth = blurWidth;
  12267. this.onApply = function (effect) {
  12268. effect.setFloat2("screenSize", _this.width, _this.height);
  12269. effect.setVector2("direction", _this.direction);
  12270. effect.setFloat("blurWidth", _this.blurWidth);
  12271. };
  12272. }
  12273. return BlurPostProcess;
  12274. })(BABYLON.PostProcess);
  12275. BABYLON.BlurPostProcess = BlurPostProcess;
  12276. })(BABYLON || (BABYLON = {}));
  12277. var __extends = this.__extends || function (d, b) {
  12278. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12279. function __() { this.constructor = d; }
  12280. __.prototype = b.prototype;
  12281. d.prototype = new __();
  12282. };
  12283. var BABYLON;
  12284. (function (BABYLON) {
  12285. var FilterPostProcess = (function (_super) {
  12286. __extends(FilterPostProcess, _super);
  12287. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12288. var _this = this;
  12289. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12290. this.kernelMatrix = kernelMatrix;
  12291. this.onApply = function (effect) {
  12292. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12293. };
  12294. }
  12295. return FilterPostProcess;
  12296. })(BABYLON.PostProcess);
  12297. BABYLON.FilterPostProcess = FilterPostProcess;
  12298. })(BABYLON || (BABYLON = {}));
  12299. var __extends = this.__extends || function (d, b) {
  12300. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12301. function __() { this.constructor = d; }
  12302. __.prototype = b.prototype;
  12303. d.prototype = new __();
  12304. };
  12305. var BABYLON;
  12306. (function (BABYLON) {
  12307. var RefractionPostProcess = (function (_super) {
  12308. __extends(RefractionPostProcess, _super);
  12309. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12310. var _this = this;
  12311. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12312. this.color = color;
  12313. this.depth = depth;
  12314. this.colorLevel = colorLevel;
  12315. this.onActivate = function (cam) {
  12316. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12317. };
  12318. this.onApply = function (effect) {
  12319. effect.setColor3("baseColor", _this.color);
  12320. effect.setFloat("depth", _this.depth);
  12321. effect.setFloat("colorLevel", _this.colorLevel);
  12322. effect.setTexture("refractionSampler", _this._refRexture);
  12323. };
  12324. }
  12325. RefractionPostProcess.prototype.dispose = function (camera) {
  12326. if (this._refRexture) {
  12327. this._refRexture.dispose();
  12328. }
  12329. _super.prototype.dispose.call(this, camera);
  12330. };
  12331. return RefractionPostProcess;
  12332. })(BABYLON.PostProcess);
  12333. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12334. })(BABYLON || (BABYLON = {}));
  12335. var __extends = this.__extends || function (d, b) {
  12336. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12337. function __() { this.constructor = d; }
  12338. __.prototype = b.prototype;
  12339. d.prototype = new __();
  12340. };
  12341. var BABYLON;
  12342. (function (BABYLON) {
  12343. var BlackAndWhitePostProcess = (function (_super) {
  12344. __extends(BlackAndWhitePostProcess, _super);
  12345. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12346. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12347. }
  12348. return BlackAndWhitePostProcess;
  12349. })(BABYLON.PostProcess);
  12350. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12351. })(BABYLON || (BABYLON = {}));
  12352. var __extends = this.__extends || function (d, b) {
  12353. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12354. function __() { this.constructor = d; }
  12355. __.prototype = b.prototype;
  12356. d.prototype = new __();
  12357. };
  12358. var BABYLON;
  12359. (function (BABYLON) {
  12360. var ConvolutionPostProcess = (function (_super) {
  12361. __extends(ConvolutionPostProcess, _super);
  12362. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12363. var _this = this;
  12364. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12365. this.kernel = kernel;
  12366. this.onApply = function (effect) {
  12367. effect.setFloat2("screenSize", _this.width, _this.height);
  12368. effect.setArray("kernel", _this.kernel);
  12369. };
  12370. }
  12371. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12372. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12373. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12374. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12375. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12376. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12377. return ConvolutionPostProcess;
  12378. })(BABYLON.PostProcess);
  12379. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12380. })(BABYLON || (BABYLON = {}));
  12381. var __extends = this.__extends || function (d, b) {
  12382. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12383. function __() { this.constructor = d; }
  12384. __.prototype = b.prototype;
  12385. d.prototype = new __();
  12386. };
  12387. var BABYLON;
  12388. (function (BABYLON) {
  12389. var FxaaPostProcess = (function (_super) {
  12390. __extends(FxaaPostProcess, _super);
  12391. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12392. var _this = this;
  12393. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12394. this.onSizeChanged = function () {
  12395. _this.texelWidth = 1.0 / _this.width;
  12396. _this.texelHeight = 1.0 / _this.height;
  12397. };
  12398. this.onApply = function (effect) {
  12399. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12400. };
  12401. }
  12402. return FxaaPostProcess;
  12403. })(BABYLON.PostProcess);
  12404. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12405. })(BABYLON || (BABYLON = {}));
  12406. var BABYLON;
  12407. (function (BABYLON) {
  12408. var LensFlare = (function () {
  12409. function LensFlare(size, position, color, imgUrl, system) {
  12410. this.size = size;
  12411. this.position = position;
  12412. this.dispose = function () {
  12413. if (this.texture) {
  12414. this.texture.dispose();
  12415. }
  12416. var index = this._system.lensFlares.indexOf(this);
  12417. this._system.lensFlares.splice(index, 1);
  12418. };
  12419. this.color = color || new BABYLON.Color3(1, 1, 1);
  12420. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12421. this._system = system;
  12422. system.lensFlares.push(this);
  12423. }
  12424. return LensFlare;
  12425. })();
  12426. BABYLON.LensFlare = LensFlare;
  12427. })(BABYLON || (BABYLON = {}));
  12428. var BABYLON;
  12429. (function (BABYLON) {
  12430. var LensFlareSystem = (function () {
  12431. function LensFlareSystem(name, emitter, scene) {
  12432. this.name = name;
  12433. this.lensFlares = new Array();
  12434. this.borderLimit = 300;
  12435. this._vertexDeclaration = [2];
  12436. this._vertexStrideSize = 2 * 4;
  12437. this._isEnabled = true;
  12438. this._scene = scene;
  12439. this._emitter = emitter;
  12440. scene.lensFlareSystems.push(this);
  12441. this.meshesSelectionPredicate = function (m) {
  12442. return m.material && m.isVisible && m.isEnabled() && m.checkCollisions && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12443. };
  12444. var vertices = [];
  12445. vertices.push(1, 1);
  12446. vertices.push(-1, 1);
  12447. vertices.push(-1, -1);
  12448. vertices.push(1, -1);
  12449. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12450. var indices = [];
  12451. indices.push(0);
  12452. indices.push(1);
  12453. indices.push(2);
  12454. indices.push(0);
  12455. indices.push(2);
  12456. indices.push(3);
  12457. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12458. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12459. }
  12460. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12461. get: function () {
  12462. return this._isEnabled;
  12463. },
  12464. set: function (value) {
  12465. this._isEnabled = value;
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. LensFlareSystem.prototype.getScene = function () {
  12471. return this._scene;
  12472. };
  12473. LensFlareSystem.prototype.getEmitter = function () {
  12474. return this._emitter;
  12475. };
  12476. LensFlareSystem.prototype.getEmitterPosition = function () {
  12477. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12478. };
  12479. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12480. var position = this.getEmitterPosition();
  12481. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12482. this._positionX = position.x;
  12483. this._positionY = position.y;
  12484. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12485. if (position.z > 0) {
  12486. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12487. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12488. return true;
  12489. }
  12490. }
  12491. return false;
  12492. };
  12493. LensFlareSystem.prototype._isVisible = function () {
  12494. if (!this._isEnabled) {
  12495. return false;
  12496. }
  12497. var emitterPosition = this.getEmitterPosition();
  12498. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12499. var distance = direction.length();
  12500. direction.normalize();
  12501. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12502. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12503. return !pickInfo.hit || pickInfo.distance > distance;
  12504. };
  12505. LensFlareSystem.prototype.render = function () {
  12506. if (!this._effect.isReady())
  12507. return false;
  12508. var engine = this._scene.getEngine();
  12509. var viewport = this._scene.activeCamera.viewport;
  12510. var globalViewport = viewport.toGlobal(engine);
  12511. if (!this.computeEffectivePosition(globalViewport)) {
  12512. return false;
  12513. }
  12514. if (!this._isVisible()) {
  12515. return false;
  12516. }
  12517. var awayX;
  12518. var awayY;
  12519. if (this._positionX < this.borderLimit + globalViewport.x) {
  12520. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12521. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12522. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12523. } else {
  12524. awayX = 0;
  12525. }
  12526. if (this._positionY < this.borderLimit + globalViewport.y) {
  12527. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12528. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12529. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12530. } else {
  12531. awayY = 0;
  12532. }
  12533. var away = (awayX > awayY) ? awayX : awayY;
  12534. if (away > this.borderLimit) {
  12535. away = this.borderLimit;
  12536. }
  12537. var intensity = 1.0 - (away / this.borderLimit);
  12538. if (intensity < 0) {
  12539. return false;
  12540. }
  12541. if (intensity > 1.0) {
  12542. intensity = 1.0;
  12543. }
  12544. var centerX = globalViewport.x + globalViewport.width / 2;
  12545. var centerY = globalViewport.y + globalViewport.height / 2;
  12546. var distX = centerX - this._positionX;
  12547. var distY = centerY - this._positionY;
  12548. engine.enableEffect(this._effect);
  12549. engine.setState(false);
  12550. engine.setDepthBuffer(false);
  12551. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12552. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12553. for (var index = 0; index < this.lensFlares.length; index++) {
  12554. var flare = this.lensFlares[index];
  12555. var x = centerX - (distX * flare.position);
  12556. var y = centerY - (distY * flare.position);
  12557. var cw = flare.size;
  12558. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12559. var cx = 2 * (x / globalViewport.width) - 1.0;
  12560. var cy = 1.0 - 2 * (y / globalViewport.height);
  12561. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12562. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12563. this._effect.setTexture("textureSampler", flare.texture);
  12564. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12565. engine.draw(true, 0, 6);
  12566. }
  12567. engine.setDepthBuffer(true);
  12568. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12569. return true;
  12570. };
  12571. LensFlareSystem.prototype.dispose = function () {
  12572. if (this._vertexBuffer) {
  12573. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12574. this._vertexBuffer = null;
  12575. }
  12576. if (this._indexBuffer) {
  12577. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12578. this._indexBuffer = null;
  12579. }
  12580. while (this.lensFlares.length) {
  12581. this.lensFlares[0].dispose();
  12582. }
  12583. var index = this._scene.lensFlareSystems.indexOf(this);
  12584. this._scene.lensFlareSystems.splice(index, 1);
  12585. };
  12586. return LensFlareSystem;
  12587. })();
  12588. BABYLON.LensFlareSystem = LensFlareSystem;
  12589. })(BABYLON || (BABYLON = {}));
  12590. var BABYLON;
  12591. (function (BABYLON) {
  12592. var IntersectionInfo = (function () {
  12593. function IntersectionInfo(bu, bv, distance) {
  12594. this.bu = bu;
  12595. this.bv = bv;
  12596. this.distance = distance;
  12597. this.faceId = 0;
  12598. }
  12599. return IntersectionInfo;
  12600. })();
  12601. BABYLON.IntersectionInfo = IntersectionInfo;
  12602. var PickingInfo = (function () {
  12603. function PickingInfo() {
  12604. this.hit = false;
  12605. this.distance = 0;
  12606. this.pickedPoint = null;
  12607. this.pickedMesh = null;
  12608. this.bu = 0;
  12609. this.bv = 0;
  12610. this.faceId = -1;
  12611. }
  12612. PickingInfo.prototype.getNormal = function () {
  12613. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12614. return null;
  12615. }
  12616. var indices = this.pickedMesh.getIndices();
  12617. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12618. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12619. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12620. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12621. normal0 = normal0.scale(this.bu);
  12622. normal1 = normal1.scale(this.bv);
  12623. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12624. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12625. };
  12626. PickingInfo.prototype.getTextureCoordinates = function () {
  12627. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12628. return null;
  12629. }
  12630. var indices = this.pickedMesh.getIndices();
  12631. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12632. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12633. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12634. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12635. uv0 = uv0.scale(this.bu);
  12636. uv1 = uv1.scale(this.bv);
  12637. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12638. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12639. };
  12640. return PickingInfo;
  12641. })();
  12642. BABYLON.PickingInfo = PickingInfo;
  12643. })(BABYLON || (BABYLON = {}));
  12644. var BABYLON;
  12645. (function (BABYLON) {
  12646. var FilesInput = (function () {
  12647. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12648. this.engine = p_engine;
  12649. this.canvas = p_canvas;
  12650. this.currentScene = p_scene;
  12651. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12652. this.progressCallback = p_progressCallback;
  12653. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12654. this.textureLoadingCallback = p_textureLoadingCallback;
  12655. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12656. }
  12657. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12658. var _this = this;
  12659. if (p_elementToMonitor) {
  12660. this.elementToMonitor = p_elementToMonitor;
  12661. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12662. _this.drag(e);
  12663. }, false);
  12664. this.elementToMonitor.addEventListener("dragover", function (e) {
  12665. _this.drag(e);
  12666. }, false);
  12667. this.elementToMonitor.addEventListener("drop", function (e) {
  12668. _this.drop(e);
  12669. }, false);
  12670. }
  12671. };
  12672. FilesInput.prototype.renderFunction = function () {
  12673. if (this.additionnalRenderLoopLogicCallback) {
  12674. this.additionnalRenderLoopLogicCallback();
  12675. }
  12676. if (this.currentScene) {
  12677. if (this.textureLoadingCallback) {
  12678. var remaining = this.currentScene.getWaitingItemsCount();
  12679. if (remaining > 0) {
  12680. this.textureLoadingCallback(remaining);
  12681. }
  12682. }
  12683. this.currentScene.render();
  12684. }
  12685. };
  12686. FilesInput.prototype.drag = function (e) {
  12687. e.stopPropagation();
  12688. e.preventDefault();
  12689. };
  12690. FilesInput.prototype.drop = function (eventDrop) {
  12691. eventDrop.stopPropagation();
  12692. eventDrop.preventDefault();
  12693. this.loadFiles(eventDrop);
  12694. };
  12695. FilesInput.prototype.loadFiles = function (event) {
  12696. var _this = this;
  12697. var that = this;
  12698. if (this.startingProcessingFilesCallback)
  12699. this.startingProcessingFilesCallback();
  12700. var sceneFileToLoad;
  12701. var filesToLoad;
  12702. if (event && event.dataTransfer && event.dataTransfer.files) {
  12703. filesToLoad = event.dataTransfer.files;
  12704. }
  12705. if (event && event.target && event.target.files) {
  12706. filesToLoad = event.target.files;
  12707. }
  12708. if (filesToLoad && filesToLoad.length > 0) {
  12709. for (var i = 0; i < filesToLoad.length; i++) {
  12710. switch (filesToLoad[i].type) {
  12711. case "image/jpeg":
  12712. case "image/png":
  12713. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12714. break;
  12715. case "image/targa":
  12716. case "image/vnd.ms-dds":
  12717. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12718. break;
  12719. default:
  12720. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  12721. sceneFileToLoad = filesToLoad[i];
  12722. }
  12723. break;
  12724. }
  12725. }
  12726. if (sceneFileToLoad) {
  12727. if (this.currentScene) {
  12728. this.engine.stopRenderLoop();
  12729. this.currentScene.dispose();
  12730. }
  12731. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12732. that.currentScene = newScene;
  12733. that.currentScene.executeWhenReady(function () {
  12734. if (that.currentScene.activeCamera) {
  12735. that.currentScene.activeCamera.attachControl(that.canvas);
  12736. }
  12737. if (that.sceneLoadedCallback) {
  12738. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12739. }
  12740. that.engine.runRenderLoop(function () {
  12741. that.renderFunction();
  12742. });
  12743. });
  12744. }, function (progress) {
  12745. if (_this.progressCallback) {
  12746. _this.progressCallback(progress);
  12747. }
  12748. });
  12749. } else {
  12750. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12751. }
  12752. }
  12753. };
  12754. FilesInput.FilesTextures = new Array();
  12755. FilesInput.FilesToLoad = new Array();
  12756. return FilesInput;
  12757. })();
  12758. BABYLON.FilesInput = FilesInput;
  12759. })(BABYLON || (BABYLON = {}));
  12760. var BABYLON;
  12761. (function (BABYLON) {
  12762. var OimoJSPlugin = (function () {
  12763. function OimoJSPlugin() {
  12764. this._registeredMeshes = [];
  12765. /**
  12766. * Update the body position according to the mesh position
  12767. * @param mesh
  12768. */
  12769. this.updateBodyPosition = function (mesh) {
  12770. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12771. var registeredMesh = this._registeredMeshes[index];
  12772. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12773. var body = registeredMesh.body.body;
  12774. var center = mesh.getBoundingInfo().boundingBox.center;
  12775. body.setPosition(center.x, center.y, center.z);
  12776. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12777. return;
  12778. }
  12779. if (registeredMesh.mesh.parent === mesh) {
  12780. mesh.computeWorldMatrix(true);
  12781. registeredMesh.mesh.computeWorldMatrix(true);
  12782. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12783. var absoluteRotation = mesh.rotation;
  12784. body = registeredMesh.body.body;
  12785. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12786. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12787. return;
  12788. }
  12789. }
  12790. };
  12791. }
  12792. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12793. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12794. };
  12795. OimoJSPlugin.prototype.initialize = function (iterations) {
  12796. this._world = new OIMO.World();
  12797. this._world.clear();
  12798. };
  12799. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12800. this._world.gravity = gravity;
  12801. };
  12802. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12803. var body = null;
  12804. this.unregisterMesh(mesh);
  12805. mesh.computeWorldMatrix(true);
  12806. switch (impostor) {
  12807. case BABYLON.PhysicsEngine.SphereImpostor:
  12808. var bbox = mesh.getBoundingInfo().boundingBox;
  12809. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12810. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12811. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12812. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12813. var deltaPosition = mesh.position.subtract(bbox.center);
  12814. body = new OIMO.Body({
  12815. type: 'sphere',
  12816. size: [size],
  12817. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12818. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12819. move: options.mass != 0,
  12820. config: [options.mass, options.friction, options.restitution],
  12821. world: this._world
  12822. });
  12823. this._registeredMeshes.push({
  12824. mesh: mesh,
  12825. body: body,
  12826. delta: deltaPosition
  12827. });
  12828. break;
  12829. case BABYLON.PhysicsEngine.PlaneImpostor:
  12830. case BABYLON.PhysicsEngine.BoxImpostor:
  12831. bbox = mesh.getBoundingInfo().boundingBox;
  12832. var min = bbox.minimumWorld;
  12833. var max = bbox.maximumWorld;
  12834. var box = max.subtract(min);
  12835. var sizeX = this._checkWithEpsilon(box.x);
  12836. var sizeY = this._checkWithEpsilon(box.y);
  12837. var sizeZ = this._checkWithEpsilon(box.z);
  12838. var deltaPosition = mesh.position.subtract(bbox.center);
  12839. body = new OIMO.Body({
  12840. type: 'box',
  12841. size: [sizeX, sizeY, sizeZ],
  12842. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12843. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12844. move: options.mass != 0,
  12845. config: [options.mass, options.friction, options.restitution],
  12846. world: this._world
  12847. });
  12848. this._registeredMeshes.push({
  12849. mesh: mesh,
  12850. body: body,
  12851. delta: deltaPosition
  12852. });
  12853. break;
  12854. }
  12855. return body;
  12856. };
  12857. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  12858. var types = [], sizes = [], positions = [], rotations = [];
  12859. var initialMesh = parts[0].mesh;
  12860. for (var index = 0; index < parts.length; index++) {
  12861. var part = parts[index];
  12862. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  12863. types.push(bodyParameters.type);
  12864. sizes.push.apply(sizes, bodyParameters.size);
  12865. positions.push.apply(positions, bodyParameters.pos);
  12866. rotations.push.apply(rotations, bodyParameters.rot);
  12867. }
  12868. var body = new OIMO.Body({
  12869. type: types,
  12870. size: sizes,
  12871. pos: positions,
  12872. rot: rotations,
  12873. move: options.mass != 0,
  12874. config: [options.mass, options.friction, options.restitution],
  12875. world: this._world
  12876. });
  12877. this._registeredMeshes.push({
  12878. mesh: initialMesh,
  12879. body: body
  12880. });
  12881. return body;
  12882. };
  12883. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  12884. var bodyParameters = null;
  12885. var mesh = part.mesh;
  12886. switch (part.impostor) {
  12887. case BABYLON.PhysicsEngine.SphereImpostor:
  12888. var bbox = mesh.getBoundingInfo().boundingBox;
  12889. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12890. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12891. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12892. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12893. bodyParameters = {
  12894. type: 'sphere',
  12895. /* bug with oimo : sphere needs 3 sizes in this case */
  12896. size: [size, -1, -1],
  12897. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  12898. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12899. };
  12900. break;
  12901. case BABYLON.PhysicsEngine.PlaneImpostor:
  12902. case BABYLON.PhysicsEngine.BoxImpostor:
  12903. bbox = mesh.getBoundingInfo().boundingBox;
  12904. var min = bbox.minimumWorld;
  12905. var max = bbox.maximumWorld;
  12906. var box = max.subtract(min);
  12907. var sizeX = this._checkWithEpsilon(box.x);
  12908. var sizeY = this._checkWithEpsilon(box.y);
  12909. var sizeZ = this._checkWithEpsilon(box.z);
  12910. var relativePosition = mesh.position;
  12911. bodyParameters = {
  12912. type: 'box',
  12913. size: [sizeX, sizeY, sizeZ],
  12914. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  12915. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12916. };
  12917. break;
  12918. }
  12919. return bodyParameters;
  12920. };
  12921. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  12922. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12923. var registeredMesh = this._registeredMeshes[index];
  12924. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12925. if (registeredMesh.body) {
  12926. this._world.removeRigidBody(registeredMesh.body.body);
  12927. this._unbindBody(registeredMesh.body);
  12928. }
  12929. this._registeredMeshes.splice(index, 1);
  12930. return;
  12931. }
  12932. }
  12933. };
  12934. OimoJSPlugin.prototype._unbindBody = function (body) {
  12935. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12936. var registeredMesh = this._registeredMeshes[index];
  12937. if (registeredMesh.body === body) {
  12938. registeredMesh.body = null;
  12939. }
  12940. }
  12941. };
  12942. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  12943. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12944. var registeredMesh = this._registeredMeshes[index];
  12945. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12946. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE));
  12947. return;
  12948. }
  12949. }
  12950. };
  12951. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  12952. var body1 = null, body2 = null;
  12953. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12954. var registeredMesh = this._registeredMeshes[index];
  12955. if (registeredMesh.mesh === mesh1) {
  12956. body1 = registeredMesh.body.body;
  12957. } else if (registeredMesh.mesh === mesh2) {
  12958. body2 = registeredMesh.body.body;
  12959. }
  12960. }
  12961. if (!body1 || !body2) {
  12962. return false;
  12963. }
  12964. if (!options) {
  12965. options = {};
  12966. }
  12967. new OIMO.Link({
  12968. type: options.type,
  12969. body1: body1,
  12970. body2: body2,
  12971. min: options.min,
  12972. max: options.max,
  12973. axe1: options.axe1,
  12974. axe2: options.axe2,
  12975. pos1: [pivot1.x, pivot1.y, pivot1.z],
  12976. pos2: [pivot2.x, pivot2.y, pivot2.z],
  12977. collision: options.collision,
  12978. spring: options.spring,
  12979. world: this._world
  12980. });
  12981. return true;
  12982. };
  12983. OimoJSPlugin.prototype.dispose = function () {
  12984. this._world.clear();
  12985. while (this._registeredMeshes.length) {
  12986. this.unregisterMesh(this._registeredMeshes[0].mesh);
  12987. }
  12988. };
  12989. OimoJSPlugin.prototype.isSupported = function () {
  12990. return OIMO !== undefined;
  12991. };
  12992. OimoJSPlugin.prototype._getLastShape = function (body) {
  12993. var lastShape = body.shapes;
  12994. while (lastShape.next) {
  12995. lastShape = lastShape.next;
  12996. }
  12997. return lastShape;
  12998. };
  12999. OimoJSPlugin.prototype.runOneStep = function (time) {
  13000. this._world.step();
  13001. var i = this._registeredMeshes.length;
  13002. var m;
  13003. while (i--) {
  13004. var body = this._registeredMeshes[i].body.body;
  13005. var mesh = this._registeredMeshes[i].mesh;
  13006. var delta = this._registeredMeshes[i].delta;
  13007. if (!body.sleeping) {
  13008. if (body.shapes.next) {
  13009. var parentShape = this._getLastShape(body);
  13010. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13011. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13012. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13013. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13014. if (!mesh.rotationQuaternion) {
  13015. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13016. }
  13017. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13018. } else {
  13019. m = body.getMatrix();
  13020. mtx = BABYLON.Matrix.FromArray(m);
  13021. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13022. if (!delta) {
  13023. mesh.position.x = bodyX;
  13024. mesh.position.y = bodyY;
  13025. mesh.position.z = bodyZ;
  13026. } else {
  13027. mesh.position.x = bodyX + delta.x;
  13028. mesh.position.y = bodyY + delta.y;
  13029. mesh.position.z = bodyZ + delta.z;
  13030. }
  13031. if (!mesh.rotationQuaternion) {
  13032. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13033. }
  13034. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13035. }
  13036. }
  13037. }
  13038. };
  13039. return OimoJSPlugin;
  13040. })();
  13041. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13042. })(BABYLON || (BABYLON = {}));
  13043. var BABYLON;
  13044. (function (BABYLON) {
  13045. var PhysicsEngine = (function () {
  13046. function PhysicsEngine(plugin) {
  13047. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13048. }
  13049. PhysicsEngine.prototype._initialize = function (gravity) {
  13050. this._currentPlugin.initialize();
  13051. this._setGravity(gravity);
  13052. };
  13053. PhysicsEngine.prototype._runOneStep = function (delta) {
  13054. if (delta > 0.1) {
  13055. delta = 0.1;
  13056. } else if (delta <= 0) {
  13057. delta = 1.0 / 60.0;
  13058. }
  13059. this._currentPlugin.runOneStep(delta);
  13060. };
  13061. PhysicsEngine.prototype._setGravity = function (gravity) {
  13062. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13063. this._currentPlugin.setGravity(this.gravity);
  13064. };
  13065. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13066. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13067. };
  13068. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13069. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13070. };
  13071. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13072. this._currentPlugin.unregisterMesh(mesh);
  13073. };
  13074. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13075. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13076. };
  13077. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13078. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13079. };
  13080. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13081. this._currentPlugin.updateBodyPosition(mesh);
  13082. };
  13083. PhysicsEngine.prototype.dispose = function () {
  13084. this._currentPlugin.dispose();
  13085. };
  13086. PhysicsEngine.prototype.isSupported = function () {
  13087. return this._currentPlugin.isSupported();
  13088. };
  13089. PhysicsEngine.NoImpostor = 0;
  13090. PhysicsEngine.SphereImpostor = 1;
  13091. PhysicsEngine.BoxImpostor = 2;
  13092. PhysicsEngine.PlaneImpostor = 3;
  13093. PhysicsEngine.CompoundImpostor = 4;
  13094. PhysicsEngine.MeshImpostor = 4;
  13095. PhysicsEngine.CapsuleImpostor = 5;
  13096. PhysicsEngine.ConeImpostor = 6;
  13097. PhysicsEngine.CylinderImpostor = 7;
  13098. PhysicsEngine.ConvexHullImpostor = 8;
  13099. PhysicsEngine.Epsilon = 0.001;
  13100. return PhysicsEngine;
  13101. })();
  13102. BABYLON.PhysicsEngine = PhysicsEngine;
  13103. })(BABYLON || (BABYLON = {}));
  13104. var BABYLON;
  13105. (function (BABYLON) {
  13106. var serializeLight = function (light) {
  13107. var serializationObject = {};
  13108. serializationObject.name = light.name;
  13109. serializationObject.id = light.id;
  13110. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13111. if (light instanceof BABYLON.PointLight) {
  13112. serializationObject.type = 0;
  13113. serializationObject.position = light.position.asArray();
  13114. } else if (light instanceof BABYLON.DirectionalLight) {
  13115. serializationObject.type = 1;
  13116. var directionalLight = light;
  13117. serializationObject.position = directionalLight.position.asArray();
  13118. serializationObject.direction = directionalLight.direction.asArray();
  13119. } else if (light instanceof BABYLON.SpotLight) {
  13120. serializationObject.type = 2;
  13121. var spotLight = light;
  13122. serializationObject.position = spotLight.position.asArray();
  13123. serializationObject.direction = spotLight.position.asArray();
  13124. serializationObject.angle = spotLight.angle;
  13125. serializationObject.exponent = spotLight.exponent;
  13126. } else if (light instanceof BABYLON.HemisphericLight) {
  13127. serializationObject.type = 3;
  13128. var hemisphericLight = light;
  13129. serializationObject.direction = hemisphericLight.direction.asArray();
  13130. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13131. }
  13132. if (light.intensity) {
  13133. serializationObject.intensity = light.intensity;
  13134. }
  13135. serializationObject.range = light.range;
  13136. serializationObject.diffuse = light.diffuse.asArray();
  13137. serializationObject.specular = light.specular.asArray();
  13138. return serializationObject;
  13139. };
  13140. var serializeCamera = function (camera) {
  13141. var serializationObject = {};
  13142. serializationObject.name = camera.name;
  13143. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13144. serializationObject.id = camera.id;
  13145. serializationObject.position = camera.position.asArray();
  13146. if (camera.parent) {
  13147. serializationObject.parentId = camera.parent.id;
  13148. }
  13149. serializationObject.rotation = camera.rotation.asArray();
  13150. if (camera.lockedTarget && camera.lockedTarget.id) {
  13151. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13152. }
  13153. serializationObject.fov = camera.fov;
  13154. serializationObject.minZ = camera.minZ;
  13155. serializationObject.maxZ = camera.maxZ;
  13156. serializationObject.speed = camera.speed;
  13157. serializationObject.inertia = camera.inertia;
  13158. serializationObject.checkCollisions = camera.checkCollisions;
  13159. serializationObject.applyGravity = camera.applyGravity;
  13160. if (camera.ellipsoid) {
  13161. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13162. }
  13163. appendAnimations(camera, serializationObject);
  13164. serializationObject.layerMask = camera.layerMask;
  13165. return serializationObject;
  13166. };
  13167. var appendAnimations = function (source, destination) {
  13168. if (source.animations) {
  13169. destination.animations = [];
  13170. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13171. var animation = source.animations[animationIndex];
  13172. destination.animations.push(serializeAnimation(animation));
  13173. }
  13174. }
  13175. };
  13176. var serializeAnimation = function (animation) {
  13177. var serializationObject = {};
  13178. serializationObject.name = animation.name;
  13179. serializationObject.property = animation.targetProperty;
  13180. serializationObject.framePerSecond = animation.framePerSecond;
  13181. serializationObject.dataType = animation.dataType;
  13182. serializationObject.loopBehavior = animation.loopMode;
  13183. var dataType = animation.dataType;
  13184. serializationObject.keys = [];
  13185. var keys = animation.getKeys();
  13186. for (var index = 0; index < keys.length; index++) {
  13187. var animationKey = keys[index];
  13188. var key = {};
  13189. key.frame = animationKey.frame;
  13190. switch (dataType) {
  13191. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13192. key.values = [animationKey.value];
  13193. break;
  13194. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13195. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13196. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13197. key.values = animationKey.value.asArray();
  13198. break;
  13199. }
  13200. serializationObject.keys.push(key);
  13201. }
  13202. return serializationObject;
  13203. };
  13204. var serializeMultiMaterial = function (material) {
  13205. var serializationObject = {};
  13206. serializationObject.name = material.name;
  13207. serializationObject.id = material.id;
  13208. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13209. serializationObject.materials = [];
  13210. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13211. var subMat = material.subMaterials[matIndex];
  13212. if (subMat) {
  13213. serializationObject.materials.push(subMat.id);
  13214. } else {
  13215. serializationObject.materials.push(null);
  13216. }
  13217. }
  13218. return serializationObject;
  13219. };
  13220. var serializeMaterial = function (material) {
  13221. var serializationObject = {};
  13222. serializationObject.name = material.name;
  13223. serializationObject.ambient = material.ambientColor.asArray();
  13224. serializationObject.diffuse = material.diffuseColor.asArray();
  13225. serializationObject.specular = material.specularColor.asArray();
  13226. serializationObject.specularPower = material.specularPower;
  13227. serializationObject.emissive = material.emissiveColor.asArray();
  13228. serializationObject.alpha = material.alpha;
  13229. serializationObject.id = material.id;
  13230. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13231. serializationObject.backFaceCulling = material.backFaceCulling;
  13232. if (material.diffuseTexture) {
  13233. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13234. }
  13235. if (material.ambientTexture) {
  13236. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13237. }
  13238. if (material.opacityTexture) {
  13239. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13240. }
  13241. if (material.reflectionTexture) {
  13242. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13243. }
  13244. if (material.emissiveTexture) {
  13245. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13246. }
  13247. if (material.specularTexture) {
  13248. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13249. }
  13250. if (material.bumpTexture) {
  13251. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13252. }
  13253. return serializationObject;
  13254. };
  13255. var serializeTexture = function (texture) {
  13256. var serializationObject = {};
  13257. if (!texture.name) {
  13258. return null;
  13259. }
  13260. if (texture instanceof BABYLON.CubeTexture) {
  13261. serializationObject.name = texture.name;
  13262. serializationObject.hasAlpha = texture.hasAlpha;
  13263. serializationObject.level = texture.level;
  13264. serializationObject.coordinatesMode = texture.coordinatesMode;
  13265. return serializationObject;
  13266. }
  13267. if (texture instanceof BABYLON.MirrorTexture) {
  13268. var mirrorTexture = texture;
  13269. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13270. serializationObject.renderList = [];
  13271. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13272. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13273. }
  13274. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13275. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13276. var renderTargetTexture = texture;
  13277. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13278. serializationObject.renderList = [];
  13279. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13280. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13281. }
  13282. }
  13283. var regularTexture = texture;
  13284. serializationObject.name = texture.name;
  13285. serializationObject.hasAlpha = texture.hasAlpha;
  13286. serializationObject.level = texture.level;
  13287. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13288. serializationObject.coordinatesMode = texture.coordinatesMode;
  13289. serializationObject.uOffset = regularTexture.uOffset;
  13290. serializationObject.vOffset = regularTexture.vOffset;
  13291. serializationObject.uScale = regularTexture.uScale;
  13292. serializationObject.vScale = regularTexture.vScale;
  13293. serializationObject.uAng = regularTexture.uAng;
  13294. serializationObject.vAng = regularTexture.vAng;
  13295. serializationObject.wAng = regularTexture.wAng;
  13296. serializationObject.wrapU = texture.wrapU;
  13297. serializationObject.wrapV = texture.wrapV;
  13298. appendAnimations(texture, serializationObject);
  13299. return serializationObject;
  13300. };
  13301. var serializeSkeleton = function (skeleton) {
  13302. var serializationObject = {};
  13303. serializationObject.name = skeleton.name;
  13304. serializationObject.id = skeleton.id;
  13305. serializationObject.bones = [];
  13306. for (var index = 0; index < skeleton.bones.length; index++) {
  13307. var bone = skeleton.bones[index];
  13308. var serializedBone = {
  13309. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13310. name: bone.name,
  13311. matrix: bone.getLocalMatrix().toArray()
  13312. };
  13313. serializationObject.bones.push(serializedBone);
  13314. if (bone.animations && bone.animations.length > 0) {
  13315. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13316. }
  13317. }
  13318. return serializationObject;
  13319. };
  13320. var serializeParticleSystem = function (particleSystem) {
  13321. var serializationObject = {};
  13322. serializationObject.emitterId = particleSystem.emitter.id;
  13323. serializationObject.capacity = particleSystem.getCapacity();
  13324. if (particleSystem.particleTexture) {
  13325. serializationObject.textureName = particleSystem.particleTexture.name;
  13326. }
  13327. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13328. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13329. serializationObject.minSize = particleSystem.minSize;
  13330. serializationObject.maxSize = particleSystem.maxSize;
  13331. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13332. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13333. serializationObject.emitRate = particleSystem.emitRate;
  13334. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13335. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13336. serializationObject.gravity = particleSystem.gravity.asArray();
  13337. serializationObject.direction1 = particleSystem.direction1.asArray();
  13338. serializationObject.direction2 = particleSystem.direction2.asArray();
  13339. serializationObject.color1 = particleSystem.color1.asArray();
  13340. serializationObject.color2 = particleSystem.color2.asArray();
  13341. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13342. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13343. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13344. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13345. serializationObject.blendMode = particleSystem.blendMode;
  13346. return serializationObject;
  13347. };
  13348. var serializeLensFlareSystem = function (lensFlareSystem) {
  13349. var serializationObject = {};
  13350. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13351. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13352. serializationObject.flares = [];
  13353. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13354. var flare = lensFlareSystem.lensFlares[index];
  13355. serializationObject.flares.push({
  13356. size: flare.size,
  13357. position: flare.position,
  13358. color: flare.color.asArray(),
  13359. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13360. });
  13361. }
  13362. return serializationObject;
  13363. };
  13364. var serializeShadowGenerator = function (light) {
  13365. var serializationObject = {};
  13366. var shadowGenerator = light.getShadowGenerator();
  13367. serializationObject.lightId = light.id;
  13368. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13369. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13370. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13371. serializationObject.renderList = [];
  13372. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13373. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13374. serializationObject.renderList.push(mesh.id);
  13375. }
  13376. return serializationObject;
  13377. };
  13378. var serializedGeometries = [];
  13379. var serializeGeometry = function (geometry, serializationGeometries) {
  13380. if (serializedGeometries[geometry.id]) {
  13381. return;
  13382. }
  13383. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13384. serializationGeometries.boxes.push(serializeBox(geometry));
  13385. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13386. serializationGeometries.spheres.push(serializeSphere(geometry));
  13387. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13388. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13389. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13390. serializationGeometries.toruses.push(serializeTorus(geometry));
  13391. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13392. serializationGeometries.grounds.push(serializeGround(geometry));
  13393. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13394. serializationGeometries.planes.push(serializePlane(geometry));
  13395. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13396. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13397. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13398. throw new Error("Unknow primitive type");
  13399. } else {
  13400. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13401. }
  13402. serializedGeometries[geometry.id] = true;
  13403. };
  13404. var serializeGeometryBase = function (geometry) {
  13405. var serializationObject = {};
  13406. serializationObject.id = geometry.id;
  13407. if (BABYLON.Tags.HasTags(geometry)) {
  13408. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13409. }
  13410. return serializationObject;
  13411. };
  13412. var serializeVertexData = function (vertexData) {
  13413. var serializationObject = serializeGeometryBase(vertexData);
  13414. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13415. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13416. }
  13417. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13418. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13419. }
  13420. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13421. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13422. }
  13423. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13424. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13425. }
  13426. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13427. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13428. }
  13429. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13430. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13431. serializationObject.matricesIndices._isExpanded = true;
  13432. }
  13433. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13434. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13435. }
  13436. serializationObject.indices = vertexData.getIndices();
  13437. return serializationObject;
  13438. };
  13439. var serializePrimitive = function (primitive) {
  13440. var serializationObject = serializeGeometryBase(primitive);
  13441. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13442. return serializationObject;
  13443. };
  13444. var serializeBox = function (box) {
  13445. var serializationObject = serializePrimitive(box);
  13446. serializationObject.size = box.size;
  13447. return serializationObject;
  13448. };
  13449. var serializeSphere = function (sphere) {
  13450. var serializationObject = serializePrimitive(sphere);
  13451. serializationObject.segments = sphere.segments;
  13452. serializationObject.diameter = sphere.diameter;
  13453. return serializationObject;
  13454. };
  13455. var serializeCylinder = function (cylinder) {
  13456. var serializationObject = serializePrimitive(cylinder);
  13457. serializationObject.height = cylinder.height;
  13458. serializationObject.diameterTop = cylinder.diameterTop;
  13459. serializationObject.diameterBottom = cylinder.diameterBottom;
  13460. serializationObject.tessellation = cylinder.tessellation;
  13461. return serializationObject;
  13462. };
  13463. var serializeTorus = function (torus) {
  13464. var serializationObject = serializePrimitive(torus);
  13465. serializationObject.diameter = torus.diameter;
  13466. serializationObject.thickness = torus.thickness;
  13467. serializationObject.tessellation = torus.tessellation;
  13468. return serializationObject;
  13469. };
  13470. var serializeGround = function (ground) {
  13471. var serializationObject = serializePrimitive(ground);
  13472. serializationObject.width = ground.width;
  13473. serializationObject.height = ground.height;
  13474. serializationObject.subdivisions = ground.subdivisions;
  13475. return serializationObject;
  13476. };
  13477. var serializePlane = function (plane) {
  13478. var serializationObject = serializePrimitive(plane);
  13479. serializationObject.size = plane.size;
  13480. return serializationObject;
  13481. };
  13482. var serializeTorusKnot = function (torusKnot) {
  13483. var serializationObject = serializePrimitive(torusKnot);
  13484. serializationObject.radius = torusKnot.radius;
  13485. serializationObject.tube = torusKnot.tube;
  13486. serializationObject.radialSegments = torusKnot.radialSegments;
  13487. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13488. serializationObject.p = torusKnot.p;
  13489. serializationObject.q = torusKnot.q;
  13490. return serializationObject;
  13491. };
  13492. var serializeMesh = function (mesh, serializationScene) {
  13493. var serializationObject = {};
  13494. serializationObject.name = mesh.name;
  13495. serializationObject.id = mesh.id;
  13496. if (BABYLON.Tags.HasTags(mesh)) {
  13497. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13498. }
  13499. serializationObject.position = mesh.position.asArray();
  13500. if (mesh.rotationQuaternion) {
  13501. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13502. } else if (mesh.rotation) {
  13503. serializationObject.rotation = mesh.rotation.asArray();
  13504. }
  13505. serializationObject.scaling = mesh.scaling.asArray();
  13506. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13507. serializationObject.isEnabled = mesh.isEnabled();
  13508. serializationObject.isVisible = mesh.isVisible;
  13509. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13510. serializationObject.pickable = mesh.isPickable;
  13511. serializationObject.receiveShadows = mesh.receiveShadows;
  13512. serializationObject.billboardMode = mesh.billboardMode;
  13513. serializationObject.visibility = mesh.visibility;
  13514. serializationObject.checkCollisions = mesh.checkCollisions;
  13515. if (mesh.parent) {
  13516. serializationObject.parentId = mesh.parent.id;
  13517. }
  13518. var geometry = mesh._geometry;
  13519. if (geometry) {
  13520. var geometryId = geometry.id;
  13521. serializationObject.geometryId = geometryId;
  13522. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13523. serializeGeometry(geometry, serializationScene.geometries);
  13524. }
  13525. serializationObject.subMeshes = [];
  13526. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13527. var subMesh = mesh.subMeshes[subIndex];
  13528. serializationObject.subMeshes.push({
  13529. materialIndex: subMesh.materialIndex,
  13530. verticesStart: subMesh.verticesStart,
  13531. verticesCount: subMesh.verticesCount,
  13532. indexStart: subMesh.indexStart,
  13533. indexCount: subMesh.indexCount
  13534. });
  13535. }
  13536. }
  13537. if (mesh.material) {
  13538. serializationObject.materialId = mesh.material.id;
  13539. } else {
  13540. mesh.material = null;
  13541. }
  13542. if (mesh.skeleton) {
  13543. serializationObject.skeletonId = mesh.skeleton.id;
  13544. }
  13545. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13546. serializationObject.physicsMass = mesh.getPhysicsMass();
  13547. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13548. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13549. switch (mesh.getPhysicsImpostor()) {
  13550. case BABYLON.PhysicsEngine.BoxImpostor:
  13551. serializationObject.physicsImpostor = 1;
  13552. break;
  13553. case BABYLON.PhysicsEngine.SphereImpostor:
  13554. serializationObject.physicsImpostor = 2;
  13555. break;
  13556. }
  13557. }
  13558. serializationObject.instances = [];
  13559. for (var index = 0; index < mesh.instances.length; index++) {
  13560. var instance = mesh.instances[index];
  13561. var serializationInstance = {
  13562. name: instance.name,
  13563. position: instance.position,
  13564. rotation: instance.rotation,
  13565. rotationQuaternion: instance.rotationQuaternion,
  13566. scaling: instance.scaling
  13567. };
  13568. serializationObject.instances.push(serializationInstance);
  13569. appendAnimations(instance, serializationInstance);
  13570. }
  13571. appendAnimations(mesh, serializationObject);
  13572. serializationObject.layerMask = mesh.layerMask;
  13573. return serializationObject;
  13574. };
  13575. var SceneSerializer = (function () {
  13576. function SceneSerializer() {
  13577. }
  13578. SceneSerializer.Serialize = function (scene) {
  13579. var serializationObject = {};
  13580. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13581. serializationObject.autoClear = scene.autoClear;
  13582. serializationObject.clearColor = scene.clearColor.asArray();
  13583. serializationObject.ambientColor = scene.ambientColor.asArray();
  13584. serializationObject.gravity = scene.gravity.asArray();
  13585. if (scene.fogMode && scene.fogMode !== 0) {
  13586. serializationObject.fogMode = scene.fogMode;
  13587. serializationObject.fogColor = scene.fogColor.asArray();
  13588. serializationObject.fogStart = scene.fogStart;
  13589. serializationObject.fogEnd = scene.fogEnd;
  13590. serializationObject.fogDensity = scene.fogDensity;
  13591. }
  13592. serializationObject.lights = [];
  13593. for (var index = 0; index < scene.lights.length; index++) {
  13594. var light = scene.lights[index];
  13595. serializationObject.lights.push(serializeLight(light));
  13596. }
  13597. serializationObject.cameras = [];
  13598. for (index = 0; index < scene.cameras.length; index++) {
  13599. var camera = scene.cameras[index];
  13600. if (camera instanceof BABYLON.FreeCamera) {
  13601. serializationObject.cameras.push(serializeCamera(camera));
  13602. }
  13603. }
  13604. if (scene.activeCamera) {
  13605. serializationObject.activeCameraID = scene.activeCamera.id;
  13606. }
  13607. serializationObject.materials = [];
  13608. serializationObject.multiMaterials = [];
  13609. for (index = 0; index < scene.materials.length; index++) {
  13610. var material = scene.materials[index];
  13611. if (material instanceof BABYLON.StandardMaterial) {
  13612. serializationObject.materials.push(serializeMaterial(material));
  13613. } else if (material instanceof BABYLON.MultiMaterial) {
  13614. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13615. }
  13616. }
  13617. serializationObject.skeletons = [];
  13618. for (index = 0; index < scene.skeletons.length; index++) {
  13619. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13620. }
  13621. serializationObject.geometries = {};
  13622. serializationObject.geometries.boxes = [];
  13623. serializationObject.geometries.spheres = [];
  13624. serializationObject.geometries.cylinders = [];
  13625. serializationObject.geometries.toruses = [];
  13626. serializationObject.geometries.grounds = [];
  13627. serializationObject.geometries.planes = [];
  13628. serializationObject.geometries.torusKnots = [];
  13629. serializationObject.geometries.vertexData = [];
  13630. serializedGeometries = [];
  13631. var geometries = scene.getGeometries();
  13632. for (var index = 0; index < geometries.length; index++) {
  13633. var geometry = geometries[index];
  13634. if (geometry.isReady()) {
  13635. serializeGeometry(geometry, serializationObject.geometries);
  13636. }
  13637. }
  13638. serializationObject.meshes = [];
  13639. for (index = 0; index < scene.meshes.length; index++) {
  13640. var abstractMesh = scene.meshes[index];
  13641. if (abstractMesh instanceof BABYLON.Mesh) {
  13642. var mesh = abstractMesh;
  13643. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13644. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13645. }
  13646. }
  13647. }
  13648. serializationObject.particleSystems = [];
  13649. for (index = 0; index < scene.particleSystems.length; index++) {
  13650. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13651. }
  13652. serializationObject.lensFlareSystems = [];
  13653. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13654. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13655. }
  13656. serializationObject.shadowGenerators = [];
  13657. for (index = 0; index < scene.lights.length; index++) {
  13658. light = scene.lights[index];
  13659. if (light.getShadowGenerator()) {
  13660. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13661. }
  13662. }
  13663. return serializationObject;
  13664. };
  13665. return SceneSerializer;
  13666. })();
  13667. BABYLON.SceneSerializer = SceneSerializer;
  13668. })(BABYLON || (BABYLON = {}));
  13669. var BABYLON;
  13670. (function (BABYLON) {
  13671. var SceneLoader = (function () {
  13672. function SceneLoader() {
  13673. }
  13674. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13675. get: function () {
  13676. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13677. },
  13678. set: function (value) {
  13679. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13680. },
  13681. enumerable: true,
  13682. configurable: true
  13683. });
  13684. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13685. get: function () {
  13686. return SceneLoader._ShowLoadingScreen;
  13687. },
  13688. set: function (value) {
  13689. SceneLoader._ShowLoadingScreen = value;
  13690. },
  13691. enumerable: true,
  13692. configurable: true
  13693. });
  13694. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13695. var dotPosition = sceneFilename.lastIndexOf(".");
  13696. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13697. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13698. var plugin = this._registeredPlugins[index];
  13699. if (plugin.extensions.indexOf(extension) !== -1) {
  13700. return plugin;
  13701. }
  13702. }
  13703. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13704. };
  13705. SceneLoader.RegisterPlugin = function (plugin) {
  13706. plugin.extensions = plugin.extensions.toLowerCase();
  13707. SceneLoader._registeredPlugins.push(plugin);
  13708. };
  13709. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13710. var _this = this;
  13711. var manifestChecked = function (success) {
  13712. scene.database = database;
  13713. var plugin = _this._getPluginForFilename(sceneFilename);
  13714. var importMeshFromData = function (data) {
  13715. var meshes = [];
  13716. var particleSystems = [];
  13717. var skeletons = [];
  13718. try {
  13719. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13720. if (onerror) {
  13721. onerror(scene);
  13722. }
  13723. return;
  13724. }
  13725. } catch (e) {
  13726. if (onerror) {
  13727. onerror(scene);
  13728. }
  13729. return;
  13730. }
  13731. if (onsuccess) {
  13732. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13733. onsuccess(meshes, particleSystems, skeletons);
  13734. }
  13735. };
  13736. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13737. importMeshFromData(sceneFilename.substr(5));
  13738. return;
  13739. }
  13740. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13741. importMeshFromData(data);
  13742. }, progressCallBack, database);
  13743. };
  13744. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13745. };
  13746. /**
  13747. * Load a scene
  13748. * @param rootUrl a string that defines the root url for scene and resources
  13749. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13750. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13751. */
  13752. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13753. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13754. };
  13755. /**
  13756. * Append a scene
  13757. * @param rootUrl a string that defines the root url for scene and resources
  13758. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13759. * @param scene is the instance of BABYLON.Scene to append to
  13760. */
  13761. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13762. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13763. var database;
  13764. if (SceneLoader.ShowLoadingScreen) {
  13765. scene.getEngine().displayLoadingUI();
  13766. }
  13767. var loadSceneFromData = function (data) {
  13768. scene.database = database;
  13769. if (!plugin.load(scene, data, rootUrl)) {
  13770. if (onerror) {
  13771. onerror(scene);
  13772. }
  13773. scene.getEngine().hideLoadingUI();
  13774. return;
  13775. }
  13776. if (onsuccess) {
  13777. onsuccess(scene);
  13778. }
  13779. if (SceneLoader.ShowLoadingScreen) {
  13780. scene.executeWhenReady(function () {
  13781. scene.getEngine().hideLoadingUI();
  13782. });
  13783. }
  13784. };
  13785. var manifestChecked = function (success) {
  13786. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13787. };
  13788. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13789. loadSceneFromData(sceneFilename.substr(5));
  13790. return;
  13791. }
  13792. if (rootUrl.indexOf("file:") === -1) {
  13793. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13794. } else {
  13795. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  13796. }
  13797. };
  13798. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  13799. SceneLoader._ShowLoadingScreen = true;
  13800. SceneLoader._registeredPlugins = new Array();
  13801. return SceneLoader;
  13802. })();
  13803. BABYLON.SceneLoader = SceneLoader;
  13804. ;
  13805. })(BABYLON || (BABYLON = {}));
  13806. var BABYLON;
  13807. (function (BABYLON) {
  13808. (function (Internals) {
  13809. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  13810. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  13811. texture.name = parsedTexture.name;
  13812. texture.hasAlpha = parsedTexture.hasAlpha;
  13813. texture.level = parsedTexture.level;
  13814. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13815. return texture;
  13816. };
  13817. var loadTexture = function (rootUrl, parsedTexture, scene) {
  13818. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  13819. return null;
  13820. }
  13821. if (parsedTexture.isCube) {
  13822. return loadCubeTexture(rootUrl, parsedTexture, scene);
  13823. }
  13824. var texture;
  13825. if (parsedTexture.mirrorPlane) {
  13826. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13827. texture._waitingRenderList = parsedTexture.renderList;
  13828. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  13829. } else if (parsedTexture.isRenderTarget) {
  13830. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13831. texture._waitingRenderList = parsedTexture.renderList;
  13832. } else {
  13833. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  13834. }
  13835. texture.name = parsedTexture.name;
  13836. texture.hasAlpha = parsedTexture.hasAlpha;
  13837. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  13838. texture.level = parsedTexture.level;
  13839. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  13840. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13841. texture.uOffset = parsedTexture.uOffset;
  13842. texture.vOffset = parsedTexture.vOffset;
  13843. texture.uScale = parsedTexture.uScale;
  13844. texture.vScale = parsedTexture.vScale;
  13845. texture.uAng = parsedTexture.uAng;
  13846. texture.vAng = parsedTexture.vAng;
  13847. texture.wAng = parsedTexture.wAng;
  13848. texture.wrapU = parsedTexture.wrapU;
  13849. texture.wrapV = parsedTexture.wrapV;
  13850. if (parsedTexture.animations) {
  13851. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  13852. var parsedAnimation = parsedTexture.animations[animationIndex];
  13853. texture.animations.push(parseAnimation(parsedAnimation));
  13854. }
  13855. }
  13856. return texture;
  13857. };
  13858. var parseSkeleton = function (parsedSkeleton, scene) {
  13859. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  13860. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  13861. var parsedBone = parsedSkeleton.bones[index];
  13862. var parentBone = null;
  13863. if (parsedBone.parentBoneIndex > -1) {
  13864. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  13865. }
  13866. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  13867. if (parsedBone.animation) {
  13868. bone.animations.push(parseAnimation(parsedBone.animation));
  13869. }
  13870. }
  13871. return skeleton;
  13872. };
  13873. var parseFresnelParameters = function (parsedFresnelParameters) {
  13874. var fresnelParameters = new BABYLON.FresnelParameters();
  13875. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  13876. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  13877. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  13878. return fresnelParameters;
  13879. };
  13880. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  13881. var material;
  13882. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  13883. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  13884. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  13885. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  13886. material.specularPower = parsedMaterial.specularPower;
  13887. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  13888. material.alpha = parsedMaterial.alpha;
  13889. material.id = parsedMaterial.id;
  13890. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  13891. material.backFaceCulling = parsedMaterial.backFaceCulling;
  13892. material.wireframe = parsedMaterial.wireframe;
  13893. if (parsedMaterial.diffuseTexture) {
  13894. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  13895. }
  13896. if (parsedMaterial.diffuseFresnelParameters) {
  13897. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  13898. }
  13899. if (parsedMaterial.ambientTexture) {
  13900. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  13901. }
  13902. if (parsedMaterial.opacityTexture) {
  13903. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  13904. }
  13905. if (parsedMaterial.opacityFresnelParameters) {
  13906. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  13907. }
  13908. if (parsedMaterial.reflectionTexture) {
  13909. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  13910. }
  13911. if (parsedMaterial.reflectionFresnelParameters) {
  13912. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  13913. }
  13914. if (parsedMaterial.emissiveTexture) {
  13915. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  13916. }
  13917. if (parsedMaterial.specularTexture) {
  13918. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  13919. }
  13920. if (parsedMaterial.bumpTexture) {
  13921. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  13922. }
  13923. return material;
  13924. };
  13925. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  13926. for (var index = 0; index < parsedData.materials.length; index++) {
  13927. var parsedMaterial = parsedData.materials[index];
  13928. if (parsedMaterial.id === id) {
  13929. return parseMaterial(parsedMaterial, scene, rootUrl);
  13930. }
  13931. }
  13932. return null;
  13933. };
  13934. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  13935. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  13936. multiMaterial.id = parsedMultiMaterial.id;
  13937. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  13938. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  13939. var subMatId = parsedMultiMaterial.materials[matIndex];
  13940. if (subMatId) {
  13941. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  13942. } else {
  13943. multiMaterial.subMaterials.push(null);
  13944. }
  13945. }
  13946. return multiMaterial;
  13947. };
  13948. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  13949. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  13950. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  13951. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  13952. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  13953. var parsedFlare = parsedLensFlareSystem.flares[index];
  13954. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  13955. }
  13956. return lensFlareSystem;
  13957. };
  13958. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  13959. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  13960. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  13961. if (parsedParticleSystem.textureName) {
  13962. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  13963. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  13964. }
  13965. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  13966. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  13967. particleSystem.minSize = parsedParticleSystem.minSize;
  13968. particleSystem.maxSize = parsedParticleSystem.maxSize;
  13969. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  13970. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  13971. particleSystem.emitter = emitter;
  13972. particleSystem.emitRate = parsedParticleSystem.emitRate;
  13973. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  13974. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  13975. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  13976. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  13977. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  13978. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  13979. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  13980. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  13981. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  13982. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  13983. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  13984. particleSystem.blendMode = parsedParticleSystem.blendMode;
  13985. particleSystem.start();
  13986. return particleSystem;
  13987. };
  13988. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  13989. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  13990. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  13991. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  13992. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  13993. shadowGenerator.getShadowMap().renderList.push(mesh);
  13994. }
  13995. if (parsedShadowGenerator.usePoissonSampling) {
  13996. shadowGenerator.usePoissonSampling = true;
  13997. } else {
  13998. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  13999. }
  14000. return shadowGenerator;
  14001. };
  14002. var parseAnimation = function (parsedAnimation) {
  14003. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14004. var dataType = parsedAnimation.dataType;
  14005. var keys = [];
  14006. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14007. var key = parsedAnimation.keys[index];
  14008. var data;
  14009. switch (dataType) {
  14010. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14011. data = key.values[0];
  14012. break;
  14013. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14014. data = BABYLON.Quaternion.FromArray(key.values);
  14015. break;
  14016. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14017. data = BABYLON.Matrix.FromArray(key.values);
  14018. break;
  14019. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14020. default:
  14021. data = BABYLON.Vector3.FromArray(key.values);
  14022. break;
  14023. }
  14024. keys.push({
  14025. frame: key.frame,
  14026. value: data
  14027. });
  14028. }
  14029. animation.setKeys(keys);
  14030. return animation;
  14031. };
  14032. var parseLight = function (parsedLight, scene) {
  14033. var light;
  14034. switch (parsedLight.type) {
  14035. case 0:
  14036. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14037. break;
  14038. case 1:
  14039. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14040. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14041. break;
  14042. case 2:
  14043. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14044. break;
  14045. case 3:
  14046. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14047. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14048. break;
  14049. }
  14050. light.id = parsedLight.id;
  14051. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14052. if (parsedLight.intensity !== undefined) {
  14053. light.intensity = parsedLight.intensity;
  14054. }
  14055. if (parsedLight.range) {
  14056. light.range = parsedLight.range;
  14057. }
  14058. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14059. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14060. if (parsedLight.excludedMeshesIds) {
  14061. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14062. }
  14063. if (parsedLight.includedOnlyMeshesIds) {
  14064. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14065. }
  14066. if (parsedLight.animations) {
  14067. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14068. var parsedAnimation = parsedLight.animations[animationIndex];
  14069. light.animations.push(parseAnimation(parsedAnimation));
  14070. }
  14071. }
  14072. if (parsedLight.autoAnimate) {
  14073. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14074. }
  14075. };
  14076. var parseCamera = function (parsedCamera, scene) {
  14077. var camera = new BABYLON.FreeCamera(parsedCamera.name, BABYLON.Vector3.FromArray(parsedCamera.position), scene);
  14078. camera.id = parsedCamera.id;
  14079. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14080. if (parsedCamera.parentId) {
  14081. camera._waitingParentId = parsedCamera.parentId;
  14082. }
  14083. if (parsedCamera.target) {
  14084. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14085. } else {
  14086. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14087. }
  14088. if (parsedCamera.lockedTargetId) {
  14089. camera._waitingLockedTargetId = parsedCamera.lockedTargetId;
  14090. }
  14091. camera.fov = parsedCamera.fov;
  14092. camera.minZ = parsedCamera.minZ;
  14093. camera.maxZ = parsedCamera.maxZ;
  14094. camera.speed = parsedCamera.speed;
  14095. camera.inertia = parsedCamera.inertia;
  14096. camera.checkCollisions = parsedCamera.checkCollisions;
  14097. camera.applyGravity = parsedCamera.applyGravity;
  14098. if (parsedCamera.ellipsoid) {
  14099. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14100. }
  14101. if (parsedCamera.animations) {
  14102. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14103. var parsedAnimation = parsedCamera.animations[animationIndex];
  14104. camera.animations.push(parseAnimation(parsedAnimation));
  14105. }
  14106. }
  14107. if (parsedCamera.autoAnimate) {
  14108. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14109. }
  14110. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14111. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14112. } else {
  14113. camera.layerMask = 0xFFFFFFFF;
  14114. }
  14115. return camera;
  14116. };
  14117. var parseGeometry = function (parsedGeometry, scene) {
  14118. var id = parsedGeometry.id;
  14119. return scene.getGeometryByID(id);
  14120. };
  14121. var parseBox = function (parsedBox, scene) {
  14122. if (parseGeometry(parsedBox, scene)) {
  14123. return null;
  14124. }
  14125. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14126. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14127. scene.pushGeometry(box, true);
  14128. return box;
  14129. };
  14130. var parseSphere = function (parsedSphere, scene) {
  14131. if (parseGeometry(parsedSphere, scene)) {
  14132. return null;
  14133. }
  14134. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14135. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14136. scene.pushGeometry(sphere, true);
  14137. return sphere;
  14138. };
  14139. var parseCylinder = function (parsedCylinder, scene) {
  14140. if (parseGeometry(parsedCylinder, scene)) {
  14141. return null;
  14142. }
  14143. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14144. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14145. scene.pushGeometry(cylinder, true);
  14146. return cylinder;
  14147. };
  14148. var parseTorus = function (parsedTorus, scene) {
  14149. if (parseGeometry(parsedTorus, scene)) {
  14150. return null;
  14151. }
  14152. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14153. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14154. scene.pushGeometry(torus, true);
  14155. return torus;
  14156. };
  14157. var parseGround = function (parsedGround, scene) {
  14158. if (parseGeometry(parsedGround, scene)) {
  14159. return null;
  14160. }
  14161. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14162. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14163. scene.pushGeometry(ground, true);
  14164. return ground;
  14165. };
  14166. var parsePlane = function (parsedPlane, scene) {
  14167. if (parseGeometry(parsedPlane, scene)) {
  14168. return null;
  14169. }
  14170. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14171. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14172. scene.pushGeometry(plane, true);
  14173. return plane;
  14174. };
  14175. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14176. if (parseGeometry(parsedTorusKnot, scene)) {
  14177. return null;
  14178. }
  14179. 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);
  14180. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14181. scene.pushGeometry(torusKnot, true);
  14182. return torusKnot;
  14183. };
  14184. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14185. if (parseGeometry(parsedVertexData, scene)) {
  14186. return null;
  14187. }
  14188. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14189. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14190. if (parsedVertexData.delayLoadingFile) {
  14191. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14192. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14193. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14194. geometry._delayInfo = [];
  14195. if (parsedVertexData.hasUVs) {
  14196. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14197. }
  14198. if (parsedVertexData.hasUVs2) {
  14199. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14200. }
  14201. if (parsedVertexData.hasColors) {
  14202. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14203. }
  14204. if (parsedVertexData.hasMatricesIndices) {
  14205. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14206. }
  14207. if (parsedVertexData.hasMatricesWeights) {
  14208. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14209. }
  14210. geometry._delayLoadingFunction = importVertexData;
  14211. } else {
  14212. importVertexData(parsedVertexData, geometry);
  14213. }
  14214. scene.pushGeometry(geometry, true);
  14215. return geometry;
  14216. };
  14217. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14218. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14219. mesh.id = parsedMesh.id;
  14220. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14221. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14222. if (parsedMesh.rotationQuaternion) {
  14223. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14224. } else if (parsedMesh.rotation) {
  14225. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14226. }
  14227. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14228. if (parsedMesh.localMatrix) {
  14229. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14230. } else if (parsedMesh.pivotMatrix) {
  14231. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14232. }
  14233. mesh.setEnabled(parsedMesh.isEnabled);
  14234. mesh.isVisible = parsedMesh.isVisible;
  14235. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14236. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14237. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14238. if (parsedMesh.pickable !== undefined) {
  14239. mesh.isPickable = parsedMesh.pickable;
  14240. }
  14241. mesh.receiveShadows = parsedMesh.receiveShadows;
  14242. mesh.billboardMode = parsedMesh.billboardMode;
  14243. if (parsedMesh.visibility !== undefined) {
  14244. mesh.visibility = parsedMesh.visibility;
  14245. }
  14246. mesh.checkCollisions = parsedMesh.checkCollisions;
  14247. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14248. if (parsedMesh.parentId) {
  14249. mesh.parent = scene.getLastEntryByID(parsedMesh.parentId);
  14250. }
  14251. if (parsedMesh.delayLoadingFile) {
  14252. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14253. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14254. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14255. mesh._delayInfo = [];
  14256. if (parsedMesh.hasUVs) {
  14257. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14258. }
  14259. if (parsedMesh.hasUVs2) {
  14260. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14261. }
  14262. if (parsedMesh.hasColors) {
  14263. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14264. }
  14265. if (parsedMesh.hasMatricesIndices) {
  14266. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14267. }
  14268. if (parsedMesh.hasMatricesWeights) {
  14269. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14270. }
  14271. mesh._delayLoadingFunction = importGeometry;
  14272. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14273. mesh._checkDelayState();
  14274. }
  14275. } else {
  14276. importGeometry(parsedMesh, mesh);
  14277. }
  14278. if (parsedMesh.materialId) {
  14279. mesh.setMaterialByID(parsedMesh.materialId);
  14280. } else {
  14281. mesh.material = null;
  14282. }
  14283. if (parsedMesh.skeletonId > -1) {
  14284. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14285. }
  14286. if (parsedMesh.physicsImpostor) {
  14287. if (!scene.isPhysicsEnabled()) {
  14288. scene.enablePhysics();
  14289. }
  14290. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14291. }
  14292. if (parsedMesh.animations) {
  14293. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14294. var parsedAnimation = parsedMesh.animations[animationIndex];
  14295. mesh.animations.push(parseAnimation(parsedAnimation));
  14296. }
  14297. }
  14298. if (parsedMesh.autoAnimate) {
  14299. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14300. }
  14301. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14302. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14303. } else {
  14304. mesh.layerMask = 0xFFFFFFFF;
  14305. }
  14306. if (parsedMesh.instances) {
  14307. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14308. var parsedInstance = parsedMesh.instances[index];
  14309. var instance = mesh.createInstance(parsedInstance.name);
  14310. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14311. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14312. if (parsedInstance.rotationQuaternion) {
  14313. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14314. } else if (parsedInstance.rotation) {
  14315. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14316. }
  14317. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14318. instance.checkCollisions = mesh.checkCollisions;
  14319. if (parsedMesh.animations) {
  14320. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14321. parsedAnimation = parsedMesh.animations[animationIndex];
  14322. instance.animations.push(parseAnimation(parsedAnimation));
  14323. }
  14324. }
  14325. }
  14326. }
  14327. return mesh;
  14328. };
  14329. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14330. names = (names instanceof Array) ? names : [names];
  14331. for (var i in names) {
  14332. if (mesh.name === names[i]) {
  14333. hierarchyIds.push(mesh.id);
  14334. return true;
  14335. }
  14336. }
  14337. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14338. hierarchyIds.push(mesh.id);
  14339. return true;
  14340. }
  14341. return false;
  14342. };
  14343. var importVertexData = function (parsedVertexData, geometry) {
  14344. var vertexData = new BABYLON.VertexData();
  14345. var positions = parsedVertexData.positions;
  14346. if (positions) {
  14347. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14348. }
  14349. var normals = parsedVertexData.normals;
  14350. if (normals) {
  14351. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14352. }
  14353. var uvs = parsedVertexData.uvs;
  14354. if (uvs) {
  14355. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14356. }
  14357. var uv2s = parsedVertexData.uv2s;
  14358. if (uv2s) {
  14359. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14360. }
  14361. var colors = parsedVertexData.colors;
  14362. if (colors) {
  14363. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14364. }
  14365. var matricesIndices = parsedVertexData.matricesIndices;
  14366. if (matricesIndices) {
  14367. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14368. }
  14369. var matricesWeights = parsedVertexData.matricesWeights;
  14370. if (matricesWeights) {
  14371. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14372. }
  14373. var indices = parsedVertexData.indices;
  14374. if (indices) {
  14375. vertexData.indices = indices;
  14376. }
  14377. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14378. };
  14379. var importGeometry = function (parsedGeometry, mesh) {
  14380. var scene = mesh.getScene();
  14381. var geometryId = parsedGeometry.geometryId;
  14382. if (geometryId) {
  14383. var geometry = scene.getGeometryByID(geometryId);
  14384. if (geometry) {
  14385. geometry.applyToMesh(mesh);
  14386. }
  14387. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14388. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14389. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14390. if (parsedGeometry.uvs) {
  14391. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14392. }
  14393. if (parsedGeometry.uvs2) {
  14394. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14395. }
  14396. if (parsedGeometry.colors) {
  14397. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14398. }
  14399. if (parsedGeometry.matricesIndices) {
  14400. if (!parsedGeometry.matricesIndices._isExpanded) {
  14401. var floatIndices = [];
  14402. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14403. var matricesIndex = parsedGeometry.matricesIndices[i];
  14404. floatIndices.push(matricesIndex & 0x000000FF);
  14405. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14406. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14407. floatIndices.push(matricesIndex >> 24);
  14408. }
  14409. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14410. } else {
  14411. delete parsedGeometry.matricesIndices._isExpanded;
  14412. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14413. }
  14414. }
  14415. if (parsedGeometry.matricesWeights) {
  14416. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14417. }
  14418. mesh.setIndices(parsedGeometry.indices);
  14419. }
  14420. if (parsedGeometry.subMeshes) {
  14421. mesh.subMeshes = [];
  14422. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14423. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14424. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14425. }
  14426. }
  14427. if (mesh._shouldGenerateFlatShading) {
  14428. mesh.convertToFlatShadedMesh();
  14429. delete mesh._shouldGenerateFlatShading;
  14430. }
  14431. mesh.computeWorldMatrix(true);
  14432. if (scene._selectionOctree) {
  14433. scene._selectionOctree.addMesh(mesh);
  14434. }
  14435. };
  14436. BABYLON.SceneLoader.RegisterPlugin({
  14437. extensions: ".babylon",
  14438. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14439. var parsedData = JSON.parse(data);
  14440. var loadedSkeletonsIds = [];
  14441. var loadedMaterialsIds = [];
  14442. var hierarchyIds = [];
  14443. for (var index = 0; index < parsedData.meshes.length; index++) {
  14444. var parsedMesh = parsedData.meshes[index];
  14445. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14446. if (meshesNames instanceof Array) {
  14447. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14448. }
  14449. if (parsedMesh.materialId) {
  14450. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14451. if (!materialFound) {
  14452. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14453. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14454. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14455. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14456. var subMatId = parsedMultiMaterial.materials[matIndex];
  14457. loadedMaterialsIds.push(subMatId);
  14458. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14459. }
  14460. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14461. parseMultiMaterial(parsedMultiMaterial, scene);
  14462. materialFound = true;
  14463. break;
  14464. }
  14465. }
  14466. }
  14467. if (!materialFound) {
  14468. loadedMaterialsIds.push(parsedMesh.materialId);
  14469. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14470. }
  14471. }
  14472. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14473. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14474. if (!skeletonAlreadyLoaded) {
  14475. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14476. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14477. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14478. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14479. loadedSkeletonsIds.push(parsedSkeleton.id);
  14480. }
  14481. }
  14482. }
  14483. }
  14484. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14485. meshes.push(mesh);
  14486. }
  14487. }
  14488. if (parsedData.particleSystems) {
  14489. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14490. var parsedParticleSystem = parsedData.particleSystems[index];
  14491. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14492. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14493. }
  14494. }
  14495. }
  14496. return true;
  14497. },
  14498. load: function (scene, data, rootUrl) {
  14499. var parsedData = JSON.parse(data);
  14500. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14501. scene.autoClear = parsedData.autoClear;
  14502. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14503. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14504. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14505. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14506. scene.fogMode = parsedData.fogMode;
  14507. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14508. scene.fogStart = parsedData.fogStart;
  14509. scene.fogEnd = parsedData.fogEnd;
  14510. scene.fogDensity = parsedData.fogDensity;
  14511. }
  14512. for (var index = 0; index < parsedData.lights.length; index++) {
  14513. var parsedLight = parsedData.lights[index];
  14514. parseLight(parsedLight, scene);
  14515. }
  14516. for (index = 0; index < parsedData.cameras.length; index++) {
  14517. var parsedCamera = parsedData.cameras[index];
  14518. parseCamera(parsedCamera, scene);
  14519. }
  14520. if (parsedData.activeCameraID) {
  14521. scene.setActiveCameraByID(parsedData.activeCameraID);
  14522. }
  14523. if (parsedData.materials) {
  14524. for (index = 0; index < parsedData.materials.length; index++) {
  14525. var parsedMaterial = parsedData.materials[index];
  14526. parseMaterial(parsedMaterial, scene, rootUrl);
  14527. }
  14528. }
  14529. if (parsedData.multiMaterials) {
  14530. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14531. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14532. parseMultiMaterial(parsedMultiMaterial, scene);
  14533. }
  14534. }
  14535. if (parsedData.skeletons) {
  14536. for (index = 0; index < parsedData.skeletons.length; index++) {
  14537. var parsedSkeleton = parsedData.skeletons[index];
  14538. parseSkeleton(parsedSkeleton, scene);
  14539. }
  14540. }
  14541. var geometries = parsedData.geometries;
  14542. if (geometries) {
  14543. var boxes = geometries.boxes;
  14544. if (boxes) {
  14545. for (index = 0; index < boxes.length; index++) {
  14546. var parsedBox = boxes[index];
  14547. parseBox(parsedBox, scene);
  14548. }
  14549. }
  14550. var spheres = geometries.spheres;
  14551. if (spheres) {
  14552. for (index = 0; index < spheres.length; index++) {
  14553. var parsedSphere = spheres[index];
  14554. parseSphere(parsedSphere, scene);
  14555. }
  14556. }
  14557. var cylinders = geometries.cylinders;
  14558. if (cylinders) {
  14559. for (index = 0; index < cylinders.length; index++) {
  14560. var parsedCylinder = cylinders[index];
  14561. parseCylinder(parsedCylinder, scene);
  14562. }
  14563. }
  14564. var toruses = geometries.toruses;
  14565. if (toruses) {
  14566. for (index = 0; index < toruses.length; index++) {
  14567. var parsedTorus = toruses[index];
  14568. parseTorus(parsedTorus, scene);
  14569. }
  14570. }
  14571. var grounds = geometries.grounds;
  14572. if (grounds) {
  14573. for (index = 0; index < grounds.length; index++) {
  14574. var parsedGround = grounds[index];
  14575. parseGround(parsedGround, scene);
  14576. }
  14577. }
  14578. var planes = geometries.planes;
  14579. if (planes) {
  14580. for (index = 0; index < planes.length; index++) {
  14581. var parsedPlane = planes[index];
  14582. parsePlane(parsedPlane, scene);
  14583. }
  14584. }
  14585. var torusKnots = geometries.torusKnots;
  14586. if (torusKnots) {
  14587. for (index = 0; index < torusKnots.length; index++) {
  14588. var parsedTorusKnot = torusKnots[index];
  14589. parseTorusKnot(parsedTorusKnot, scene);
  14590. }
  14591. }
  14592. var vertexData = geometries.vertexData;
  14593. if (vertexData) {
  14594. for (index = 0; index < vertexData.length; index++) {
  14595. var parsedVertexData = vertexData[index];
  14596. parseVertexData(parsedVertexData, scene, rootUrl);
  14597. }
  14598. }
  14599. }
  14600. for (index = 0; index < parsedData.meshes.length; index++) {
  14601. var parsedMesh = parsedData.meshes[index];
  14602. parseMesh(parsedMesh, scene, rootUrl);
  14603. }
  14604. for (index = 0; index < scene.cameras.length; index++) {
  14605. var camera = scene.cameras[index];
  14606. if (camera._waitingParentId) {
  14607. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14608. delete camera._waitingParentId;
  14609. }
  14610. if (camera instanceof BABYLON.FreeCamera) {
  14611. var freecamera = camera;
  14612. if (freecamera._waitingLockedTargetId) {
  14613. freecamera.lockedTarget = scene.getLastEntryByID(freecamera._waitingLockedTargetId);
  14614. delete freecamera._waitingLockedTargetId;
  14615. }
  14616. }
  14617. }
  14618. if (parsedData.particleSystems) {
  14619. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14620. var parsedParticleSystem = parsedData.particleSystems[index];
  14621. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14622. }
  14623. }
  14624. if (parsedData.lensFlareSystems) {
  14625. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14626. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14627. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14628. }
  14629. }
  14630. if (parsedData.shadowGenerators) {
  14631. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14632. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14633. parseShadowGenerator(parsedShadowGenerator, scene);
  14634. }
  14635. }
  14636. return true;
  14637. }
  14638. });
  14639. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14640. var Internals = BABYLON.Internals;
  14641. })(BABYLON || (BABYLON = {}));
  14642. var BABYLON;
  14643. (function (BABYLON) {
  14644. var currentCSGMeshId = 0;
  14645. var Vertex = (function () {
  14646. function Vertex(pos, normal, uv) {
  14647. this.pos = pos;
  14648. this.normal = normal;
  14649. this.uv = uv;
  14650. }
  14651. Vertex.prototype.clone = function () {
  14652. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14653. };
  14654. Vertex.prototype.flip = function () {
  14655. this.normal = this.normal.scale(-1);
  14656. };
  14657. Vertex.prototype.interpolate = function (other, t) {
  14658. 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));
  14659. };
  14660. return Vertex;
  14661. })();
  14662. var Plane = (function () {
  14663. function Plane(normal, w) {
  14664. this.normal = normal;
  14665. this.w = w;
  14666. }
  14667. Plane.FromPoints = function (a, b, c) {
  14668. var v0 = c.subtract(a);
  14669. var v1 = b.subtract(a);
  14670. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14671. return null;
  14672. }
  14673. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14674. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14675. };
  14676. Plane.prototype.clone = function () {
  14677. return new Plane(this.normal.clone(), this.w);
  14678. };
  14679. Plane.prototype.flip = function () {
  14680. this.normal.scaleInPlace(-1);
  14681. this.w = -this.w;
  14682. };
  14683. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14684. var COPLANAR = 0;
  14685. var FRONT = 1;
  14686. var BACK = 2;
  14687. var SPANNING = 3;
  14688. var polygonType = 0;
  14689. var types = [];
  14690. for (var i = 0; i < polygon.vertices.length; i++) {
  14691. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  14692. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  14693. polygonType |= type;
  14694. types.push(type);
  14695. }
  14696. switch (polygonType) {
  14697. case COPLANAR:
  14698. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  14699. break;
  14700. case FRONT:
  14701. front.push(polygon);
  14702. break;
  14703. case BACK:
  14704. back.push(polygon);
  14705. break;
  14706. case SPANNING:
  14707. var f = [], b = [];
  14708. for (i = 0; i < polygon.vertices.length; i++) {
  14709. var j = (i + 1) % polygon.vertices.length;
  14710. var ti = types[i], tj = types[j];
  14711. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  14712. if (ti != BACK)
  14713. f.push(vi);
  14714. if (ti != FRONT)
  14715. b.push(ti != BACK ? vi.clone() : vi);
  14716. if ((ti | tj) == SPANNING) {
  14717. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  14718. var v = vi.interpolate(vj, t);
  14719. f.push(v);
  14720. b.push(v.clone());
  14721. }
  14722. }
  14723. if (f.length >= 3) {
  14724. var poly = new Polygon(f, polygon.shared);
  14725. if (poly.plane)
  14726. front.push(poly);
  14727. }
  14728. if (b.length >= 3) {
  14729. poly = new Polygon(b, polygon.shared);
  14730. if (poly.plane)
  14731. back.push(poly);
  14732. }
  14733. break;
  14734. }
  14735. };
  14736. Plane.EPSILON = 1e-5;
  14737. return Plane;
  14738. })();
  14739. var Polygon = (function () {
  14740. function Polygon(vertices, shared) {
  14741. this.vertices = vertices;
  14742. this.shared = shared;
  14743. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  14744. }
  14745. Polygon.prototype.clone = function () {
  14746. var vertices = this.vertices.map(function (v) {
  14747. return v.clone();
  14748. });
  14749. return new Polygon(vertices, this.shared);
  14750. };
  14751. Polygon.prototype.flip = function () {
  14752. this.vertices.reverse().map(function (v) {
  14753. v.flip();
  14754. });
  14755. this.plane.flip();
  14756. };
  14757. return Polygon;
  14758. })();
  14759. var Node = (function () {
  14760. function Node(polygons) {
  14761. this.plane = null;
  14762. this.front = null;
  14763. this.back = null;
  14764. this.polygons = [];
  14765. if (polygons) {
  14766. this.build(polygons);
  14767. }
  14768. }
  14769. Node.prototype.clone = function () {
  14770. var node = new Node();
  14771. node.plane = this.plane && this.plane.clone();
  14772. node.front = this.front && this.front.clone();
  14773. node.back = this.back && this.back.clone();
  14774. node.polygons = this.polygons.map(function (p) {
  14775. return p.clone();
  14776. });
  14777. return node;
  14778. };
  14779. Node.prototype.invert = function () {
  14780. for (var i = 0; i < this.polygons.length; i++) {
  14781. this.polygons[i].flip();
  14782. }
  14783. if (this.plane) {
  14784. this.plane.flip();
  14785. }
  14786. if (this.front) {
  14787. this.front.invert();
  14788. }
  14789. if (this.back) {
  14790. this.back.invert();
  14791. }
  14792. var temp = this.front;
  14793. this.front = this.back;
  14794. this.back = temp;
  14795. };
  14796. Node.prototype.clipPolygons = function (polygons) {
  14797. if (!this.plane)
  14798. return polygons.slice();
  14799. var front = [], back = [];
  14800. for (var i = 0; i < polygons.length; i++) {
  14801. this.plane.splitPolygon(polygons[i], front, back, front, back);
  14802. }
  14803. if (this.front) {
  14804. front = this.front.clipPolygons(front);
  14805. }
  14806. if (this.back) {
  14807. back = this.back.clipPolygons(back);
  14808. } else {
  14809. back = [];
  14810. }
  14811. return front.concat(back);
  14812. };
  14813. Node.prototype.clipTo = function (bsp) {
  14814. this.polygons = bsp.clipPolygons(this.polygons);
  14815. if (this.front)
  14816. this.front.clipTo(bsp);
  14817. if (this.back)
  14818. this.back.clipTo(bsp);
  14819. };
  14820. Node.prototype.allPolygons = function () {
  14821. var polygons = this.polygons.slice();
  14822. if (this.front)
  14823. polygons = polygons.concat(this.front.allPolygons());
  14824. if (this.back)
  14825. polygons = polygons.concat(this.back.allPolygons());
  14826. return polygons;
  14827. };
  14828. Node.prototype.build = function (polygons) {
  14829. if (!polygons.length)
  14830. return;
  14831. if (!this.plane)
  14832. this.plane = polygons[0].plane.clone();
  14833. var front = [], back = [];
  14834. for (var i = 0; i < polygons.length; i++) {
  14835. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  14836. }
  14837. if (front.length) {
  14838. if (!this.front)
  14839. this.front = new Node();
  14840. this.front.build(front);
  14841. }
  14842. if (back.length) {
  14843. if (!this.back)
  14844. this.back = new Node();
  14845. this.back.build(back);
  14846. }
  14847. };
  14848. return Node;
  14849. })();
  14850. var CSG = (function () {
  14851. function CSG() {
  14852. this.polygons = new Array();
  14853. }
  14854. CSG.FromMesh = function (mesh) {
  14855. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  14856. if (mesh instanceof BABYLON.Mesh) {
  14857. mesh.computeWorldMatrix(true);
  14858. var matrix = mesh.getWorldMatrix();
  14859. var meshPosition = mesh.position.clone();
  14860. var meshRotation = mesh.rotation.clone();
  14861. var meshScaling = mesh.scaling.clone();
  14862. } else {
  14863. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  14864. }
  14865. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14866. var subMeshes = mesh.subMeshes;
  14867. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  14868. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  14869. vertices = [];
  14870. for (var j = 0; j < 3; j++) {
  14871. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  14872. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  14873. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  14874. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  14875. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  14876. vertex = new Vertex(position, normal, uv);
  14877. vertices.push(vertex);
  14878. }
  14879. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  14880. if (polygon.plane)
  14881. polygons.push(polygon);
  14882. }
  14883. }
  14884. var csg = CSG.FromPolygons(polygons);
  14885. csg.matrix = matrix;
  14886. csg.position = meshPosition;
  14887. csg.rotation = meshRotation;
  14888. csg.scaling = meshScaling;
  14889. currentCSGMeshId++;
  14890. return csg;
  14891. };
  14892. CSG.FromPolygons = function (polygons) {
  14893. var csg = new BABYLON.CSG();
  14894. csg.polygons = polygons;
  14895. return csg;
  14896. };
  14897. CSG.prototype.clone = function () {
  14898. var csg = new BABYLON.CSG();
  14899. csg.polygons = this.polygons.map(function (p) {
  14900. return p.clone();
  14901. });
  14902. csg.copyTransformAttributes(this);
  14903. return csg;
  14904. };
  14905. CSG.prototype.toPolygons = function () {
  14906. return this.polygons;
  14907. };
  14908. CSG.prototype.union = function (csg) {
  14909. var a = new Node(this.clone().polygons);
  14910. var b = new Node(csg.clone().polygons);
  14911. a.clipTo(b);
  14912. b.clipTo(a);
  14913. b.invert();
  14914. b.clipTo(a);
  14915. b.invert();
  14916. a.build(b.allPolygons());
  14917. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  14918. };
  14919. CSG.prototype.unionInPlace = function (csg) {
  14920. var a = new Node(this.polygons);
  14921. var b = new Node(csg.polygons);
  14922. a.clipTo(b);
  14923. b.clipTo(a);
  14924. b.invert();
  14925. b.clipTo(a);
  14926. b.invert();
  14927. a.build(b.allPolygons());
  14928. this.polygons = a.allPolygons();
  14929. };
  14930. CSG.prototype.subtract = function (csg) {
  14931. var a = new Node(this.clone().polygons);
  14932. var b = new Node(csg.clone().polygons);
  14933. a.invert();
  14934. a.clipTo(b);
  14935. b.clipTo(a);
  14936. b.invert();
  14937. b.clipTo(a);
  14938. b.invert();
  14939. a.build(b.allPolygons());
  14940. a.invert();
  14941. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  14942. };
  14943. CSG.prototype.subtractInPlace = function (csg) {
  14944. var a = new Node(this.polygons);
  14945. var b = new Node(csg.polygons);
  14946. a.invert();
  14947. a.clipTo(b);
  14948. b.clipTo(a);
  14949. b.invert();
  14950. b.clipTo(a);
  14951. b.invert();
  14952. a.build(b.allPolygons());
  14953. a.invert();
  14954. this.polygons = a.allPolygons();
  14955. };
  14956. CSG.prototype.intersect = function (csg) {
  14957. var a = new Node(this.clone().polygons);
  14958. var b = new Node(csg.clone().polygons);
  14959. a.invert();
  14960. b.clipTo(a);
  14961. b.invert();
  14962. a.clipTo(b);
  14963. b.clipTo(a);
  14964. a.build(b.allPolygons());
  14965. a.invert();
  14966. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  14967. };
  14968. CSG.prototype.intersectInPlace = function (csg) {
  14969. var a = new Node(this.polygons);
  14970. var b = new Node(csg.polygons);
  14971. a.invert();
  14972. b.clipTo(a);
  14973. b.invert();
  14974. a.clipTo(b);
  14975. b.clipTo(a);
  14976. a.build(b.allPolygons());
  14977. a.invert();
  14978. this.polygons = a.allPolygons();
  14979. };
  14980. CSG.prototype.inverse = function () {
  14981. var csg = this.clone();
  14982. csg.inverseInPlace();
  14983. return csg;
  14984. };
  14985. CSG.prototype.inverseInPlace = function () {
  14986. this.polygons.map(function (p) {
  14987. p.flip();
  14988. });
  14989. };
  14990. CSG.prototype.copyTransformAttributes = function (csg) {
  14991. this.matrix = csg.matrix;
  14992. this.position = csg.position;
  14993. this.rotation = csg.rotation;
  14994. this.scaling = csg.scaling;
  14995. return this;
  14996. };
  14997. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  14998. var matrix = this.matrix.clone();
  14999. matrix.invert();
  15000. 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;
  15001. if (keepSubMeshes) {
  15002. polygons.sort(function (a, b) {
  15003. if (a.shared.meshId === b.shared.meshId) {
  15004. return a.shared.subMeshId - b.shared.subMeshId;
  15005. } else {
  15006. return a.shared.meshId - b.shared.meshId;
  15007. }
  15008. });
  15009. }
  15010. for (var i = 0, il = polygons.length; i < il; i++) {
  15011. polygon = polygons[i];
  15012. if (!subMesh_dict[polygon.shared.meshId]) {
  15013. subMesh_dict[polygon.shared.meshId] = {};
  15014. }
  15015. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15016. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15017. indexStart: +Infinity,
  15018. indexEnd: -Infinity,
  15019. materialIndex: polygon.shared.materialIndex
  15020. };
  15021. }
  15022. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15023. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15024. polygonIndices[0] = 0;
  15025. polygonIndices[1] = j - 1;
  15026. polygonIndices[2] = j;
  15027. for (var k = 0; k < 3; k++) {
  15028. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15029. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15030. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15031. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15032. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15033. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15034. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  15035. vertices.push(vertex.x, vertex.y, vertex.z);
  15036. uvs.push(uv.x, uv.y);
  15037. normals.push(normal.x, normal.y, normal.z);
  15038. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15039. }
  15040. indices.push(vertex_idx);
  15041. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15042. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15043. currentIndex++;
  15044. }
  15045. }
  15046. }
  15047. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15048. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15049. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15050. mesh.setIndices(indices);
  15051. if (keepSubMeshes) {
  15052. var materialIndexOffset = 0, materialMaxIndex;
  15053. mesh.subMeshes.length = 0;
  15054. for (var m in subMesh_dict) {
  15055. materialMaxIndex = -1;
  15056. for (var sm in subMesh_dict[m]) {
  15057. subMesh_obj = subMesh_dict[m][sm];
  15058. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15059. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15060. }
  15061. materialIndexOffset += ++materialMaxIndex;
  15062. }
  15063. }
  15064. return mesh;
  15065. };
  15066. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15067. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15068. mesh.material = material;
  15069. mesh.position.copyFrom(this.position);
  15070. mesh.rotation.copyFrom(this.rotation);
  15071. mesh.scaling.copyFrom(this.scaling);
  15072. mesh.computeWorldMatrix(true);
  15073. return mesh;
  15074. };
  15075. return CSG;
  15076. })();
  15077. BABYLON.CSG = CSG;
  15078. })(BABYLON || (BABYLON = {}));
  15079. var __extends = this.__extends || function (d, b) {
  15080. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15081. function __() { this.constructor = d; }
  15082. __.prototype = b.prototype;
  15083. d.prototype = new __();
  15084. };
  15085. var BABYLON;
  15086. (function (BABYLON) {
  15087. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15088. __extends(OculusDistortionCorrectionPostProcess, _super);
  15089. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15090. var _this = this;
  15091. _super.call(this, name, "oculusDistortionCorrection", [
  15092. 'LensCenter',
  15093. 'Scale',
  15094. 'ScaleIn',
  15095. 'HmdWarpParam'
  15096. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15097. this._isRightEye = isRightEye;
  15098. this._distortionFactors = cameraSettings.DistortionK;
  15099. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15100. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15101. this.onSizeChanged = function () {
  15102. _this.aspectRatio = _this.width * .5 / _this.height;
  15103. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15104. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15105. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15106. };
  15107. this.onApply = function (effect) {
  15108. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15109. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15110. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15111. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15112. };
  15113. }
  15114. return OculusDistortionCorrectionPostProcess;
  15115. })(BABYLON.PostProcess);
  15116. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15117. })(BABYLON || (BABYLON = {}));
  15118. var BABYLON;
  15119. (function (BABYLON) {
  15120. (function (JoystickAxis) {
  15121. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15122. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15123. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15124. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15125. var JoystickAxis = BABYLON.JoystickAxis;
  15126. var VirtualJoystick = (function () {
  15127. function VirtualJoystick(leftJoystick) {
  15128. var _this = this;
  15129. if (leftJoystick) {
  15130. this._leftJoystick = true;
  15131. } else {
  15132. this._leftJoystick = false;
  15133. }
  15134. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15135. VirtualJoystick._globalJoystickIndex++;
  15136. this._axisTargetedByLeftAndRight = 0 /* X */;
  15137. this._axisTargetedByUpAndDown = 1 /* Y */;
  15138. this.reverseLeftRight = false;
  15139. this.reverseUpDown = false;
  15140. this._touches = new BABYLON.VirtualJoystick.Collection();
  15141. this.deltaPosition = BABYLON.Vector3.Zero();
  15142. this._joystickSensibility = 25;
  15143. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15144. this._rotationSpeed = 25;
  15145. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15146. this._rotateOnAxisRelativeToMesh = false;
  15147. if (!VirtualJoystick.vjCanvas) {
  15148. window.addEventListener("resize", function () {
  15149. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15150. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15151. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15152. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15153. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15154. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15155. }, false);
  15156. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15157. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15158. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15159. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15160. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15161. VirtualJoystick.vjCanvas.style.width = "100%";
  15162. VirtualJoystick.vjCanvas.style.height = "100%";
  15163. VirtualJoystick.vjCanvas.style.position = "absolute";
  15164. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15165. VirtualJoystick.vjCanvas.style.top = "0px";
  15166. VirtualJoystick.vjCanvas.style.left = "0px";
  15167. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15168. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15169. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15170. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15171. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15172. document.body.appendChild(VirtualJoystick.vjCanvas);
  15173. }
  15174. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15175. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15176. this.pressed = false;
  15177. this._joystickColor = "cyan";
  15178. this._joystickPointerID = -1;
  15179. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15180. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15181. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15182. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15183. _this._onPointerDown(evt);
  15184. }, false);
  15185. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15186. _this._onPointerMove(evt);
  15187. }, false);
  15188. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15189. _this._onPointerUp(evt);
  15190. }, false);
  15191. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15192. _this._onPointerUp(evt);
  15193. }, false);
  15194. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15195. evt.preventDefault();
  15196. }, false);
  15197. requestAnimationFrame(function () {
  15198. _this._drawVirtualJoystick();
  15199. });
  15200. }
  15201. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15202. this._joystickSensibility = newJoystickSensibility;
  15203. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15204. };
  15205. VirtualJoystick.prototype._onPointerDown = function (e) {
  15206. var positionOnScreenCondition;
  15207. e.preventDefault();
  15208. if (this._leftJoystick === true) {
  15209. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15210. } else {
  15211. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15212. }
  15213. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15214. this._joystickPointerID = e.pointerId;
  15215. this._joystickPointerStartPos.x = e.clientX;
  15216. this._joystickPointerStartPos.y = e.clientY;
  15217. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15218. this._deltaJoystickVector.x = 0;
  15219. this._deltaJoystickVector.y = 0;
  15220. this.pressed = true;
  15221. this._touches.add(e.pointerId.toString(), e);
  15222. } else {
  15223. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15224. this._action();
  15225. this._touches.add(e.pointerId.toString(), e);
  15226. }
  15227. }
  15228. };
  15229. VirtualJoystick.prototype._onPointerMove = function (e) {
  15230. if (this._joystickPointerID == e.pointerId) {
  15231. this._joystickPointerPos.x = e.clientX;
  15232. this._joystickPointerPos.y = e.clientY;
  15233. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15234. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15235. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15236. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15237. switch (this._axisTargetedByLeftAndRight) {
  15238. case 0 /* X */:
  15239. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15240. break;
  15241. case 1 /* Y */:
  15242. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15243. break;
  15244. case 2 /* Z */:
  15245. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15246. break;
  15247. }
  15248. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15249. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15250. switch (this._axisTargetedByUpAndDown) {
  15251. case 0 /* X */:
  15252. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15253. break;
  15254. case 1 /* Y */:
  15255. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15256. break;
  15257. case 2 /* Z */:
  15258. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15259. break;
  15260. }
  15261. } else {
  15262. if (this._touches.item(e.pointerId.toString())) {
  15263. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15264. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15265. }
  15266. }
  15267. };
  15268. VirtualJoystick.prototype._onPointerUp = function (e) {
  15269. this._clearCanvas();
  15270. if (this._joystickPointerID == e.pointerId) {
  15271. this._joystickPointerID = -1;
  15272. this.pressed = false;
  15273. }
  15274. this._deltaJoystickVector.x = 0;
  15275. this._deltaJoystickVector.y = 0;
  15276. this._touches.remove(e.pointerId.toString());
  15277. };
  15278. /**
  15279. * Change the color of the virtual joystick
  15280. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15281. */
  15282. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15283. this._joystickColor = newColor;
  15284. };
  15285. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15286. this._action = action;
  15287. };
  15288. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15289. switch (axis) {
  15290. case 0 /* X */:
  15291. case 1 /* Y */:
  15292. case 2 /* Z */:
  15293. this._axisTargetedByLeftAndRight = axis;
  15294. break;
  15295. default:
  15296. this._axisTargetedByLeftAndRight = 0 /* X */;
  15297. break;
  15298. }
  15299. };
  15300. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15301. switch (axis) {
  15302. case 0 /* X */:
  15303. case 1 /* Y */:
  15304. case 2 /* Z */:
  15305. this._axisTargetedByUpAndDown = axis;
  15306. break;
  15307. default:
  15308. this._axisTargetedByUpAndDown = 1 /* Y */;
  15309. break;
  15310. }
  15311. };
  15312. VirtualJoystick.prototype._clearCanvas = function () {
  15313. if (this._leftJoystick) {
  15314. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15315. } else {
  15316. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15317. }
  15318. };
  15319. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15320. var _this = this;
  15321. if (this.pressed) {
  15322. this._clearCanvas();
  15323. this._touches.forEach(function (touch) {
  15324. if (touch.pointerId === _this._joystickPointerID) {
  15325. VirtualJoystick.vjCanvasContext.beginPath();
  15326. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15327. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15328. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15329. VirtualJoystick.vjCanvasContext.stroke();
  15330. VirtualJoystick.vjCanvasContext.beginPath();
  15331. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15332. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15333. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15334. VirtualJoystick.vjCanvasContext.stroke();
  15335. VirtualJoystick.vjCanvasContext.beginPath();
  15336. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15337. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15338. VirtualJoystick.vjCanvasContext.stroke();
  15339. } else {
  15340. VirtualJoystick.vjCanvasContext.beginPath();
  15341. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15342. VirtualJoystick.vjCanvasContext.beginPath();
  15343. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15344. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15345. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15346. VirtualJoystick.vjCanvasContext.stroke();
  15347. }
  15348. ;
  15349. });
  15350. }
  15351. requestAnimationFrame(function () {
  15352. _this._drawVirtualJoystick();
  15353. });
  15354. };
  15355. VirtualJoystick.prototype.releaseCanvas = function () {
  15356. if (VirtualJoystick.vjCanvas) {
  15357. document.body.removeChild(VirtualJoystick.vjCanvas);
  15358. VirtualJoystick.vjCanvas = null;
  15359. }
  15360. };
  15361. VirtualJoystick._globalJoystickIndex = 0;
  15362. return VirtualJoystick;
  15363. })();
  15364. BABYLON.VirtualJoystick = VirtualJoystick;
  15365. })(BABYLON || (BABYLON = {}));
  15366. var BABYLON;
  15367. (function (BABYLON) {
  15368. (function (VirtualJoystick) {
  15369. var Collection = (function () {
  15370. function Collection() {
  15371. this._count = 0;
  15372. this._collection = new Array();
  15373. }
  15374. Collection.prototype.Count = function () {
  15375. return this._count;
  15376. };
  15377. Collection.prototype.add = function (key, item) {
  15378. if (this._collection[key] != undefined) {
  15379. return undefined;
  15380. }
  15381. this._collection[key] = item;
  15382. return ++this._count;
  15383. };
  15384. Collection.prototype.remove = function (key) {
  15385. if (this._collection[key] == undefined) {
  15386. return undefined;
  15387. }
  15388. delete this._collection[key];
  15389. return --this._count;
  15390. };
  15391. Collection.prototype.item = function (key) {
  15392. return this._collection[key];
  15393. };
  15394. Collection.prototype.forEach = function (block) {
  15395. var key;
  15396. for (key in this._collection) {
  15397. if (this._collection.hasOwnProperty(key)) {
  15398. block(this._collection[key]);
  15399. }
  15400. }
  15401. };
  15402. return Collection;
  15403. })();
  15404. VirtualJoystick.Collection = Collection;
  15405. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15406. var VirtualJoystick = BABYLON.VirtualJoystick;
  15407. })(BABYLON || (BABYLON = {}));
  15408. var __extends = this.__extends || function (d, b) {
  15409. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15410. function __() { this.constructor = d; }
  15411. __.prototype = b.prototype;
  15412. d.prototype = new __();
  15413. };
  15414. var BABYLON;
  15415. (function (BABYLON) {
  15416. var OculusRiftDevKit2013_Metric = {
  15417. HResolution: 1280,
  15418. VResolution: 800,
  15419. HScreenSize: 0.149759993,
  15420. VScreenSize: 0.0935999975,
  15421. VScreenCenter: 0.0467999987,
  15422. EyeToScreenDistance: 0.0410000011,
  15423. LensSeparationDistance: 0.0635000020,
  15424. InterpupillaryDistance: 0.0640000030,
  15425. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15426. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15427. PostProcessScaleFactor: 1.714605507808412,
  15428. LensCenterOffset: 0.151976421
  15429. };
  15430. var _OculusInnerCamera = (function (_super) {
  15431. __extends(_OculusInnerCamera, _super);
  15432. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15433. _super.call(this, name, position, scene);
  15434. this._workMatrix = new BABYLON.Matrix();
  15435. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15436. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15437. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15438. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15439. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15440. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15441. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15442. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15443. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15444. }
  15445. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15446. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15447. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15448. return this._projectionMatrix;
  15449. };
  15450. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15451. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15452. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15453. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15454. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15455. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15456. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15457. return this._viewMatrix;
  15458. };
  15459. return _OculusInnerCamera;
  15460. })(BABYLON.FreeCamera);
  15461. var OculusCamera = (function (_super) {
  15462. __extends(OculusCamera, _super);
  15463. function OculusCamera(name, position, scene) {
  15464. _super.call(this, name, position, scene);
  15465. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15466. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15467. this.subCameras.push(this._leftCamera);
  15468. this.subCameras.push(this._rightCamera);
  15469. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15470. }
  15471. OculusCamera.prototype._update = function () {
  15472. this._leftCamera.position.copyFrom(this.position);
  15473. this._rightCamera.position.copyFrom(this.position);
  15474. this._updateCamera(this._leftCamera);
  15475. this._updateCamera(this._rightCamera);
  15476. _super.prototype._update.call(this);
  15477. };
  15478. OculusCamera.prototype._updateCamera = function (camera) {
  15479. camera.minZ = this.minZ;
  15480. camera.maxZ = this.maxZ;
  15481. camera.rotation.x = this.rotation.x;
  15482. camera.rotation.y = this.rotation.y;
  15483. camera.rotation.z = this.rotation.z;
  15484. };
  15485. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15486. var yaw = evt.alpha / 180 * Math.PI;
  15487. var pitch = evt.beta / 180 * Math.PI;
  15488. var roll = evt.gamma / 180 * Math.PI;
  15489. if (!this._offsetOrientation) {
  15490. this._offsetOrientation = {
  15491. yaw: yaw,
  15492. pitch: pitch,
  15493. roll: roll
  15494. };
  15495. return;
  15496. } else {
  15497. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15498. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15499. this.rotation.z += this._offsetOrientation.roll - roll;
  15500. this._offsetOrientation.yaw = yaw;
  15501. this._offsetOrientation.pitch = pitch;
  15502. this._offsetOrientation.roll = roll;
  15503. }
  15504. };
  15505. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15506. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15507. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15508. };
  15509. OculusCamera.prototype.detachControl = function (element) {
  15510. _super.prototype.detachControl.call(this, element);
  15511. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15512. };
  15513. return OculusCamera;
  15514. })(BABYLON.FreeCamera);
  15515. BABYLON.OculusCamera = OculusCamera;
  15516. })(BABYLON || (BABYLON = {}));
  15517. var __extends = this.__extends || function (d, b) {
  15518. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15519. function __() { this.constructor = d; }
  15520. __.prototype = b.prototype;
  15521. d.prototype = new __();
  15522. };
  15523. var BABYLON;
  15524. (function (BABYLON) {
  15525. var VirtualJoysticksCamera = (function (_super) {
  15526. __extends(VirtualJoysticksCamera, _super);
  15527. function VirtualJoysticksCamera(name, position, scene) {
  15528. _super.call(this, name, position, scene);
  15529. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15530. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15531. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15532. this._leftjoystick.setJoystickSensibility(0.15);
  15533. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15534. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15535. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15536. this._rightjoystick.reverseUpDown = true;
  15537. this._rightjoystick.setJoystickSensibility(0.05);
  15538. this._rightjoystick.setJoystickColor("yellow");
  15539. }
  15540. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15541. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15542. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15543. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15544. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15545. if (!this._leftjoystick.pressed) {
  15546. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15547. }
  15548. if (!this._rightjoystick.pressed) {
  15549. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15550. }
  15551. };
  15552. VirtualJoysticksCamera.prototype.dispose = function () {
  15553. this._leftjoystick.releaseCanvas();
  15554. _super.prototype.dispose.call(this);
  15555. };
  15556. return VirtualJoysticksCamera;
  15557. })(BABYLON.FreeCamera);
  15558. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15559. })(BABYLON || (BABYLON = {}));
  15560. var __extends = this.__extends || function (d, b) {
  15561. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15562. function __() { this.constructor = d; }
  15563. __.prototype = b.prototype;
  15564. d.prototype = new __();
  15565. };
  15566. var BABYLON;
  15567. (function (BABYLON) {
  15568. var ShaderMaterial = (function (_super) {
  15569. __extends(ShaderMaterial, _super);
  15570. function ShaderMaterial(name, scene, shaderPath, options) {
  15571. _super.call(this, name, scene);
  15572. this._textures = new Array();
  15573. this._floats = new Array();
  15574. this._floatsArrays = {};
  15575. this._colors3 = new Array();
  15576. this._colors4 = new Array();
  15577. this._vectors2 = new Array();
  15578. this._vectors3 = new Array();
  15579. this._matrices = new Array();
  15580. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15581. this._shaderPath = shaderPath;
  15582. options.needAlphaBlending = options.needAlphaBlending || false;
  15583. options.needAlphaTesting = options.needAlphaTesting || false;
  15584. options.attributes = options.attributes || ["position", "normal", "uv"];
  15585. options.uniforms = options.uniforms || ["worldViewProjection"];
  15586. options.samplers = options.samplers || [];
  15587. this._options = options;
  15588. }
  15589. ShaderMaterial.prototype.needAlphaBlending = function () {
  15590. return this._options.needAlphaBlending;
  15591. };
  15592. ShaderMaterial.prototype.needAlphaTesting = function () {
  15593. return this._options.needAlphaTesting;
  15594. };
  15595. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15596. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15597. this._options.uniforms.push(uniformName);
  15598. }
  15599. };
  15600. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15601. if (this._options.samplers.indexOf(name) === -1) {
  15602. this._options.samplers.push(name);
  15603. }
  15604. this._textures[name] = texture;
  15605. return this;
  15606. };
  15607. ShaderMaterial.prototype.setFloat = function (name, value) {
  15608. this._checkUniform(name);
  15609. this._floats[name] = value;
  15610. return this;
  15611. };
  15612. ShaderMaterial.prototype.setFloats = function (name, value) {
  15613. this._checkUniform(name);
  15614. this._floatsArrays[name] = value;
  15615. return this;
  15616. };
  15617. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15618. this._checkUniform(name);
  15619. this._colors3[name] = value;
  15620. return this;
  15621. };
  15622. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15623. this._checkUniform(name);
  15624. this._colors4[name] = value;
  15625. return this;
  15626. };
  15627. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15628. this._checkUniform(name);
  15629. this._vectors2[name] = value;
  15630. return this;
  15631. };
  15632. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15633. this._checkUniform(name);
  15634. this._vectors3[name] = value;
  15635. return this;
  15636. };
  15637. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15638. this._checkUniform(name);
  15639. this._matrices[name] = value;
  15640. return this;
  15641. };
  15642. ShaderMaterial.prototype.isReady = function () {
  15643. var engine = this.getScene().getEngine();
  15644. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15645. if (!this._effect.isReady()) {
  15646. return false;
  15647. }
  15648. return true;
  15649. };
  15650. ShaderMaterial.prototype.bind = function (world) {
  15651. if (this._options.uniforms.indexOf("world") !== -1) {
  15652. this._effect.setMatrix("world", world);
  15653. }
  15654. if (this._options.uniforms.indexOf("view") !== -1) {
  15655. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15656. }
  15657. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15658. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15659. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15660. }
  15661. if (this._options.uniforms.indexOf("projection") !== -1) {
  15662. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15663. }
  15664. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15665. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15666. }
  15667. for (var name in this._textures) {
  15668. this._effect.setTexture(name, this._textures[name]);
  15669. }
  15670. for (name in this._floats) {
  15671. this._effect.setFloat(name, this._floats[name]);
  15672. }
  15673. for (name in this._floatsArrays) {
  15674. this._effect.setArray(name, this._floatsArrays[name]);
  15675. }
  15676. for (name in this._colors3) {
  15677. this._effect.setColor3(name, this._colors3[name]);
  15678. }
  15679. for (name in this._colors4) {
  15680. var color = this._colors4[name];
  15681. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15682. }
  15683. for (name in this._vectors2) {
  15684. this._effect.setVector2(name, this._vectors2[name]);
  15685. }
  15686. for (name in this._vectors3) {
  15687. this._effect.setVector3(name, this._vectors3[name]);
  15688. }
  15689. for (name in this._matrices) {
  15690. this._effect.setMatrix(name, this._matrices[name]);
  15691. }
  15692. };
  15693. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  15694. for (var name in this._textures) {
  15695. this._textures[name].dispose();
  15696. }
  15697. this._textures = [];
  15698. _super.prototype.dispose.call(this, forceDisposeEffect);
  15699. };
  15700. return ShaderMaterial;
  15701. })(BABYLON.Material);
  15702. BABYLON.ShaderMaterial = ShaderMaterial;
  15703. })(BABYLON || (BABYLON = {}));
  15704. var BABYLON;
  15705. (function (BABYLON) {
  15706. var VertexData = (function () {
  15707. function VertexData() {
  15708. }
  15709. VertexData.prototype.set = function (data, kind) {
  15710. switch (kind) {
  15711. case BABYLON.VertexBuffer.PositionKind:
  15712. this.positions = data;
  15713. break;
  15714. case BABYLON.VertexBuffer.NormalKind:
  15715. this.normals = data;
  15716. break;
  15717. case BABYLON.VertexBuffer.UVKind:
  15718. this.uvs = data;
  15719. break;
  15720. case BABYLON.VertexBuffer.UV2Kind:
  15721. this.uv2s = data;
  15722. break;
  15723. case BABYLON.VertexBuffer.ColorKind:
  15724. this.colors = data;
  15725. break;
  15726. case BABYLON.VertexBuffer.MatricesIndicesKind:
  15727. this.matricesIndices = data;
  15728. break;
  15729. case BABYLON.VertexBuffer.MatricesWeightsKind:
  15730. this.matricesWeights = data;
  15731. break;
  15732. }
  15733. };
  15734. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  15735. this._applyTo(mesh, updatable);
  15736. };
  15737. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  15738. this._applyTo(geometry, updatable);
  15739. };
  15740. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  15741. this._update(mesh);
  15742. };
  15743. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  15744. this._update(geometry);
  15745. };
  15746. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  15747. if (this.positions) {
  15748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  15749. }
  15750. if (this.normals) {
  15751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  15752. }
  15753. if (this.uvs) {
  15754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  15755. }
  15756. if (this.uv2s) {
  15757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  15758. }
  15759. if (this.colors) {
  15760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  15761. }
  15762. if (this.matricesIndices) {
  15763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  15764. }
  15765. if (this.matricesWeights) {
  15766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  15767. }
  15768. if (this.indices) {
  15769. meshOrGeometry.setIndices(this.indices);
  15770. }
  15771. };
  15772. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  15773. if (this.positions) {
  15774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  15775. }
  15776. if (this.normals) {
  15777. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  15778. }
  15779. if (this.uvs) {
  15780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  15781. }
  15782. if (this.uv2s) {
  15783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  15784. }
  15785. if (this.colors) {
  15786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  15787. }
  15788. if (this.matricesIndices) {
  15789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  15790. }
  15791. if (this.matricesWeights) {
  15792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  15793. }
  15794. if (this.indices) {
  15795. meshOrGeometry.setIndices(this.indices);
  15796. }
  15797. };
  15798. VertexData.prototype.transform = function (matrix) {
  15799. var transformed = BABYLON.Vector3.Zero();
  15800. if (this.positions) {
  15801. var position = BABYLON.Vector3.Zero();
  15802. for (var index = 0; index < this.positions.length; index += 3) {
  15803. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  15804. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  15805. this.positions[index] = transformed.x;
  15806. this.positions[index + 1] = transformed.y;
  15807. this.positions[index + 2] = transformed.z;
  15808. }
  15809. }
  15810. if (this.normals) {
  15811. var normal = BABYLON.Vector3.Zero();
  15812. for (index = 0; index < this.normals.length; index += 3) {
  15813. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  15814. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  15815. this.normals[index] = transformed.x;
  15816. this.normals[index + 1] = transformed.y;
  15817. this.normals[index + 2] = transformed.z;
  15818. }
  15819. }
  15820. };
  15821. VertexData.prototype.merge = function (other) {
  15822. if (other.indices) {
  15823. if (!this.indices) {
  15824. this.indices = [];
  15825. }
  15826. var offset = this.positions ? this.positions.length / 3 : 0;
  15827. for (var index = 0; index < other.indices.length; index++) {
  15828. this.indices.push(other.indices[index] + offset);
  15829. }
  15830. }
  15831. if (other.positions) {
  15832. if (!this.positions) {
  15833. this.positions = [];
  15834. }
  15835. for (index = 0; index < other.positions.length; index++) {
  15836. this.positions.push(other.positions[index]);
  15837. }
  15838. }
  15839. if (other.normals) {
  15840. if (!this.normals) {
  15841. this.normals = [];
  15842. }
  15843. for (index = 0; index < other.normals.length; index++) {
  15844. this.normals.push(other.normals[index]);
  15845. }
  15846. }
  15847. if (other.uvs) {
  15848. if (!this.uvs) {
  15849. this.uvs = [];
  15850. }
  15851. for (index = 0; index < other.uvs.length; index++) {
  15852. this.uvs.push(other.uvs[index]);
  15853. }
  15854. }
  15855. if (other.uv2s) {
  15856. if (!this.uv2s) {
  15857. this.uv2s = [];
  15858. }
  15859. for (index = 0; index < other.uv2s.length; index++) {
  15860. this.uv2s.push(other.uv2s[index]);
  15861. }
  15862. }
  15863. if (other.matricesIndices) {
  15864. if (!this.matricesIndices) {
  15865. this.matricesIndices = [];
  15866. }
  15867. for (index = 0; index < other.matricesIndices.length; index++) {
  15868. this.matricesIndices.push(other.matricesIndices[index]);
  15869. }
  15870. }
  15871. if (other.matricesWeights) {
  15872. if (!this.matricesWeights) {
  15873. this.matricesWeights = [];
  15874. }
  15875. for (index = 0; index < other.matricesWeights.length; index++) {
  15876. this.matricesWeights.push(other.matricesWeights[index]);
  15877. }
  15878. }
  15879. if (other.colors) {
  15880. if (!this.colors) {
  15881. this.colors = [];
  15882. }
  15883. for (index = 0; index < other.colors.length; index++) {
  15884. this.colors.push(other.colors[index]);
  15885. }
  15886. }
  15887. };
  15888. VertexData.ExtractFromMesh = function (mesh) {
  15889. return VertexData._ExtractFrom(mesh);
  15890. };
  15891. VertexData.ExtractFromGeometry = function (geometry) {
  15892. return VertexData._ExtractFrom(geometry);
  15893. };
  15894. VertexData._ExtractFrom = function (meshOrGeometry) {
  15895. var result = new BABYLON.VertexData();
  15896. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15897. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15898. }
  15899. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15900. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15901. }
  15902. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15903. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15904. }
  15905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15906. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  15907. }
  15908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15909. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  15910. }
  15911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15912. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15913. }
  15914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15915. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15916. }
  15917. result.indices = meshOrGeometry.getIndices();
  15918. return result;
  15919. };
  15920. VertexData.CreateBox = function (size) {
  15921. var normalsSource = [
  15922. new BABYLON.Vector3(0, 0, 1),
  15923. new BABYLON.Vector3(0, 0, -1),
  15924. new BABYLON.Vector3(1, 0, 0),
  15925. new BABYLON.Vector3(-1, 0, 0),
  15926. new BABYLON.Vector3(0, 1, 0),
  15927. new BABYLON.Vector3(0, -1, 0)
  15928. ];
  15929. var indices = [];
  15930. var positions = [];
  15931. var normals = [];
  15932. var uvs = [];
  15933. size = size || 1;
  15934. for (var index = 0; index < normalsSource.length; index++) {
  15935. var normal = normalsSource[index];
  15936. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  15937. var side2 = BABYLON.Vector3.Cross(normal, side1);
  15938. var verticesLength = positions.length / 3;
  15939. indices.push(verticesLength);
  15940. indices.push(verticesLength + 1);
  15941. indices.push(verticesLength + 2);
  15942. indices.push(verticesLength);
  15943. indices.push(verticesLength + 2);
  15944. indices.push(verticesLength + 3);
  15945. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  15946. positions.push(vertex.x, vertex.y, vertex.z);
  15947. normals.push(normal.x, normal.y, normal.z);
  15948. uvs.push(1.0, 1.0);
  15949. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  15950. positions.push(vertex.x, vertex.y, vertex.z);
  15951. normals.push(normal.x, normal.y, normal.z);
  15952. uvs.push(0.0, 1.0);
  15953. vertex = normal.add(side1).add(side2).scale(size / 2);
  15954. positions.push(vertex.x, vertex.y, vertex.z);
  15955. normals.push(normal.x, normal.y, normal.z);
  15956. uvs.push(0.0, 0.0);
  15957. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  15958. positions.push(vertex.x, vertex.y, vertex.z);
  15959. normals.push(normal.x, normal.y, normal.z);
  15960. uvs.push(1.0, 0.0);
  15961. }
  15962. var vertexData = new BABYLON.VertexData();
  15963. vertexData.indices = indices;
  15964. vertexData.positions = positions;
  15965. vertexData.normals = normals;
  15966. vertexData.uvs = uvs;
  15967. return vertexData;
  15968. };
  15969. VertexData.CreateSphere = function (segments, diameter) {
  15970. segments = segments || 32;
  15971. diameter = diameter || 1;
  15972. var radius = diameter / 2;
  15973. var totalZRotationSteps = 2 + segments;
  15974. var totalYRotationSteps = 2 * totalZRotationSteps;
  15975. var indices = [];
  15976. var positions = [];
  15977. var normals = [];
  15978. var uvs = [];
  15979. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  15980. var normalizedZ = zRotationStep / totalZRotationSteps;
  15981. var angleZ = (normalizedZ * Math.PI);
  15982. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  15983. var normalizedY = yRotationStep / totalYRotationSteps;
  15984. var angleY = normalizedY * Math.PI * 2;
  15985. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  15986. var rotationY = BABYLON.Matrix.RotationY(angleY);
  15987. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  15988. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  15989. var vertex = complete.scale(radius);
  15990. var normal = BABYLON.Vector3.Normalize(vertex);
  15991. positions.push(vertex.x, vertex.y, vertex.z);
  15992. normals.push(normal.x, normal.y, normal.z);
  15993. uvs.push(normalizedZ, normalizedY);
  15994. }
  15995. if (zRotationStep > 0) {
  15996. var verticesCount = positions.length / 3;
  15997. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  15998. indices.push((firstIndex));
  15999. indices.push((firstIndex + 1));
  16000. indices.push(firstIndex + totalYRotationSteps + 1);
  16001. indices.push((firstIndex + totalYRotationSteps + 1));
  16002. indices.push((firstIndex + 1));
  16003. indices.push((firstIndex + totalYRotationSteps + 2));
  16004. }
  16005. }
  16006. }
  16007. var vertexData = new BABYLON.VertexData();
  16008. vertexData.indices = indices;
  16009. vertexData.positions = positions;
  16010. vertexData.normals = normals;
  16011. vertexData.uvs = uvs;
  16012. return vertexData;
  16013. };
  16014. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16015. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16016. var radiusTop = diameterTop / 2;
  16017. var radiusBottom = diameterBottom / 2;
  16018. var indices = [];
  16019. var positions = [];
  16020. var normals = [];
  16021. var uvs = [];
  16022. height = height || 1;
  16023. diameterTop = diameterTop || 0.5;
  16024. diameterBottom = diameterBottom || 1;
  16025. tessellation = tessellation || 16;
  16026. subdivisions = subdivisions || 1;
  16027. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16028. var getCircleVector = function (i) {
  16029. var angle = (i * 2.0 * Math.PI / tessellation);
  16030. var dx = Math.cos(angle);
  16031. var dz = Math.sin(angle);
  16032. return new BABYLON.Vector3(dx, 0, dz);
  16033. };
  16034. var createCylinderCap = function (isTop) {
  16035. var radius = isTop ? radiusTop : radiusBottom;
  16036. if (radius == 0) {
  16037. return;
  16038. }
  16039. var vbase = positions.length / 3;
  16040. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16041. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16042. if (!isTop) {
  16043. offset.scaleInPlace(-1);
  16044. textureScale.x = -textureScale.x;
  16045. }
  16046. for (i = 0; i < tessellation; i++) {
  16047. var circleVector = getCircleVector(i);
  16048. var position = circleVector.scale(radius).add(offset);
  16049. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16050. positions.push(position.x, position.y, position.z);
  16051. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16052. }
  16053. for (var i = 0; i < tessellation - 2; i++) {
  16054. if (!isTop) {
  16055. indices.push(vbase);
  16056. indices.push(vbase + (i + 2) % tessellation);
  16057. indices.push(vbase + (i + 1) % tessellation);
  16058. } else {
  16059. indices.push(vbase);
  16060. indices.push(vbase + (i + 1) % tessellation);
  16061. indices.push(vbase + (i + 2) % tessellation);
  16062. }
  16063. }
  16064. };
  16065. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16066. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16067. var stride = tessellation + 1;
  16068. for (var i = 0; i <= tessellation; i++) {
  16069. var circleVector = getCircleVector(i);
  16070. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16071. var position, radius = radiusBottom;
  16072. for (var s = 0; s <= subdivisions; s++) {
  16073. position = circleVector.scale(radius);
  16074. position.addInPlace(base.add(offset.scale(s)));
  16075. textureCoordinate.y += 1 / subdivisions;
  16076. radius += (radiusTop - radiusBottom) / subdivisions;
  16077. positions.push(position.x, position.y, position.z);
  16078. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16079. }
  16080. }
  16081. subdivisions += 1;
  16082. for (var s = 0; s < subdivisions - 1; s++) {
  16083. for (var i = 0; i <= tessellation; i++) {
  16084. indices.push(i * subdivisions + s);
  16085. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16086. indices.push(i * subdivisions + (s + 1));
  16087. indices.push(i * subdivisions + (s + 1));
  16088. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16089. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16090. }
  16091. }
  16092. createCylinderCap(true);
  16093. createCylinderCap(false);
  16094. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16095. var vertexData = new BABYLON.VertexData();
  16096. vertexData.indices = indices;
  16097. vertexData.positions = positions;
  16098. vertexData.normals = normals;
  16099. vertexData.uvs = uvs;
  16100. return vertexData;
  16101. };
  16102. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16103. var indices = [];
  16104. var positions = [];
  16105. var normals = [];
  16106. var uvs = [];
  16107. diameter = diameter || 1;
  16108. thickness = thickness || 0.5;
  16109. tessellation = tessellation || 16;
  16110. var stride = tessellation + 1;
  16111. for (var i = 0; i <= tessellation; i++) {
  16112. var u = i / tessellation;
  16113. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16114. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16115. for (var j = 0; j <= tessellation; j++) {
  16116. var v = 1 - j / tessellation;
  16117. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16118. var dx = Math.cos(innerAngle);
  16119. var dy = Math.sin(innerAngle);
  16120. var normal = new BABYLON.Vector3(dx, dy, 0);
  16121. var position = normal.scale(thickness / 2);
  16122. var textureCoordinate = new BABYLON.Vector2(u, v);
  16123. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16124. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16125. positions.push(position.x, position.y, position.z);
  16126. normals.push(normal.x, normal.y, normal.z);
  16127. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16128. var nextI = (i + 1) % stride;
  16129. var nextJ = (j + 1) % stride;
  16130. indices.push(i * stride + j);
  16131. indices.push(i * stride + nextJ);
  16132. indices.push(nextI * stride + j);
  16133. indices.push(i * stride + nextJ);
  16134. indices.push(nextI * stride + nextJ);
  16135. indices.push(nextI * stride + j);
  16136. }
  16137. }
  16138. var vertexData = new BABYLON.VertexData();
  16139. vertexData.indices = indices;
  16140. vertexData.positions = positions;
  16141. vertexData.normals = normals;
  16142. vertexData.uvs = uvs;
  16143. return vertexData;
  16144. };
  16145. VertexData.CreateLines = function (points) {
  16146. var indices = [];
  16147. var positions = [];
  16148. for (var index = 0; index < points.length; index++) {
  16149. positions.push(points[index].x, points[index].y, points[index].z);
  16150. if (index > 0) {
  16151. indices.push(index - 1);
  16152. indices.push(index);
  16153. }
  16154. }
  16155. var vertexData = new BABYLON.VertexData();
  16156. vertexData.indices = indices;
  16157. vertexData.positions = positions;
  16158. return vertexData;
  16159. };
  16160. VertexData.CreateGround = function (width, height, subdivisions) {
  16161. var indices = [];
  16162. var positions = [];
  16163. var normals = [];
  16164. var uvs = [];
  16165. var row, col;
  16166. width = width || 1;
  16167. height = height || 1;
  16168. subdivisions = subdivisions || 1;
  16169. for (row = 0; row <= subdivisions; row++) {
  16170. for (col = 0; col <= subdivisions; col++) {
  16171. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16172. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16173. positions.push(position.x, position.y, position.z);
  16174. normals.push(normal.x, normal.y, normal.z);
  16175. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16176. }
  16177. }
  16178. for (row = 0; row < subdivisions; row++) {
  16179. for (col = 0; col < subdivisions; col++) {
  16180. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16181. indices.push(col + 1 + row * (subdivisions + 1));
  16182. indices.push(col + row * (subdivisions + 1));
  16183. indices.push(col + (row + 1) * (subdivisions + 1));
  16184. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16185. indices.push(col + row * (subdivisions + 1));
  16186. }
  16187. }
  16188. var vertexData = new BABYLON.VertexData();
  16189. vertexData.indices = indices;
  16190. vertexData.positions = positions;
  16191. vertexData.normals = normals;
  16192. vertexData.uvs = uvs;
  16193. return vertexData;
  16194. };
  16195. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16196. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16197. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16198. var indices = [];
  16199. var positions = [];
  16200. var normals = [];
  16201. var uvs = [];
  16202. var row, col, tileRow, tileCol;
  16203. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16204. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16205. precision.w = (precision.w < 1) ? 1 : precision.w;
  16206. precision.h = (precision.h < 1) ? 1 : precision.h;
  16207. var tileSize = {
  16208. 'w': (xmax - xmin) / subdivisions.w,
  16209. 'h': (zmax - zmin) / subdivisions.h
  16210. };
  16211. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16212. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16213. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16214. }
  16215. }
  16216. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16217. var base = positions.length / 3;
  16218. var rowLength = precision.w + 1;
  16219. for (row = 0; row < precision.h; row++) {
  16220. for (col = 0; col < precision.w; col++) {
  16221. var square = [
  16222. base + col + row * rowLength,
  16223. base + (col + 1) + row * rowLength,
  16224. base + (col + 1) + (row + 1) * rowLength,
  16225. base + col + (row + 1) * rowLength
  16226. ];
  16227. indices.push(square[1]);
  16228. indices.push(square[2]);
  16229. indices.push(square[3]);
  16230. indices.push(square[0]);
  16231. indices.push(square[1]);
  16232. indices.push(square[3]);
  16233. }
  16234. }
  16235. var position = BABYLON.Vector3.Zero();
  16236. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16237. for (row = 0; row <= precision.h; row++) {
  16238. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16239. for (col = 0; col <= precision.w; col++) {
  16240. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16241. position.y = 0;
  16242. positions.push(position.x, position.y, position.z);
  16243. normals.push(normal.x, normal.y, normal.z);
  16244. uvs.push(col / precision.w, row / precision.h);
  16245. }
  16246. }
  16247. }
  16248. var vertexData = new BABYLON.VertexData();
  16249. vertexData.indices = indices;
  16250. vertexData.positions = positions;
  16251. vertexData.normals = normals;
  16252. vertexData.uvs = uvs;
  16253. return vertexData;
  16254. };
  16255. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16256. var indices = [];
  16257. var positions = [];
  16258. var normals = [];
  16259. var uvs = [];
  16260. var row, col;
  16261. for (row = 0; row <= subdivisions; row++) {
  16262. for (col = 0; col <= subdivisions; col++) {
  16263. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16264. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16265. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16266. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16267. var r = buffer[pos] / 255.0;
  16268. var g = buffer[pos + 1] / 255.0;
  16269. var b = buffer[pos + 2] / 255.0;
  16270. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16271. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16272. positions.push(position.x, position.y, position.z);
  16273. normals.push(0, 0, 0);
  16274. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16275. }
  16276. }
  16277. for (row = 0; row < subdivisions; row++) {
  16278. for (col = 0; col < subdivisions; col++) {
  16279. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16280. indices.push(col + 1 + row * (subdivisions + 1));
  16281. indices.push(col + row * (subdivisions + 1));
  16282. indices.push(col + (row + 1) * (subdivisions + 1));
  16283. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16284. indices.push(col + row * (subdivisions + 1));
  16285. }
  16286. }
  16287. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16288. var vertexData = new BABYLON.VertexData();
  16289. vertexData.indices = indices;
  16290. vertexData.positions = positions;
  16291. vertexData.normals = normals;
  16292. vertexData.uvs = uvs;
  16293. return vertexData;
  16294. };
  16295. VertexData.CreatePlane = function (size) {
  16296. var indices = [];
  16297. var positions = [];
  16298. var normals = [];
  16299. var uvs = [];
  16300. size = size || 1;
  16301. var halfSize = size / 2.0;
  16302. positions.push(-halfSize, -halfSize, 0);
  16303. normals.push(0, 0, -1.0);
  16304. uvs.push(0.0, 0.0);
  16305. positions.push(halfSize, -halfSize, 0);
  16306. normals.push(0, 0, -1.0);
  16307. uvs.push(1.0, 0.0);
  16308. positions.push(halfSize, halfSize, 0);
  16309. normals.push(0, 0, -1.0);
  16310. uvs.push(1.0, 1.0);
  16311. positions.push(-halfSize, halfSize, 0);
  16312. normals.push(0, 0, -1.0);
  16313. uvs.push(0.0, 1.0);
  16314. indices.push(0);
  16315. indices.push(1);
  16316. indices.push(2);
  16317. indices.push(0);
  16318. indices.push(2);
  16319. indices.push(3);
  16320. var vertexData = new BABYLON.VertexData();
  16321. vertexData.indices = indices;
  16322. vertexData.positions = positions;
  16323. vertexData.normals = normals;
  16324. vertexData.uvs = uvs;
  16325. return vertexData;
  16326. };
  16327. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16328. var indices = [];
  16329. var positions = [];
  16330. var normals = [];
  16331. var uvs = [];
  16332. radius = radius || 2;
  16333. tube = tube || 0.5;
  16334. radialSegments = radialSegments || 32;
  16335. tubularSegments = tubularSegments || 32;
  16336. p = p || 2;
  16337. q = q || 3;
  16338. var getPos = function (angle) {
  16339. var cu = Math.cos(angle);
  16340. var su = Math.sin(angle);
  16341. var quOverP = q / p * angle;
  16342. var cs = Math.cos(quOverP);
  16343. var tx = radius * (2 + cs) * 0.5 * cu;
  16344. var ty = radius * (2 + cs) * su * 0.5;
  16345. var tz = radius * Math.sin(quOverP) * 0.5;
  16346. return new BABYLON.Vector3(tx, ty, tz);
  16347. };
  16348. for (var i = 0; i <= radialSegments; i++) {
  16349. var modI = i % radialSegments;
  16350. var u = modI / radialSegments * 2 * p * Math.PI;
  16351. var p1 = getPos(u);
  16352. var p2 = getPos(u + 0.01);
  16353. var tang = p2.subtract(p1);
  16354. var n = p2.add(p1);
  16355. var bitan = BABYLON.Vector3.Cross(tang, n);
  16356. n = BABYLON.Vector3.Cross(bitan, tang);
  16357. bitan.normalize();
  16358. n.normalize();
  16359. for (var j = 0; j < tubularSegments; j++) {
  16360. var modJ = j % tubularSegments;
  16361. var v = modJ / tubularSegments * 2 * Math.PI;
  16362. var cx = -tube * Math.cos(v);
  16363. var cy = tube * Math.sin(v);
  16364. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16365. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16366. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16367. uvs.push(i / radialSegments);
  16368. uvs.push(j / tubularSegments);
  16369. }
  16370. }
  16371. for (i = 0; i < radialSegments; i++) {
  16372. for (j = 0; j < tubularSegments; j++) {
  16373. var jNext = (j + 1) % tubularSegments;
  16374. var a = i * tubularSegments + j;
  16375. var b = (i + 1) * tubularSegments + j;
  16376. var c = (i + 1) * tubularSegments + jNext;
  16377. var d = i * tubularSegments + jNext;
  16378. indices.push(d);
  16379. indices.push(b);
  16380. indices.push(a);
  16381. indices.push(d);
  16382. indices.push(c);
  16383. indices.push(b);
  16384. }
  16385. }
  16386. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16387. var vertexData = new BABYLON.VertexData();
  16388. vertexData.indices = indices;
  16389. vertexData.positions = positions;
  16390. vertexData.normals = normals;
  16391. vertexData.uvs = uvs;
  16392. return vertexData;
  16393. };
  16394. VertexData.ComputeNormals = function (positions, indices, normals) {
  16395. var positionVectors = [];
  16396. var facesOfVertices = [];
  16397. var index;
  16398. for (index = 0; index < positions.length; index += 3) {
  16399. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16400. positionVectors.push(vector3);
  16401. facesOfVertices.push([]);
  16402. }
  16403. var facesNormals = [];
  16404. for (index = 0; index < indices.length / 3; index++) {
  16405. var i1 = indices[index * 3];
  16406. var i2 = indices[index * 3 + 1];
  16407. var i3 = indices[index * 3 + 2];
  16408. var p1 = positionVectors[i1];
  16409. var p2 = positionVectors[i2];
  16410. var p3 = positionVectors[i3];
  16411. var p1p2 = p1.subtract(p2);
  16412. var p3p2 = p3.subtract(p2);
  16413. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16414. facesOfVertices[i1].push(index);
  16415. facesOfVertices[i2].push(index);
  16416. facesOfVertices[i3].push(index);
  16417. }
  16418. for (index = 0; index < positionVectors.length; index++) {
  16419. var faces = facesOfVertices[index];
  16420. var normal = BABYLON.Vector3.Zero();
  16421. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16422. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16423. }
  16424. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16425. normals[index * 3] = normal.x;
  16426. normals[index * 3 + 1] = normal.y;
  16427. normals[index * 3 + 2] = normal.z;
  16428. }
  16429. };
  16430. return VertexData;
  16431. })();
  16432. BABYLON.VertexData = VertexData;
  16433. })(BABYLON || (BABYLON = {}));
  16434. var __extends = this.__extends || function (d, b) {
  16435. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16436. function __() { this.constructor = d; }
  16437. __.prototype = b.prototype;
  16438. d.prototype = new __();
  16439. };
  16440. var BABYLON;
  16441. (function (BABYLON) {
  16442. var buildCamera = function (that, name) {
  16443. that._leftCamera.isIntermediate = true;
  16444. that.subCameras.push(that._leftCamera);
  16445. that.subCameras.push(that._rightCamera);
  16446. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16447. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16448. that._anaglyphPostProcess.onApply = function (effect) {
  16449. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16450. };
  16451. that._update();
  16452. };
  16453. var AnaglyphArcRotateCamera = (function (_super) {
  16454. __extends(AnaglyphArcRotateCamera, _super);
  16455. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16456. _super.call(this, name, alpha, beta, radius, target, scene);
  16457. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16458. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16459. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16460. buildCamera(this, name);
  16461. }
  16462. AnaglyphArcRotateCamera.prototype._update = function () {
  16463. this._updateCamera(this._leftCamera);
  16464. this._updateCamera(this._rightCamera);
  16465. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16466. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16467. _super.prototype._update.call(this);
  16468. };
  16469. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16470. camera.beta = this.beta;
  16471. camera.radius = this.radius;
  16472. camera.minZ = this.minZ;
  16473. camera.maxZ = this.maxZ;
  16474. camera.fov = this.fov;
  16475. camera.target = this.target;
  16476. };
  16477. return AnaglyphArcRotateCamera;
  16478. })(BABYLON.ArcRotateCamera);
  16479. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16480. var AnaglyphFreeCamera = (function (_super) {
  16481. __extends(AnaglyphFreeCamera, _super);
  16482. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16483. _super.call(this, name, position, scene);
  16484. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16485. this._transformMatrix = new BABYLON.Matrix();
  16486. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16487. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16488. buildCamera(this, name);
  16489. }
  16490. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16491. var target = this.getTarget();
  16492. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16493. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16494. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16495. };
  16496. AnaglyphFreeCamera.prototype._update = function () {
  16497. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16498. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16499. this._updateCamera(this._leftCamera);
  16500. this._updateCamera(this._rightCamera);
  16501. _super.prototype._update.call(this);
  16502. };
  16503. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16504. camera.minZ = this.minZ;
  16505. camera.maxZ = this.maxZ;
  16506. camera.fov = this.fov;
  16507. camera.viewport = this.viewport;
  16508. camera.setTarget(this.getTarget());
  16509. };
  16510. return AnaglyphFreeCamera;
  16511. })(BABYLON.FreeCamera);
  16512. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16513. })(BABYLON || (BABYLON = {}));
  16514. var __extends = this.__extends || function (d, b) {
  16515. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16516. function __() { this.constructor = d; }
  16517. __.prototype = b.prototype;
  16518. d.prototype = new __();
  16519. };
  16520. var BABYLON;
  16521. (function (BABYLON) {
  16522. var AnaglyphPostProcess = (function (_super) {
  16523. __extends(AnaglyphPostProcess, _super);
  16524. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16525. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16526. }
  16527. return AnaglyphPostProcess;
  16528. })(BABYLON.PostProcess);
  16529. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16530. })(BABYLON || (BABYLON = {}));
  16531. var BABYLON;
  16532. (function (BABYLON) {
  16533. var Tags = (function () {
  16534. function Tags() {
  16535. }
  16536. Tags.EnableFor = function (obj) {
  16537. obj._tags = obj._tags || {};
  16538. obj.hasTags = function () {
  16539. return Tags.HasTags(obj);
  16540. };
  16541. obj.addTags = function (tagsString) {
  16542. return Tags.AddTagsTo(obj, tagsString);
  16543. };
  16544. obj.removeTags = function (tagsString) {
  16545. return Tags.RemoveTagsFrom(obj, tagsString);
  16546. };
  16547. obj.matchesTagsQuery = function (tagsQuery) {
  16548. return Tags.MatchesQuery(obj, tagsQuery);
  16549. };
  16550. };
  16551. Tags.DisableFor = function (obj) {
  16552. delete obj._tags;
  16553. delete obj.hasTags;
  16554. delete obj.addTags;
  16555. delete obj.removeTags;
  16556. delete obj.matchesTagsQuery;
  16557. };
  16558. Tags.HasTags = function (obj) {
  16559. if (!obj._tags) {
  16560. return false;
  16561. }
  16562. return !BABYLON.Tools.IsEmpty(obj._tags);
  16563. };
  16564. Tags.GetTags = function (obj) {
  16565. if (!obj._tags) {
  16566. return null;
  16567. }
  16568. return obj._tags;
  16569. };
  16570. Tags.AddTagsTo = function (obj, tagsString) {
  16571. if (!tagsString) {
  16572. return;
  16573. }
  16574. var tags = tagsString.split(" ");
  16575. for (var t in tags) {
  16576. Tags._AddTagTo(obj, tags[t]);
  16577. }
  16578. };
  16579. Tags._AddTagTo = function (obj, tag) {
  16580. tag = tag.trim();
  16581. if (tag === "" || tag === "true" || tag === "false") {
  16582. return;
  16583. }
  16584. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16585. return;
  16586. }
  16587. Tags.EnableFor(obj);
  16588. obj._tags[tag] = true;
  16589. };
  16590. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16591. if (!Tags.HasTags(obj)) {
  16592. return;
  16593. }
  16594. var tags = tagsString.split(" ");
  16595. for (var t in tags) {
  16596. Tags._RemoveTagFrom(obj, tags[t]);
  16597. }
  16598. };
  16599. Tags._RemoveTagFrom = function (obj, tag) {
  16600. delete obj._tags[tag];
  16601. };
  16602. Tags.MatchesQuery = function (obj, tagsQuery) {
  16603. if (tagsQuery === undefined) {
  16604. return true;
  16605. }
  16606. if (tagsQuery === "") {
  16607. return Tags.HasTags(obj);
  16608. }
  16609. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16610. return Tags.HasTags(obj) && obj._tags[r];
  16611. });
  16612. };
  16613. return Tags;
  16614. })();
  16615. BABYLON.Tags = Tags;
  16616. })(BABYLON || (BABYLON = {}));
  16617. var BABYLON;
  16618. (function (BABYLON) {
  16619. (function (Internals) {
  16620. var AndOrNotEvaluator = (function () {
  16621. function AndOrNotEvaluator() {
  16622. }
  16623. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16624. if (!query.match(/\([^\(\)]*\)/g)) {
  16625. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16626. } else {
  16627. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16628. r = r.slice(1, r.length - 1);
  16629. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16630. });
  16631. }
  16632. if (query === "true") {
  16633. return true;
  16634. }
  16635. if (query === "false") {
  16636. return false;
  16637. }
  16638. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16639. };
  16640. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16641. evaluateCallback = evaluateCallback || (function (r) {
  16642. return r === "true" ? true : false;
  16643. });
  16644. var result;
  16645. var or = parenthesisContent.split("||");
  16646. for (var i in or) {
  16647. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16648. var and = ori.split("&&");
  16649. if (and.length > 1) {
  16650. for (var j = 0; j < and.length; ++j) {
  16651. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16652. if (andj !== "true" && andj !== "false") {
  16653. if (andj[0] === "!") {
  16654. result = !evaluateCallback(andj.substring(1));
  16655. } else {
  16656. result = evaluateCallback(andj);
  16657. }
  16658. } else {
  16659. result = andj === "true" ? true : false;
  16660. }
  16661. if (!result) {
  16662. ori = "false";
  16663. break;
  16664. }
  16665. }
  16666. }
  16667. if (result || ori === "true") {
  16668. result = true;
  16669. break;
  16670. }
  16671. if (ori !== "true" && ori !== "false") {
  16672. if (ori[0] === "!") {
  16673. result = !evaluateCallback(ori.substring(1));
  16674. } else {
  16675. result = evaluateCallback(ori);
  16676. }
  16677. } else {
  16678. result = ori === "true" ? true : false;
  16679. }
  16680. }
  16681. return result ? "true" : "false";
  16682. };
  16683. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16684. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16685. r = r.replace(/[\s]/g, function () {
  16686. return "";
  16687. });
  16688. return r.length % 2 ? "!" : "";
  16689. });
  16690. booleanString = booleanString.trim();
  16691. if (booleanString === "!true") {
  16692. booleanString = "false";
  16693. } else if (booleanString === "!false") {
  16694. booleanString = "true";
  16695. }
  16696. return booleanString;
  16697. };
  16698. return AndOrNotEvaluator;
  16699. })();
  16700. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  16701. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16702. var Internals = BABYLON.Internals;
  16703. })(BABYLON || (BABYLON = {}));
  16704. var BABYLON;
  16705. (function (BABYLON) {
  16706. var PostProcessRenderPass = (function () {
  16707. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  16708. this._enabled = true;
  16709. this._refCount = 0;
  16710. this._name = name;
  16711. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  16712. this.setRenderList(renderList);
  16713. this._renderTexture.onBeforeRender = beforeRender;
  16714. this._renderTexture.onAfterRender = afterRender;
  16715. this._scene = scene;
  16716. }
  16717. PostProcessRenderPass.prototype._incRefCount = function () {
  16718. if (this._refCount === 0) {
  16719. this._scene.customRenderTargets.push(this._renderTexture);
  16720. }
  16721. return ++this._refCount;
  16722. };
  16723. PostProcessRenderPass.prototype._decRefCount = function () {
  16724. this._refCount--;
  16725. if (this._refCount <= 0) {
  16726. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  16727. }
  16728. return this._refCount;
  16729. };
  16730. PostProcessRenderPass.prototype._update = function () {
  16731. this.setRenderList(this._renderList);
  16732. };
  16733. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  16734. this._renderTexture.renderList = renderList;
  16735. };
  16736. PostProcessRenderPass.prototype.getRenderTexture = function () {
  16737. return this._renderTexture;
  16738. };
  16739. return PostProcessRenderPass;
  16740. })();
  16741. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  16742. })(BABYLON || (BABYLON = {}));
  16743. var BABYLON;
  16744. (function (BABYLON) {
  16745. var PostProcessRenderEffect = (function () {
  16746. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  16747. this._engine = engine;
  16748. this._name = name;
  16749. this._postProcessType = postProcessType;
  16750. this._ratio = ratio || 1.0;
  16751. this._samplingMode = samplingMode || null;
  16752. this._singleInstance = singleInstance || true;
  16753. this._cameras = [];
  16754. this._postProcesses = [];
  16755. this._indicesForCamera = [];
  16756. this._renderPasses = [];
  16757. this._renderEffectAsPasses = [];
  16758. this.parameters = function (effect) {
  16759. };
  16760. }
  16761. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  16762. var postProcess;
  16763. var instance;
  16764. var args = [];
  16765. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  16766. for (var i = 0; i < parameters.length; i++) {
  16767. switch (parameters[i]) {
  16768. case "name":
  16769. args[i] = postProcessType.toString();
  16770. break;
  16771. case "ratio":
  16772. args[i] = ratio;
  16773. break;
  16774. case "camera":
  16775. args[i] = null;
  16776. break;
  16777. case "samplingMode":
  16778. args[i] = samplingMode;
  16779. break;
  16780. case "engine":
  16781. args[i] = engine;
  16782. break;
  16783. case "reusable":
  16784. args[i] = true;
  16785. break;
  16786. default:
  16787. args[i] = null;
  16788. break;
  16789. }
  16790. }
  16791. postProcess = function () {
  16792. };
  16793. postProcess.prototype = postProcessType.prototype;
  16794. instance = new postProcess();
  16795. postProcessType.apply(instance, args);
  16796. return instance;
  16797. };
  16798. PostProcessRenderEffect._GetParametersNames = function (func) {
  16799. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  16800. var functWithoutComments = func.toString().replace(commentsRegex, '');
  16801. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  16802. if (parameters === null)
  16803. parameters = [];
  16804. return parameters;
  16805. };
  16806. PostProcessRenderEffect.prototype._update = function () {
  16807. for (var renderPassName in this._renderPasses) {
  16808. this._renderPasses[renderPassName]._update();
  16809. }
  16810. };
  16811. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  16812. this._renderPasses[renderPass._name] = renderPass;
  16813. this._linkParameters();
  16814. };
  16815. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  16816. delete this._renderPasses[renderPass._name];
  16817. this._linkParameters();
  16818. };
  16819. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  16820. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  16821. this._linkParameters();
  16822. };
  16823. PostProcessRenderEffect.prototype.getPass = function (passName) {
  16824. for (var renderPassName in this._renderPasses) {
  16825. if (renderPassName === passName) {
  16826. return this._renderPasses[passName];
  16827. }
  16828. }
  16829. };
  16830. PostProcessRenderEffect.prototype.emptyPasses = function () {
  16831. this._renderPasses.length = 0;
  16832. this._linkParameters();
  16833. };
  16834. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  16835. var cameraKey;
  16836. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16837. for (var i = 0; i < _cam.length; i++) {
  16838. var camera = _cam[i];
  16839. var cameraName = camera.name;
  16840. if (this._singleInstance) {
  16841. cameraKey = 0;
  16842. } else {
  16843. cameraKey = cameraName;
  16844. }
  16845. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  16846. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  16847. if (this._indicesForCamera[cameraName] === null) {
  16848. this._indicesForCamera[cameraName] = [];
  16849. }
  16850. this._indicesForCamera[cameraName].push(index);
  16851. if (this._cameras.indexOf(camera) === -1) {
  16852. this._cameras[cameraName] = camera;
  16853. }
  16854. for (var passName in this._renderPasses) {
  16855. this._renderPasses[passName]._incRefCount();
  16856. }
  16857. }
  16858. this._linkParameters();
  16859. };
  16860. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  16861. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16862. for (var i = 0; i < _cam.length; i++) {
  16863. var camera = _cam[i];
  16864. var cameraName = camera.name;
  16865. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16866. var index = this._cameras.indexOf(cameraName);
  16867. this._indicesForCamera.splice(index, 1);
  16868. this._cameras.splice(index, 1);
  16869. for (var passName in this._renderPasses) {
  16870. this._renderPasses[passName]._decRefCount();
  16871. }
  16872. }
  16873. };
  16874. PostProcessRenderEffect.prototype._enable = function (cameras) {
  16875. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16876. for (var i = 0; i < _cam.length; i++) {
  16877. var camera = _cam[i];
  16878. var cameraName = camera.name;
  16879. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  16880. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  16881. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  16882. }
  16883. }
  16884. for (var passName in this._renderPasses) {
  16885. this._renderPasses[passName]._incRefCount();
  16886. }
  16887. }
  16888. };
  16889. PostProcessRenderEffect.prototype._disable = function (cameras) {
  16890. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16891. for (var i = 0; i < _cam.length; i++) {
  16892. var camera = _cam[i];
  16893. var cameraName = camera.Name;
  16894. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  16895. for (var passName in this._renderPasses) {
  16896. this._renderPasses[passName]._decRefCount();
  16897. }
  16898. }
  16899. };
  16900. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  16901. if (this._singleInstance) {
  16902. return this._postProcesses[0];
  16903. } else {
  16904. return this._postProcesses[camera.name];
  16905. }
  16906. };
  16907. PostProcessRenderEffect.prototype._linkParameters = function () {
  16908. var _this = this;
  16909. for (var index in this._postProcesses) {
  16910. this._postProcesses[index].onApply = function (effect) {
  16911. _this.parameters(effect);
  16912. _this._linkTextures(effect);
  16913. };
  16914. }
  16915. };
  16916. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  16917. for (var renderPassName in this._renderPasses) {
  16918. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  16919. }
  16920. for (var renderEffectName in this._renderEffectAsPasses) {
  16921. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  16922. }
  16923. };
  16924. return PostProcessRenderEffect;
  16925. })();
  16926. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  16927. })(BABYLON || (BABYLON = {}));
  16928. var BABYLON;
  16929. (function (BABYLON) {
  16930. var PostProcessRenderPipeline = (function () {
  16931. function PostProcessRenderPipeline(engine, name) {
  16932. this._engine = engine;
  16933. this._name = name;
  16934. this._renderEffects = [];
  16935. this._renderEffectsForIsolatedPass = [];
  16936. this._cameras = [];
  16937. }
  16938. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  16939. this._renderEffects[renderEffect._name] = renderEffect;
  16940. };
  16941. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  16942. var renderEffects = this._renderEffects[renderEffectName];
  16943. if (!renderEffects) {
  16944. return;
  16945. }
  16946. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  16947. };
  16948. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  16949. var renderEffects = this._renderEffects[renderEffectName];
  16950. if (!renderEffects) {
  16951. return;
  16952. }
  16953. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  16954. };
  16955. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  16956. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16957. var indicesToDelete = [];
  16958. for (var i = 0; i < _cam.length; i++) {
  16959. var camera = _cam[i];
  16960. var cameraName = camera.name;
  16961. if (this._cameras.indexOf(camera) === -1) {
  16962. this._cameras[cameraName] = camera;
  16963. } else if (unique) {
  16964. indicesToDelete.push(i);
  16965. }
  16966. }
  16967. for (var i = 0; i < indicesToDelete.length; i++) {
  16968. cameras.splice(indicesToDelete[i], 1);
  16969. }
  16970. for (var renderEffectName in this._renderEffects) {
  16971. this._renderEffects[renderEffectName]._attachCameras(_cam);
  16972. }
  16973. };
  16974. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  16975. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16976. for (var renderEffectName in this._renderEffects) {
  16977. this._renderEffects[renderEffectName]._detachCameras(_cam);
  16978. }
  16979. for (var i = 0; i < _cam.length; i++) {
  16980. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  16981. }
  16982. };
  16983. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  16984. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  16985. var pass = null;
  16986. for (var renderEffectName in this._renderEffects) {
  16987. pass = this._renderEffects[renderEffectName].getPass(passName);
  16988. if (pass != null) {
  16989. break;
  16990. }
  16991. }
  16992. if (pass === null) {
  16993. return;
  16994. }
  16995. for (var renderEffectName in this._renderEffects) {
  16996. this._renderEffects[renderEffectName]._disable(_cam);
  16997. }
  16998. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  16999. for (var i = 0; i < _cam.length; i++) {
  17000. var camera = _cam[i];
  17001. var cameraName = camera.name;
  17002. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17003. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17004. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17005. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17006. }
  17007. };
  17008. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17009. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17010. for (var i = 0; i < _cam.length; i++) {
  17011. var camera = _cam[i];
  17012. var cameraName = camera.name;
  17013. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17014. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17015. }
  17016. for (var renderEffectName in this._renderEffects) {
  17017. this._renderEffects[renderEffectName]._enable(_cam);
  17018. }
  17019. };
  17020. PostProcessRenderPipeline.prototype._update = function () {
  17021. for (var renderEffectName in this._renderEffects) {
  17022. this._renderEffects[renderEffectName]._update();
  17023. }
  17024. for (var i = 0; i < this._cameras.length; i++) {
  17025. var cameraName = this._cameras[i].name;
  17026. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17027. this._renderEffectsForIsolatedPass[cameraName]._update();
  17028. }
  17029. }
  17030. };
  17031. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17032. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17033. return PostProcessRenderPipeline;
  17034. })();
  17035. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17036. })(BABYLON || (BABYLON = {}));
  17037. var BABYLON;
  17038. (function (BABYLON) {
  17039. var PostProcessRenderPipelineManager = (function () {
  17040. function PostProcessRenderPipelineManager() {
  17041. this._renderPipelines = [];
  17042. }
  17043. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17044. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17045. };
  17046. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17047. var renderPipeline = this._renderPipelines[renderPipelineName];
  17048. if (!renderPipeline) {
  17049. return;
  17050. }
  17051. renderPipeline.attachCameras(cameras, unique);
  17052. };
  17053. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17054. var renderPipeline = this._renderPipelines[renderPipelineName];
  17055. if (!renderPipeline) {
  17056. return;
  17057. }
  17058. renderPipeline.detachCameras(cameras);
  17059. };
  17060. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17061. var renderPipeline = this._renderPipelines[renderPipelineName];
  17062. if (!renderPipeline) {
  17063. return;
  17064. }
  17065. renderPipeline.enableEffect(renderEffectName, cameras);
  17066. };
  17067. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17068. var renderPipeline = this._renderPipelines[renderPipelineName];
  17069. if (!renderPipeline) {
  17070. return;
  17071. }
  17072. renderPipeline.disableEffect(renderEffectName, cameras);
  17073. };
  17074. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17075. var renderPipeline = this._renderPipelines[renderPipelineName];
  17076. if (!renderPipeline) {
  17077. return;
  17078. }
  17079. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17080. };
  17081. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17082. var renderPipeline = this._renderPipelines[renderPipelineName];
  17083. if (!renderPipeline) {
  17084. return;
  17085. }
  17086. renderPipeline.disableDisplayOnlyPass(cameras);
  17087. };
  17088. PostProcessRenderPipelineManager.prototype.update = function () {
  17089. for (var renderPipelineName in this._renderPipelines) {
  17090. this._renderPipelines[renderPipelineName]._update();
  17091. }
  17092. };
  17093. return PostProcessRenderPipelineManager;
  17094. })();
  17095. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17096. })(BABYLON || (BABYLON = {}));
  17097. var __extends = this.__extends || function (d, b) {
  17098. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17099. function __() { this.constructor = d; }
  17100. __.prototype = b.prototype;
  17101. d.prototype = new __();
  17102. };
  17103. var BABYLON;
  17104. (function (BABYLON) {
  17105. var DisplayPassPostProcess = (function (_super) {
  17106. __extends(DisplayPassPostProcess, _super);
  17107. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17108. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17109. }
  17110. return DisplayPassPostProcess;
  17111. })(BABYLON.PostProcess);
  17112. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17113. })(BABYLON || (BABYLON = {}));
  17114. var BABYLON;
  17115. (function (BABYLON) {
  17116. var BoundingBoxRenderer = (function () {
  17117. function BoundingBoxRenderer(scene) {
  17118. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17119. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17120. this.showBackLines = true;
  17121. this.renderList = new BABYLON.SmartArray(32);
  17122. this._scene = scene;
  17123. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17124. attributes: ["position"],
  17125. uniforms: ["worldViewProjection", "color"]
  17126. });
  17127. var engine = this._scene.getEngine();
  17128. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17129. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17130. 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]);
  17131. }
  17132. BoundingBoxRenderer.prototype.reset = function () {
  17133. this.renderList.reset();
  17134. };
  17135. BoundingBoxRenderer.prototype.render = function () {
  17136. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17137. return;
  17138. }
  17139. var engine = this._scene.getEngine();
  17140. engine.setDepthWrite(false);
  17141. this._colorShader._preBind();
  17142. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17143. var boundingBox = this.renderList.data[boundingBoxIndex];
  17144. var min = boundingBox.minimum;
  17145. var max = boundingBox.maximum;
  17146. var diff = max.subtract(min);
  17147. var median = min.add(diff.scale(0.5));
  17148. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17149. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17150. if (this.showBackLines) {
  17151. engine.setDepthFunctionToGreaterOrEqual();
  17152. this._colorShader.setColor4("color", this.backColor.toColor4());
  17153. this._colorShader.bind(worldMatrix);
  17154. engine.draw(false, 0, 24);
  17155. }
  17156. engine.setDepthFunctionToLess();
  17157. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17158. this._colorShader.bind(worldMatrix);
  17159. engine.draw(false, 0, 24);
  17160. }
  17161. this._colorShader.unbind();
  17162. engine.setDepthFunctionToLessOrEqual();
  17163. engine.setDepthWrite(true);
  17164. };
  17165. BoundingBoxRenderer.prototype.dispose = function () {
  17166. this._colorShader.dispose();
  17167. this._vb.dispose();
  17168. this._scene.getEngine()._releaseBuffer(this._ib);
  17169. };
  17170. return BoundingBoxRenderer;
  17171. })();
  17172. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17173. })(BABYLON || (BABYLON = {}));
  17174. /**
  17175. * Based on jsTGALoader - Javascript loader for TGA file
  17176. * By Vincent Thibault
  17177. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17178. */
  17179. var BABYLON;
  17180. (function (BABYLON) {
  17181. (function (Internals) {
  17182. var TGATools = (function () {
  17183. function TGATools() {
  17184. }
  17185. TGATools.GetTGAHeader = function (data) {
  17186. var offset = 0;
  17187. var header = {
  17188. id_length: data[offset++],
  17189. colormap_type: data[offset++],
  17190. image_type: data[offset++],
  17191. colormap_index: data[offset++] | data[offset++] << 8,
  17192. colormap_length: data[offset++] | data[offset++] << 8,
  17193. colormap_size: data[offset++],
  17194. origin: [
  17195. data[offset++] | data[offset++] << 8,
  17196. data[offset++] | data[offset++] << 8
  17197. ],
  17198. width: data[offset++] | data[offset++] << 8,
  17199. height: data[offset++] | data[offset++] << 8,
  17200. pixel_size: data[offset++],
  17201. flags: data[offset++]
  17202. };
  17203. return header;
  17204. };
  17205. TGATools.UploadContent = function (gl, data) {
  17206. if (data.length < 19) {
  17207. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17208. return;
  17209. }
  17210. var offset = 18;
  17211. var header = TGATools.GetTGAHeader(data);
  17212. if (header.id_length + offset > data.length) {
  17213. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17214. return;
  17215. }
  17216. offset += header.id_length;
  17217. var use_rle = false;
  17218. var use_pal = false;
  17219. var use_rgb = false;
  17220. var use_grey = false;
  17221. switch (header.image_type) {
  17222. case TGATools._TYPE_RLE_INDEXED:
  17223. use_rle = true;
  17224. case TGATools._TYPE_INDEXED:
  17225. use_pal = true;
  17226. break;
  17227. case TGATools._TYPE_RLE_RGB:
  17228. use_rle = true;
  17229. case TGATools._TYPE_RGB:
  17230. use_rgb = true;
  17231. break;
  17232. case TGATools._TYPE_RLE_GREY:
  17233. use_rle = true;
  17234. case TGATools._TYPE_GREY:
  17235. use_grey = true;
  17236. break;
  17237. }
  17238. var pixel_data;
  17239. var numAlphaBits = header.flags & 0xf;
  17240. var pixel_size = header.pixel_size >> 3;
  17241. var pixel_total = header.width * header.height * pixel_size;
  17242. var palettes;
  17243. if (use_pal) {
  17244. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17245. }
  17246. if (use_rle) {
  17247. pixel_data = new Uint8Array(pixel_total);
  17248. var c, count, i;
  17249. var localOffset = 0;
  17250. var pixels = new Uint8Array(pixel_size);
  17251. while (offset < pixel_total) {
  17252. c = data[offset++];
  17253. count = (c & 0x7f) + 1;
  17254. if (c & 0x80) {
  17255. for (i = 0; i < pixel_size; ++i) {
  17256. pixels[i] = data[offset++];
  17257. }
  17258. for (i = 0; i < count; ++i) {
  17259. pixel_data.set(pixels, localOffset + i * pixel_size);
  17260. }
  17261. localOffset += pixel_size * count;
  17262. } else {
  17263. count *= pixel_size;
  17264. for (i = 0; i < count; ++i) {
  17265. pixel_data[localOffset + i] = data[offset++];
  17266. }
  17267. localOffset += count;
  17268. }
  17269. }
  17270. } else {
  17271. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17272. }
  17273. var x_start, y_start, x_step, y_step, y_end, x_end;
  17274. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17275. default:
  17276. case TGATools._ORIGIN_UL:
  17277. x_start = 0;
  17278. x_step = 1;
  17279. x_end = header.width;
  17280. y_start = 0;
  17281. y_step = 1;
  17282. y_end = header.height;
  17283. break;
  17284. case TGATools._ORIGIN_BL:
  17285. x_start = 0;
  17286. x_step = 1;
  17287. x_end = header.width;
  17288. y_start = header.height - 1;
  17289. y_step = -1;
  17290. y_end = -1;
  17291. break;
  17292. case TGATools._ORIGIN_UR:
  17293. x_start = header.width - 1;
  17294. x_step = -1;
  17295. x_end = -1;
  17296. y_start = 0;
  17297. y_step = 1;
  17298. y_end = header.height;
  17299. break;
  17300. case TGATools._ORIGIN_BR:
  17301. x_start = header.width - 1;
  17302. x_step = -1;
  17303. x_end = -1;
  17304. y_start = header.height - 1;
  17305. y_step = -1;
  17306. y_end = -1;
  17307. break;
  17308. }
  17309. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17310. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17311. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17312. };
  17313. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17314. var image = pixel_data, colormap = palettes;
  17315. var width = header.width, height = header.height;
  17316. var color, i = 0, x, y;
  17317. var imageData = new Uint8Array(width * height * 4);
  17318. for (y = y_start; y !== y_end; y += y_step) {
  17319. for (x = x_start; x !== x_end; x += x_step, i++) {
  17320. color = image[i];
  17321. imageData[(x + width * y) * 4 + 3] = 255;
  17322. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17323. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17324. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17325. }
  17326. }
  17327. return imageData;
  17328. };
  17329. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17330. var image = pixel_data;
  17331. var width = header.width, height = header.height;
  17332. var color, i = 0, x, y;
  17333. var imageData = new Uint8Array(width * height * 4);
  17334. for (y = y_start; y !== y_end; y += y_step) {
  17335. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17336. color = image[i + 0] + (image[i + 1] << 8);
  17337. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17338. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17339. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17340. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17341. }
  17342. }
  17343. return imageData;
  17344. };
  17345. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17346. var image = pixel_data;
  17347. var width = header.width, height = header.height;
  17348. var i = 0, x, y;
  17349. var imageData = new Uint8Array(width * height * 4);
  17350. for (y = y_start; y !== y_end; y += y_step) {
  17351. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17352. imageData[(x + width * y) * 4 + 3] = 255;
  17353. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17354. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17355. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17356. }
  17357. }
  17358. return imageData;
  17359. };
  17360. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17361. var image = pixel_data;
  17362. var width = header.width, height = header.height;
  17363. var i = 0, x, y;
  17364. var imageData = new Uint8Array(width * height * 4);
  17365. for (y = y_start; y !== y_end; y += y_step) {
  17366. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17367. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17368. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17369. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17370. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17371. }
  17372. }
  17373. return imageData;
  17374. };
  17375. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17376. var image = pixel_data;
  17377. var width = header.width, height = header.height;
  17378. var color, i = 0, x, y;
  17379. var imageData = new Uint8Array(width * height * 4);
  17380. for (y = y_start; y !== y_end; y += y_step) {
  17381. for (x = x_start; x !== x_end; x += x_step, i++) {
  17382. color = image[i];
  17383. imageData[(x + width * y) * 4 + 0] = color;
  17384. imageData[(x + width * y) * 4 + 1] = color;
  17385. imageData[(x + width * y) * 4 + 2] = color;
  17386. imageData[(x + width * y) * 4 + 3] = 255;
  17387. }
  17388. }
  17389. return imageData;
  17390. };
  17391. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17392. var image = pixel_data;
  17393. var width = header.width, height = header.height;
  17394. var i = 0, x, y;
  17395. var imageData = new Uint8Array(width * height * 4);
  17396. for (y = y_start; y !== y_end; y += y_step) {
  17397. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17398. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17399. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17400. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17401. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17402. }
  17403. }
  17404. return imageData;
  17405. };
  17406. TGATools._TYPE_NO_DATA = 0;
  17407. TGATools._TYPE_INDEXED = 1;
  17408. TGATools._TYPE_RGB = 2;
  17409. TGATools._TYPE_GREY = 3;
  17410. TGATools._TYPE_RLE_INDEXED = 9;
  17411. TGATools._TYPE_RLE_RGB = 10;
  17412. TGATools._TYPE_RLE_GREY = 11;
  17413. TGATools._ORIGIN_MASK = 0x30;
  17414. TGATools._ORIGIN_SHIFT = 0x04;
  17415. TGATools._ORIGIN_BL = 0x00;
  17416. TGATools._ORIGIN_BR = 0x01;
  17417. TGATools._ORIGIN_UL = 0x02;
  17418. TGATools._ORIGIN_UR = 0x03;
  17419. return TGATools;
  17420. })();
  17421. Internals.TGATools = TGATools;
  17422. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17423. var Internals = BABYLON.Internals;
  17424. })(BABYLON || (BABYLON = {}));
  17425. var BABYLON;
  17426. (function (BABYLON) {
  17427. (function (Internals) {
  17428. var DDS_MAGIC = 0x20534444;
  17429. 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;
  17430. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17431. 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;
  17432. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17433. function FourCCToInt32(value) {
  17434. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17435. }
  17436. function Int32ToFourCC(value) {
  17437. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17438. }
  17439. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17440. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17441. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17442. var headerLengthInt = 31;
  17443. var off_magic = 0;
  17444. var off_size = 1;
  17445. var off_flags = 2;
  17446. var off_height = 3;
  17447. var off_width = 4;
  17448. var off_mipmapCount = 7;
  17449. var off_pfFlags = 20;
  17450. var off_pfFourCC = 21;
  17451. var off_RGBbpp = 22;
  17452. var off_RMask = 23;
  17453. var off_GMask = 24;
  17454. var off_BMask = 25;
  17455. var off_AMask = 26;
  17456. var off_caps1 = 27;
  17457. var off_caps2 = 28;
  17458. ;
  17459. var DDSTools = (function () {
  17460. function DDSTools() {
  17461. }
  17462. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17463. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17464. var mipmapCount = 1;
  17465. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17466. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17467. }
  17468. return {
  17469. width: header[off_width],
  17470. height: header[off_height],
  17471. mipmapCount: mipmapCount,
  17472. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17473. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17474. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17475. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17476. };
  17477. };
  17478. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17479. var byteArray = new Uint8Array(dataLength);
  17480. var srcData = new Uint8Array(arrayBuffer);
  17481. var index = 0;
  17482. for (var y = height - 1; y >= 0; y--) {
  17483. for (var x = 0; x < width; x++) {
  17484. var srcPos = dataOffset + (x + y * width) * 4;
  17485. byteArray[index + 2] = srcData[srcPos];
  17486. byteArray[index + 1] = srcData[srcPos + 1];
  17487. byteArray[index] = srcData[srcPos + 2];
  17488. byteArray[index + 3] = srcData[srcPos + 3];
  17489. index += 4;
  17490. }
  17491. }
  17492. return byteArray;
  17493. };
  17494. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17495. var byteArray = new Uint8Array(dataLength);
  17496. var srcData = new Uint8Array(arrayBuffer);
  17497. var index = 0;
  17498. for (var y = height - 1; y >= 0; y--) {
  17499. for (var x = 0; x < width; x++) {
  17500. var srcPos = dataOffset + (x + y * width) * 3;
  17501. byteArray[index + 2] = srcData[srcPos];
  17502. byteArray[index + 1] = srcData[srcPos + 1];
  17503. byteArray[index] = srcData[srcPos + 2];
  17504. index += 3;
  17505. }
  17506. }
  17507. return byteArray;
  17508. };
  17509. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17510. var byteArray = new Uint8Array(dataLength);
  17511. var srcData = new Uint8Array(arrayBuffer);
  17512. var index = 0;
  17513. for (var y = height - 1; y >= 0; y--) {
  17514. for (var x = 0; x < width; x++) {
  17515. var srcPos = dataOffset + (x + y * width);
  17516. byteArray[index] = srcData[srcPos];
  17517. index++;
  17518. }
  17519. }
  17520. return byteArray;
  17521. };
  17522. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17523. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17524. if (header[off_magic] != DDS_MAGIC) {
  17525. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17526. return;
  17527. }
  17528. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17529. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17530. return;
  17531. }
  17532. if (info.isFourCC) {
  17533. fourCC = header[off_pfFourCC];
  17534. switch (fourCC) {
  17535. case FOURCC_DXT1:
  17536. blockBytes = 8;
  17537. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17538. break;
  17539. case FOURCC_DXT3:
  17540. blockBytes = 16;
  17541. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17542. break;
  17543. case FOURCC_DXT5:
  17544. blockBytes = 16;
  17545. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17546. break;
  17547. default:
  17548. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17549. return;
  17550. }
  17551. }
  17552. mipmapCount = 1;
  17553. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17554. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17555. }
  17556. var bpp = header[off_RGBbpp];
  17557. for (var face = 0; face < faces; face++) {
  17558. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17559. width = header[off_width];
  17560. height = header[off_height];
  17561. dataOffset = header[off_size] + 4;
  17562. for (i = 0; i < mipmapCount; ++i) {
  17563. if (info.isRGB) {
  17564. if (bpp == 24) {
  17565. dataLength = width * height * 3;
  17566. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17567. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17568. } else {
  17569. dataLength = width * height * 4;
  17570. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17571. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17572. }
  17573. } else if (info.isLuminance) {
  17574. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17575. var unpaddedRowSize = width;
  17576. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17577. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17578. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17579. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17580. } else {
  17581. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17582. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17583. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17584. }
  17585. dataOffset += dataLength;
  17586. width *= 0.5;
  17587. height *= 0.5;
  17588. width = Math.max(1.0, width);
  17589. height = Math.max(1.0, height);
  17590. }
  17591. }
  17592. };
  17593. return DDSTools;
  17594. })();
  17595. Internals.DDSTools = DDSTools;
  17596. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17597. var Internals = BABYLON.Internals;
  17598. })(BABYLON || (BABYLON = {}));
  17599. var BABYLON;
  17600. (function (BABYLON) {
  17601. var SmartArray = (function () {
  17602. function SmartArray(capacity) {
  17603. this.length = 0;
  17604. this._duplicateId = 0;
  17605. this.data = new Array(capacity);
  17606. this._id = SmartArray._GlobalId++;
  17607. }
  17608. SmartArray.prototype.push = function (value) {
  17609. this.data[this.length++] = value;
  17610. if (this.length > this.data.length) {
  17611. this.data.length *= 2;
  17612. }
  17613. if (!value.__smartArrayFlags) {
  17614. value.__smartArrayFlags = {};
  17615. }
  17616. value.__smartArrayFlags[this._id] = this._duplicateId;
  17617. };
  17618. SmartArray.prototype.pushNoDuplicate = function (value) {
  17619. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17620. return;
  17621. }
  17622. this.push(value);
  17623. };
  17624. SmartArray.prototype.sort = function (compareFn) {
  17625. this.data.sort(compareFn);
  17626. };
  17627. SmartArray.prototype.reset = function () {
  17628. this.length = 0;
  17629. this._duplicateId++;
  17630. };
  17631. SmartArray.prototype.concat = function (array) {
  17632. if (array.length === 0) {
  17633. return;
  17634. }
  17635. if (this.length + array.length > this.data.length) {
  17636. this.data.length = (this.length + array.length) * 2;
  17637. }
  17638. for (var index = 0; index < array.length; index++) {
  17639. this.data[this.length++] = (array.data || array)[index];
  17640. }
  17641. };
  17642. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17643. if (array.length === 0) {
  17644. return;
  17645. }
  17646. if (this.length + array.length > this.data.length) {
  17647. this.data.length = (this.length + array.length) * 2;
  17648. }
  17649. for (var index = 0; index < array.length; index++) {
  17650. var item = (array.data || array)[index];
  17651. this.pushNoDuplicate(item);
  17652. }
  17653. };
  17654. SmartArray.prototype.indexOf = function (value) {
  17655. var position = this.data.indexOf(value);
  17656. if (position >= this.length) {
  17657. return -1;
  17658. }
  17659. return position;
  17660. };
  17661. SmartArray._GlobalId = 0;
  17662. return SmartArray;
  17663. })();
  17664. BABYLON.SmartArray = SmartArray;
  17665. })(BABYLON || (BABYLON = {}));
  17666. var BABYLON;
  17667. (function (BABYLON) {
  17668. var CannonJSPlugin = (function () {
  17669. function CannonJSPlugin() {
  17670. this._registeredMeshes = [];
  17671. this._physicsMaterials = [];
  17672. this.updateBodyPosition = function (mesh) {
  17673. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17674. var registeredMesh = this._registeredMeshes[index];
  17675. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17676. var body = registeredMesh.body.body;
  17677. var center = mesh.getBoundingInfo().boundingBox.center;
  17678. body.position.set(center.x, center.z, center.y);
  17679. body.quaternion.x = mesh.rotationQuaternion.x;
  17680. body.quaternion.z = mesh.rotationQuaternion.y;
  17681. body.quaternion.y = mesh.rotationQuaternion.z;
  17682. body.quaternion.w = -mesh.rotationQuaternion.w;
  17683. return;
  17684. }
  17685. }
  17686. };
  17687. }
  17688. CannonJSPlugin.prototype.initialize = function (iterations) {
  17689. if (typeof iterations === "undefined") { iterations = 10; }
  17690. this._world = new CANNON.World();
  17691. this._world.broadphase = new CANNON.NaiveBroadphase();
  17692. this._world.solver.iterations = iterations;
  17693. };
  17694. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  17695. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17696. };
  17697. CannonJSPlugin.prototype.runOneStep = function (delta) {
  17698. this._world.step(delta);
  17699. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17700. var registeredMesh = this._registeredMeshes[index];
  17701. if (registeredMesh.isChild) {
  17702. continue;
  17703. }
  17704. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  17705. var deltaPos = registeredMesh.delta;
  17706. if (deltaPos) {
  17707. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  17708. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  17709. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  17710. } else {
  17711. registeredMesh.mesh.position.x = bodyX;
  17712. registeredMesh.mesh.position.y = bodyZ;
  17713. registeredMesh.mesh.position.z = bodyY;
  17714. }
  17715. if (!registeredMesh.mesh.rotationQuaternion) {
  17716. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17717. }
  17718. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  17719. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  17720. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  17721. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  17722. }
  17723. };
  17724. CannonJSPlugin.prototype.setGravity = function (gravity) {
  17725. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  17726. };
  17727. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17728. this.unregisterMesh(mesh);
  17729. mesh.computeWorldMatrix(true);
  17730. switch (impostor) {
  17731. case BABYLON.PhysicsEngine.SphereImpostor:
  17732. var bbox = mesh.getBoundingInfo().boundingBox;
  17733. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17734. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17735. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17736. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  17737. case BABYLON.PhysicsEngine.BoxImpostor:
  17738. bbox = mesh.getBoundingInfo().boundingBox;
  17739. var min = bbox.minimumWorld;
  17740. var max = bbox.maximumWorld;
  17741. var box = max.subtract(min).scale(0.5);
  17742. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  17743. case BABYLON.PhysicsEngine.PlaneImpostor:
  17744. return this._createPlane(mesh, options);
  17745. case BABYLON.PhysicsEngine.MeshImpostor:
  17746. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17747. var rawFaces = mesh.getIndices();
  17748. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  17749. }
  17750. return null;
  17751. };
  17752. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  17753. var shape = new CANNON.Sphere(radius);
  17754. if (!options) {
  17755. return shape;
  17756. }
  17757. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17758. };
  17759. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  17760. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  17761. if (!options) {
  17762. return shape;
  17763. }
  17764. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17765. };
  17766. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  17767. var shape = new CANNON.Plane();
  17768. if (!options) {
  17769. return shape;
  17770. }
  17771. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17772. };
  17773. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  17774. var verts = [], faces = [];
  17775. mesh.computeWorldMatrix(true);
  17776. for (var i = 0; i < rawVerts.length; i += 3) {
  17777. var transformed = BABYLON.Vector3.Zero();
  17778. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  17779. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  17780. }
  17781. for (var j = 0; j < rawFaces.length; j += 3) {
  17782. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  17783. }
  17784. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  17785. if (!options) {
  17786. return shape;
  17787. }
  17788. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17789. };
  17790. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  17791. var index;
  17792. var mat;
  17793. for (index = 0; index < this._physicsMaterials.length; index++) {
  17794. mat = this._physicsMaterials[index];
  17795. if (mat.friction === friction && mat.restitution === restitution) {
  17796. return mat;
  17797. }
  17798. }
  17799. var currentMat = new CANNON.Material();
  17800. currentMat.friction = friction;
  17801. currentMat.restitution = restitution;
  17802. this._physicsMaterials.push(currentMat);
  17803. for (index = 0; index < this._physicsMaterials.length; index++) {
  17804. mat = this._physicsMaterials[index];
  17805. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  17806. contactMaterial.contactEquationStiffness = 1e10;
  17807. contactMaterial.contactEquationRegularizationTime = 10;
  17808. this._world.addContactMaterial(contactMaterial);
  17809. }
  17810. return currentMat;
  17811. };
  17812. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  17813. var initialRotation = null;
  17814. if (mesh.rotationQuaternion) {
  17815. initialRotation = mesh.rotationQuaternion.clone();
  17816. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17817. }
  17818. var bbox = mesh.getBoundingInfo().boundingBox;
  17819. var deltaPosition = mesh.position.subtract(bbox.center);
  17820. var material = this._addMaterial(friction, restitution);
  17821. var body = new CANNON.RigidBody(mass, shape, material);
  17822. if (initialRotation) {
  17823. body.quaternion.x = initialRotation.x;
  17824. body.quaternion.z = initialRotation.y;
  17825. body.quaternion.y = initialRotation.z;
  17826. body.quaternion.w = -initialRotation.w;
  17827. }
  17828. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  17829. this._world.add(body);
  17830. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  17831. return body;
  17832. };
  17833. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17834. var compoundShape = new CANNON.Compound();
  17835. for (var index = 0; index < parts.length; index++) {
  17836. var mesh = parts[index].mesh;
  17837. var shape = this.registerMesh(mesh, parts[index].impostor);
  17838. if (index == 0) {
  17839. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  17840. } else {
  17841. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  17842. }
  17843. }
  17844. var initialMesh = parts[0].mesh;
  17845. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  17846. body.parts = parts;
  17847. return body;
  17848. };
  17849. CannonJSPlugin.prototype._unbindBody = function (body) {
  17850. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17851. var registeredMesh = this._registeredMeshes[index];
  17852. if (registeredMesh.body === body) {
  17853. registeredMesh.body = null;
  17854. registeredMesh.delta = 0;
  17855. }
  17856. }
  17857. };
  17858. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  17859. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17860. var registeredMesh = this._registeredMeshes[index];
  17861. if (registeredMesh.mesh === mesh) {
  17862. if (registeredMesh.body) {
  17863. this._world.remove(registeredMesh.body);
  17864. this._unbindBody(registeredMesh.body);
  17865. }
  17866. this._registeredMeshes.splice(index, 1);
  17867. return;
  17868. }
  17869. }
  17870. };
  17871. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17872. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  17873. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  17874. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17875. var registeredMesh = this._registeredMeshes[index];
  17876. if (registeredMesh.mesh === mesh) {
  17877. registeredMesh.body.applyImpulse(impulse, worldPoint);
  17878. return;
  17879. }
  17880. }
  17881. };
  17882. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  17883. var body1 = null, body2 = null;
  17884. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17885. var registeredMesh = this._registeredMeshes[index];
  17886. if (registeredMesh.mesh === mesh1) {
  17887. body1 = registeredMesh.body;
  17888. } else if (registeredMesh.mesh === mesh2) {
  17889. body2 = registeredMesh.body;
  17890. }
  17891. }
  17892. if (!body1 || !body2) {
  17893. return false;
  17894. }
  17895. 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));
  17896. this._world.addConstraint(constraint);
  17897. return true;
  17898. };
  17899. CannonJSPlugin.prototype.dispose = function () {
  17900. while (this._registeredMeshes.length) {
  17901. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17902. }
  17903. };
  17904. CannonJSPlugin.prototype.isSupported = function () {
  17905. return window.CANNON !== undefined;
  17906. };
  17907. return CannonJSPlugin;
  17908. })();
  17909. BABYLON.CannonJSPlugin = CannonJSPlugin;
  17910. })(BABYLON || (BABYLON = {}));
  17911. var __extends = this.__extends || function (d, b) {
  17912. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17913. function __() { this.constructor = d; }
  17914. __.prototype = b.prototype;
  17915. d.prototype = new __();
  17916. };
  17917. var BABYLON;
  17918. (function (BABYLON) {
  17919. var Condition = (function () {
  17920. function Condition(actionManager) {
  17921. this._actionManager = actionManager;
  17922. }
  17923. Condition.prototype.isValid = function () {
  17924. return true;
  17925. };
  17926. Condition.prototype._getProperty = function (propertyPath) {
  17927. return this._actionManager._getProperty(propertyPath);
  17928. };
  17929. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  17930. return this._actionManager._getEffectiveTarget(target, propertyPath);
  17931. };
  17932. return Condition;
  17933. })();
  17934. BABYLON.Condition = Condition;
  17935. var ValueCondition = (function (_super) {
  17936. __extends(ValueCondition, _super);
  17937. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  17938. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  17939. _super.call(this, actionManager);
  17940. this.propertyPath = propertyPath;
  17941. this.value = value;
  17942. this.operator = operator;
  17943. this._target = this._getEffectiveTarget(target, this.propertyPath);
  17944. this._property = this._getProperty(this.propertyPath);
  17945. }
  17946. Object.defineProperty(ValueCondition, "IsEqual", {
  17947. get: function () {
  17948. return ValueCondition._IsEqual;
  17949. },
  17950. enumerable: true,
  17951. configurable: true
  17952. });
  17953. Object.defineProperty(ValueCondition, "IsDifferent", {
  17954. get: function () {
  17955. return ValueCondition._IsDifferent;
  17956. },
  17957. enumerable: true,
  17958. configurable: true
  17959. });
  17960. Object.defineProperty(ValueCondition, "IsGreater", {
  17961. get: function () {
  17962. return ValueCondition._IsGreater;
  17963. },
  17964. enumerable: true,
  17965. configurable: true
  17966. });
  17967. Object.defineProperty(ValueCondition, "IsLesser", {
  17968. get: function () {
  17969. return ValueCondition._IsLesser;
  17970. },
  17971. enumerable: true,
  17972. configurable: true
  17973. });
  17974. ValueCondition.prototype.isValid = function () {
  17975. switch (this.operator) {
  17976. case ValueCondition.IsGreater:
  17977. return this._target[this._property] > this.value;
  17978. case ValueCondition.IsLesser:
  17979. return this._target[this._property] < this.value;
  17980. case ValueCondition.IsEqual:
  17981. case ValueCondition.IsDifferent:
  17982. var check;
  17983. if (this.value.equals) {
  17984. check = this.value.equals(this._target[this._property]);
  17985. } else {
  17986. check = this.value === this._target[this._property];
  17987. }
  17988. return this.operator === ValueCondition.IsEqual ? check : !check;
  17989. }
  17990. return false;
  17991. };
  17992. ValueCondition._IsEqual = 0;
  17993. ValueCondition._IsDifferent = 1;
  17994. ValueCondition._IsGreater = 2;
  17995. ValueCondition._IsLesser = 3;
  17996. return ValueCondition;
  17997. })(Condition);
  17998. BABYLON.ValueCondition = ValueCondition;
  17999. var PredicateCondition = (function (_super) {
  18000. __extends(PredicateCondition, _super);
  18001. function PredicateCondition(actionManager, predicate) {
  18002. _super.call(this, actionManager);
  18003. this.predicate = predicate;
  18004. }
  18005. PredicateCondition.prototype.isValid = function () {
  18006. return this.predicate();
  18007. };
  18008. return PredicateCondition;
  18009. })(Condition);
  18010. BABYLON.PredicateCondition = PredicateCondition;
  18011. var StateCondition = (function (_super) {
  18012. __extends(StateCondition, _super);
  18013. function StateCondition(actionManager, target, value) {
  18014. _super.call(this, actionManager);
  18015. this.value = value;
  18016. this._target = target;
  18017. }
  18018. StateCondition.prototype.isValid = function () {
  18019. return this._target.state === this.value;
  18020. };
  18021. return StateCondition;
  18022. })(Condition);
  18023. BABYLON.StateCondition = StateCondition;
  18024. })(BABYLON || (BABYLON = {}));
  18025. var BABYLON;
  18026. (function (BABYLON) {
  18027. var Action = (function () {
  18028. function Action(triggerOptions, condition) {
  18029. this.triggerOptions = triggerOptions;
  18030. if (triggerOptions.parameter) {
  18031. this.trigger = triggerOptions.trigger;
  18032. this._triggerParameter = triggerOptions.parameter;
  18033. } else {
  18034. this.trigger = triggerOptions;
  18035. }
  18036. this._nextActiveAction = this;
  18037. this._condition = condition;
  18038. }
  18039. Action.prototype._prepare = function () {
  18040. };
  18041. Action.prototype.getTriggerParameter = function () {
  18042. return this._triggerParameter;
  18043. };
  18044. Action.prototype._executeCurrent = function (evt) {
  18045. if (this._condition) {
  18046. var currentRenderId = this._actionManager.getScene().getRenderId();
  18047. if (this._condition._evaluationId === currentRenderId) {
  18048. if (!this._condition._currentResult) {
  18049. return;
  18050. }
  18051. } else {
  18052. this._condition._evaluationId = currentRenderId;
  18053. if (!this._condition.isValid()) {
  18054. this._condition._currentResult = false;
  18055. return;
  18056. }
  18057. this._condition._currentResult = true;
  18058. }
  18059. }
  18060. this._nextActiveAction.execute(evt);
  18061. if (this._nextActiveAction._child) {
  18062. this._nextActiveAction = this._nextActiveAction._child;
  18063. } else {
  18064. this._nextActiveAction = this;
  18065. }
  18066. };
  18067. Action.prototype.execute = function (evt) {
  18068. };
  18069. Action.prototype.then = function (action) {
  18070. this._child = action;
  18071. action._actionManager = this._actionManager;
  18072. action._prepare();
  18073. return action;
  18074. };
  18075. Action.prototype._getProperty = function (propertyPath) {
  18076. return this._actionManager._getProperty(propertyPath);
  18077. };
  18078. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18079. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18080. };
  18081. return Action;
  18082. })();
  18083. BABYLON.Action = Action;
  18084. })(BABYLON || (BABYLON = {}));
  18085. var BABYLON;
  18086. (function (BABYLON) {
  18087. var ActionEvent = (function () {
  18088. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18089. this.source = source;
  18090. this.pointerX = pointerX;
  18091. this.pointerY = pointerY;
  18092. this.meshUnderPointer = meshUnderPointer;
  18093. this.sourceEvent = sourceEvent;
  18094. }
  18095. ActionEvent.CreateNew = function (source) {
  18096. var scene = source.getScene();
  18097. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18098. };
  18099. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18100. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18101. };
  18102. return ActionEvent;
  18103. })();
  18104. BABYLON.ActionEvent = ActionEvent;
  18105. var ActionManager = (function () {
  18106. function ActionManager(scene) {
  18107. this.actions = new Array();
  18108. this._scene = scene;
  18109. scene._actionManagers.push(this);
  18110. }
  18111. Object.defineProperty(ActionManager, "NothingTrigger", {
  18112. get: function () {
  18113. return ActionManager._NothingTrigger;
  18114. },
  18115. enumerable: true,
  18116. configurable: true
  18117. });
  18118. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18119. get: function () {
  18120. return ActionManager._OnPickTrigger;
  18121. },
  18122. enumerable: true,
  18123. configurable: true
  18124. });
  18125. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18126. get: function () {
  18127. return ActionManager._OnLeftPickTrigger;
  18128. },
  18129. enumerable: true,
  18130. configurable: true
  18131. });
  18132. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18133. get: function () {
  18134. return ActionManager._OnRightPickTrigger;
  18135. },
  18136. enumerable: true,
  18137. configurable: true
  18138. });
  18139. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18140. get: function () {
  18141. return ActionManager._OnCenterPickTrigger;
  18142. },
  18143. enumerable: true,
  18144. configurable: true
  18145. });
  18146. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18147. get: function () {
  18148. return ActionManager._OnPointerOverTrigger;
  18149. },
  18150. enumerable: true,
  18151. configurable: true
  18152. });
  18153. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18154. get: function () {
  18155. return ActionManager._OnPointerOutTrigger;
  18156. },
  18157. enumerable: true,
  18158. configurable: true
  18159. });
  18160. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18161. get: function () {
  18162. return ActionManager._OnEveryFrameTrigger;
  18163. },
  18164. enumerable: true,
  18165. configurable: true
  18166. });
  18167. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18168. get: function () {
  18169. return ActionManager._OnIntersectionEnterTrigger;
  18170. },
  18171. enumerable: true,
  18172. configurable: true
  18173. });
  18174. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18175. get: function () {
  18176. return ActionManager._OnIntersectionExitTrigger;
  18177. },
  18178. enumerable: true,
  18179. configurable: true
  18180. });
  18181. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18182. get: function () {
  18183. return ActionManager._OnKeyDownTrigger;
  18184. },
  18185. enumerable: true,
  18186. configurable: true
  18187. });
  18188. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18189. get: function () {
  18190. return ActionManager._OnKeyUpTrigger;
  18191. },
  18192. enumerable: true,
  18193. configurable: true
  18194. });
  18195. ActionManager.prototype.dispose = function () {
  18196. var index = this._scene._actionManagers.indexOf(this);
  18197. if (index > -1) {
  18198. this._scene._actionManagers.splice(index, 1);
  18199. }
  18200. };
  18201. ActionManager.prototype.getScene = function () {
  18202. return this._scene;
  18203. };
  18204. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18205. for (var index = 0; index < this.actions.length; index++) {
  18206. var action = this.actions[index];
  18207. if (triggers.indexOf(action.trigger) > -1) {
  18208. return true;
  18209. }
  18210. }
  18211. return false;
  18212. };
  18213. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18214. get: function () {
  18215. for (var index = 0; index < this.actions.length; index++) {
  18216. var action = this.actions[index];
  18217. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18218. return true;
  18219. }
  18220. }
  18221. return false;
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18227. get: function () {
  18228. for (var index = 0; index < this.actions.length; index++) {
  18229. var action = this.actions[index];
  18230. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18231. return true;
  18232. }
  18233. }
  18234. return false;
  18235. },
  18236. enumerable: true,
  18237. configurable: true
  18238. });
  18239. ActionManager.prototype.registerAction = function (action) {
  18240. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18241. if (this.getScene().actionManager !== this) {
  18242. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18243. return null;
  18244. }
  18245. }
  18246. this.actions.push(action);
  18247. action._actionManager = this;
  18248. action._prepare();
  18249. return action;
  18250. };
  18251. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18252. for (var index = 0; index < this.actions.length; index++) {
  18253. var action = this.actions[index];
  18254. if (action.trigger === trigger) {
  18255. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18256. var parameter = action.getTriggerParameter();
  18257. if (parameter) {
  18258. if (evt.sourceEvent.key !== parameter) {
  18259. continue;
  18260. }
  18261. }
  18262. }
  18263. action._executeCurrent(evt);
  18264. }
  18265. }
  18266. };
  18267. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18268. var properties = propertyPath.split(".");
  18269. for (var index = 0; index < properties.length - 1; index++) {
  18270. target = target[properties[index]];
  18271. }
  18272. return target;
  18273. };
  18274. ActionManager.prototype._getProperty = function (propertyPath) {
  18275. var properties = propertyPath.split(".");
  18276. return properties[properties.length - 1];
  18277. };
  18278. ActionManager._NothingTrigger = 0;
  18279. ActionManager._OnPickTrigger = 1;
  18280. ActionManager._OnLeftPickTrigger = 2;
  18281. ActionManager._OnRightPickTrigger = 3;
  18282. ActionManager._OnCenterPickTrigger = 4;
  18283. ActionManager._OnPointerOverTrigger = 5;
  18284. ActionManager._OnPointerOutTrigger = 6;
  18285. ActionManager._OnEveryFrameTrigger = 7;
  18286. ActionManager._OnIntersectionEnterTrigger = 8;
  18287. ActionManager._OnIntersectionExitTrigger = 9;
  18288. ActionManager._OnKeyDownTrigger = 10;
  18289. ActionManager._OnKeyUpTrigger = 11;
  18290. return ActionManager;
  18291. })();
  18292. BABYLON.ActionManager = ActionManager;
  18293. })(BABYLON || (BABYLON = {}));
  18294. var __extends = this.__extends || function (d, b) {
  18295. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18296. function __() { this.constructor = d; }
  18297. __.prototype = b.prototype;
  18298. d.prototype = new __();
  18299. };
  18300. var BABYLON;
  18301. (function (BABYLON) {
  18302. var InterpolateValueAction = (function (_super) {
  18303. __extends(InterpolateValueAction, _super);
  18304. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18305. if (typeof duration === "undefined") { duration = 1000; }
  18306. _super.call(this, triggerOptions, condition);
  18307. this.propertyPath = propertyPath;
  18308. this.value = value;
  18309. this.duration = duration;
  18310. this.stopOtherAnimations = stopOtherAnimations;
  18311. this._target = target;
  18312. }
  18313. InterpolateValueAction.prototype._prepare = function () {
  18314. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18315. this._property = this._getProperty(this.propertyPath);
  18316. };
  18317. InterpolateValueAction.prototype.execute = function () {
  18318. var scene = this._actionManager.getScene();
  18319. var keys = [
  18320. {
  18321. frame: 0,
  18322. value: this._target[this._property]
  18323. }, {
  18324. frame: 100,
  18325. value: this.value
  18326. }
  18327. ];
  18328. var dataType;
  18329. if (typeof this.value === "number") {
  18330. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18331. } else if (this.value instanceof BABYLON.Color3) {
  18332. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18333. } else if (this.value instanceof BABYLON.Vector3) {
  18334. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18335. } else if (this.value instanceof BABYLON.Matrix) {
  18336. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18337. } else if (this.value instanceof BABYLON.Quaternion) {
  18338. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18339. } else {
  18340. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18341. return;
  18342. }
  18343. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18344. animation.setKeys(keys);
  18345. if (this.stopOtherAnimations) {
  18346. scene.stopAnimation(this._target);
  18347. }
  18348. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18349. };
  18350. return InterpolateValueAction;
  18351. })(BABYLON.Action);
  18352. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18353. })(BABYLON || (BABYLON = {}));
  18354. var __extends = this.__extends || function (d, b) {
  18355. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18356. function __() { this.constructor = d; }
  18357. __.prototype = b.prototype;
  18358. d.prototype = new __();
  18359. };
  18360. var BABYLON;
  18361. (function (BABYLON) {
  18362. var SwitchBooleanAction = (function (_super) {
  18363. __extends(SwitchBooleanAction, _super);
  18364. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18365. _super.call(this, triggerOptions, condition);
  18366. this.propertyPath = propertyPath;
  18367. this._target = target;
  18368. }
  18369. SwitchBooleanAction.prototype._prepare = function () {
  18370. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18371. this._property = this._getProperty(this.propertyPath);
  18372. };
  18373. SwitchBooleanAction.prototype.execute = function () {
  18374. this._target[this._property] = !this._target[this._property];
  18375. };
  18376. return SwitchBooleanAction;
  18377. })(BABYLON.Action);
  18378. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18379. var SetStateAction = (function (_super) {
  18380. __extends(SetStateAction, _super);
  18381. function SetStateAction(triggerOptions, target, value, condition) {
  18382. _super.call(this, triggerOptions, condition);
  18383. this.value = value;
  18384. this._target = target;
  18385. }
  18386. SetStateAction.prototype.execute = function () {
  18387. this._target.state = this.value;
  18388. };
  18389. return SetStateAction;
  18390. })(BABYLON.Action);
  18391. BABYLON.SetStateAction = SetStateAction;
  18392. var SetValueAction = (function (_super) {
  18393. __extends(SetValueAction, _super);
  18394. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18395. _super.call(this, triggerOptions, condition);
  18396. this.propertyPath = propertyPath;
  18397. this.value = value;
  18398. this._target = target;
  18399. }
  18400. SetValueAction.prototype._prepare = function () {
  18401. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18402. this._property = this._getProperty(this.propertyPath);
  18403. };
  18404. SetValueAction.prototype.execute = function () {
  18405. this._target[this._property] = this.value;
  18406. };
  18407. return SetValueAction;
  18408. })(BABYLON.Action);
  18409. BABYLON.SetValueAction = SetValueAction;
  18410. var IncrementValueAction = (function (_super) {
  18411. __extends(IncrementValueAction, _super);
  18412. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18413. _super.call(this, triggerOptions, condition);
  18414. this.propertyPath = propertyPath;
  18415. this.value = value;
  18416. this._target = target;
  18417. }
  18418. IncrementValueAction.prototype._prepare = function () {
  18419. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18420. this._property = this._getProperty(this.propertyPath);
  18421. if (typeof this._target[this._property] !== "number") {
  18422. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18423. }
  18424. };
  18425. IncrementValueAction.prototype.execute = function () {
  18426. this._target[this._property] += this.value;
  18427. };
  18428. return IncrementValueAction;
  18429. })(BABYLON.Action);
  18430. BABYLON.IncrementValueAction = IncrementValueAction;
  18431. var PlayAnimationAction = (function (_super) {
  18432. __extends(PlayAnimationAction, _super);
  18433. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18434. _super.call(this, triggerOptions, condition);
  18435. this.from = from;
  18436. this.to = to;
  18437. this.loop = loop;
  18438. this._target = target;
  18439. }
  18440. PlayAnimationAction.prototype._prepare = function () {
  18441. };
  18442. PlayAnimationAction.prototype.execute = function () {
  18443. var scene = this._actionManager.getScene();
  18444. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18445. };
  18446. return PlayAnimationAction;
  18447. })(BABYLON.Action);
  18448. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18449. var StopAnimationAction = (function (_super) {
  18450. __extends(StopAnimationAction, _super);
  18451. function StopAnimationAction(triggerOptions, target, condition) {
  18452. _super.call(this, triggerOptions, condition);
  18453. this._target = target;
  18454. }
  18455. StopAnimationAction.prototype._prepare = function () {
  18456. };
  18457. StopAnimationAction.prototype.execute = function () {
  18458. var scene = this._actionManager.getScene();
  18459. scene.stopAnimation(this._target);
  18460. };
  18461. return StopAnimationAction;
  18462. })(BABYLON.Action);
  18463. BABYLON.StopAnimationAction = StopAnimationAction;
  18464. var DoNothingAction = (function (_super) {
  18465. __extends(DoNothingAction, _super);
  18466. function DoNothingAction(triggerOptions, condition) {
  18467. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18468. _super.call(this, triggerOptions, condition);
  18469. }
  18470. DoNothingAction.prototype.execute = function () {
  18471. };
  18472. return DoNothingAction;
  18473. })(BABYLON.Action);
  18474. BABYLON.DoNothingAction = DoNothingAction;
  18475. var CombineAction = (function (_super) {
  18476. __extends(CombineAction, _super);
  18477. function CombineAction(triggerOptions, children, condition) {
  18478. _super.call(this, triggerOptions, condition);
  18479. this.children = children;
  18480. }
  18481. CombineAction.prototype._prepare = function () {
  18482. for (var index = 0; index < this.children.length; index++) {
  18483. this.children[index]._actionManager = this._actionManager;
  18484. this.children[index]._prepare();
  18485. }
  18486. };
  18487. CombineAction.prototype.execute = function (evt) {
  18488. for (var index = 0; index < this.children.length; index++) {
  18489. this.children[index].execute(evt);
  18490. }
  18491. };
  18492. return CombineAction;
  18493. })(BABYLON.Action);
  18494. BABYLON.CombineAction = CombineAction;
  18495. var ExecuteCodeAction = (function (_super) {
  18496. __extends(ExecuteCodeAction, _super);
  18497. function ExecuteCodeAction(triggerOptions, func, condition) {
  18498. _super.call(this, triggerOptions, condition);
  18499. this.func = func;
  18500. }
  18501. ExecuteCodeAction.prototype.execute = function (evt) {
  18502. this.func(evt);
  18503. };
  18504. return ExecuteCodeAction;
  18505. })(BABYLON.Action);
  18506. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18507. var SetParentAction = (function (_super) {
  18508. __extends(SetParentAction, _super);
  18509. function SetParentAction(triggerOptions, target, parent, condition) {
  18510. _super.call(this, triggerOptions, condition);
  18511. this._target = target;
  18512. this._parent = parent;
  18513. }
  18514. SetParentAction.prototype._prepare = function () {
  18515. };
  18516. SetParentAction.prototype.execute = function () {
  18517. if (this._target.parent === this._parent) {
  18518. return;
  18519. }
  18520. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18521. invertParentWorldMatrix.invert();
  18522. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18523. this._target.parent = this._parent;
  18524. };
  18525. return SetParentAction;
  18526. })(BABYLON.Action);
  18527. BABYLON.SetParentAction = SetParentAction;
  18528. })(BABYLON || (BABYLON = {}));
  18529. var __extends = this.__extends || function (d, b) {
  18530. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18531. function __() { this.constructor = d; }
  18532. __.prototype = b.prototype;
  18533. d.prototype = new __();
  18534. };
  18535. var BABYLON;
  18536. (function (BABYLON) {
  18537. var Geometry = (function () {
  18538. function Geometry(id, scene, vertexData, updatable, mesh) {
  18539. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18540. this._totalVertices = 0;
  18541. this._indices = [];
  18542. this.id = id;
  18543. this._engine = scene.getEngine();
  18544. this._meshes = [];
  18545. this._scene = scene;
  18546. if (vertexData) {
  18547. this.setAllVerticesData(vertexData, updatable);
  18548. } else {
  18549. this._totalVertices = 0;
  18550. this._indices = [];
  18551. }
  18552. if (mesh) {
  18553. this.applyToMesh(mesh);
  18554. }
  18555. }
  18556. Geometry.prototype.getScene = function () {
  18557. return this._scene;
  18558. };
  18559. Geometry.prototype.getEngine = function () {
  18560. return this._engine;
  18561. };
  18562. Geometry.prototype.isReady = function () {
  18563. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18564. };
  18565. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18566. vertexData.applyToGeometry(this, updatable);
  18567. };
  18568. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18569. this._vertexBuffers = this._vertexBuffers || {};
  18570. if (this._vertexBuffers[kind]) {
  18571. this._vertexBuffers[kind].dispose();
  18572. }
  18573. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18574. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18575. var stride = this._vertexBuffers[kind].getStrideSize();
  18576. this._totalVertices = data.length / stride;
  18577. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18578. var meshes = this._meshes;
  18579. var numOfMeshes = meshes.length;
  18580. for (var index = 0; index < numOfMeshes; index++) {
  18581. var mesh = meshes[index];
  18582. mesh._resetPointsArrayCache();
  18583. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18584. mesh._createGlobalSubMesh();
  18585. mesh.computeWorldMatrix(true);
  18586. }
  18587. }
  18588. };
  18589. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18590. var vertexBuffer = this.getVertexBuffer(kind);
  18591. if (!vertexBuffer) {
  18592. return;
  18593. }
  18594. vertexBuffer.update(data);
  18595. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18596. var extend;
  18597. if (updateExtends) {
  18598. var stride = vertexBuffer.getStrideSize();
  18599. this._totalVertices = data.length / stride;
  18600. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18601. }
  18602. var meshes = this._meshes;
  18603. var numOfMeshes = meshes.length;
  18604. for (var index = 0; index < numOfMeshes; index++) {
  18605. var mesh = meshes[index];
  18606. mesh._resetPointsArrayCache();
  18607. if (updateExtends) {
  18608. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18609. }
  18610. }
  18611. }
  18612. };
  18613. Geometry.prototype.getTotalVertices = function () {
  18614. if (!this.isReady()) {
  18615. return 0;
  18616. }
  18617. return this._totalVertices;
  18618. };
  18619. Geometry.prototype.getVerticesData = function (kind) {
  18620. var vertexBuffer = this.getVertexBuffer(kind);
  18621. if (!vertexBuffer) {
  18622. return null;
  18623. }
  18624. return vertexBuffer.getData();
  18625. };
  18626. Geometry.prototype.getVertexBuffer = function (kind) {
  18627. if (!this.isReady()) {
  18628. return null;
  18629. }
  18630. return this._vertexBuffers[kind];
  18631. };
  18632. Geometry.prototype.getVertexBuffers = function () {
  18633. if (!this.isReady()) {
  18634. return null;
  18635. }
  18636. return this._vertexBuffers;
  18637. };
  18638. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18639. if (!this._vertexBuffers) {
  18640. if (this._delayInfo) {
  18641. return this._delayInfo.indexOf(kind) !== -1;
  18642. }
  18643. return false;
  18644. }
  18645. return this._vertexBuffers[kind] !== undefined;
  18646. };
  18647. Geometry.prototype.getVerticesDataKinds = function () {
  18648. var result = [];
  18649. if (!this._vertexBuffers && this._delayInfo) {
  18650. for (var kind in this._delayInfo) {
  18651. result.push(kind);
  18652. }
  18653. } else {
  18654. for (kind in this._vertexBuffers) {
  18655. result.push(kind);
  18656. }
  18657. }
  18658. return result;
  18659. };
  18660. Geometry.prototype.setIndices = function (indices) {
  18661. if (this._indexBuffer) {
  18662. this._engine._releaseBuffer(this._indexBuffer);
  18663. }
  18664. this._indices = indices;
  18665. if (this._meshes.length !== 0 && this._indices) {
  18666. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18667. }
  18668. var meshes = this._meshes;
  18669. var numOfMeshes = meshes.length;
  18670. for (var index = 0; index < numOfMeshes; index++) {
  18671. meshes[index]._createGlobalSubMesh();
  18672. }
  18673. };
  18674. Geometry.prototype.getTotalIndices = function () {
  18675. if (!this.isReady()) {
  18676. return 0;
  18677. }
  18678. return this._indices.length;
  18679. };
  18680. Geometry.prototype.getIndices = function () {
  18681. if (!this.isReady()) {
  18682. return null;
  18683. }
  18684. return this._indices;
  18685. };
  18686. Geometry.prototype.getIndexBuffer = function () {
  18687. if (!this.isReady()) {
  18688. return null;
  18689. }
  18690. return this._indexBuffer;
  18691. };
  18692. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  18693. var meshes = this._meshes;
  18694. var index = meshes.indexOf(mesh);
  18695. if (index === -1) {
  18696. return;
  18697. }
  18698. for (var kind in this._vertexBuffers) {
  18699. this._vertexBuffers[kind].dispose();
  18700. }
  18701. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  18702. this._indexBuffer = null;
  18703. }
  18704. meshes.splice(index, 1);
  18705. mesh._geometry = null;
  18706. if (meshes.length == 0 && shouldDispose) {
  18707. this.dispose();
  18708. }
  18709. };
  18710. Geometry.prototype.applyToMesh = function (mesh) {
  18711. if (mesh._geometry === this) {
  18712. return;
  18713. }
  18714. var previousGeometry = mesh._geometry;
  18715. if (previousGeometry) {
  18716. previousGeometry.releaseForMesh(mesh);
  18717. }
  18718. var meshes = this._meshes;
  18719. mesh._geometry = this;
  18720. this._scene.pushGeometry(this);
  18721. meshes.push(mesh);
  18722. if (this.isReady()) {
  18723. this._applyToMesh(mesh);
  18724. } else {
  18725. mesh._boundingInfo = this._boundingInfo;
  18726. }
  18727. };
  18728. Geometry.prototype._applyToMesh = function (mesh) {
  18729. var numOfMeshes = this._meshes.length;
  18730. for (var kind in this._vertexBuffers) {
  18731. if (numOfMeshes === 1) {
  18732. this._vertexBuffers[kind].create();
  18733. }
  18734. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  18735. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18736. mesh._resetPointsArrayCache();
  18737. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  18738. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18739. mesh._createGlobalSubMesh();
  18740. }
  18741. }
  18742. if (numOfMeshes === 1 && this._indices) {
  18743. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18744. }
  18745. if (this._indexBuffer) {
  18746. this._indexBuffer.references = numOfMeshes;
  18747. }
  18748. };
  18749. Geometry.prototype.load = function (scene, onLoaded) {
  18750. var _this = this;
  18751. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18752. return;
  18753. }
  18754. if (this.isReady()) {
  18755. if (onLoaded) {
  18756. onLoaded();
  18757. }
  18758. return;
  18759. }
  18760. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18761. scene._addPendingData(this);
  18762. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18763. _this._delayLoadingFunction(JSON.parse(data), _this);
  18764. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18765. _this._delayInfo = [];
  18766. scene._removePendingData(_this);
  18767. var meshes = _this._meshes;
  18768. var numOfMeshes = meshes.length;
  18769. for (var index = 0; index < numOfMeshes; index++) {
  18770. _this._applyToMesh(meshes[index]);
  18771. }
  18772. if (onLoaded) {
  18773. onLoaded();
  18774. }
  18775. }, function () {
  18776. }, scene.database);
  18777. };
  18778. Geometry.prototype.dispose = function () {
  18779. var meshes = this._meshes;
  18780. var numOfMeshes = meshes.length;
  18781. for (var index = 0; index < numOfMeshes; index++) {
  18782. this.releaseForMesh(meshes[index]);
  18783. }
  18784. this._meshes = [];
  18785. for (var kind in this._vertexBuffers) {
  18786. this._vertexBuffers[kind].dispose();
  18787. }
  18788. this._vertexBuffers = [];
  18789. this._totalVertices = 0;
  18790. if (this._indexBuffer) {
  18791. this._engine._releaseBuffer(this._indexBuffer);
  18792. }
  18793. this._indexBuffer = null;
  18794. this._indices = [];
  18795. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18796. this.delayLoadingFile = null;
  18797. this._delayLoadingFunction = null;
  18798. this._delayInfo = [];
  18799. this._boundingInfo = null;
  18800. var geometries = this._scene.getGeometries();
  18801. index = geometries.indexOf(this);
  18802. if (index > -1) {
  18803. geometries.splice(index, 1);
  18804. }
  18805. };
  18806. Geometry.prototype.copy = function (id) {
  18807. var vertexData = new BABYLON.VertexData();
  18808. vertexData.indices = [];
  18809. var indices = this.getIndices();
  18810. for (var index = 0; index < indices.length; index++) {
  18811. vertexData.indices.push(indices[index]);
  18812. }
  18813. var updatable = false;
  18814. var stopChecking = false;
  18815. for (var kind in this._vertexBuffers) {
  18816. vertexData.set(this.getVerticesData(kind), kind);
  18817. if (!stopChecking) {
  18818. updatable = this.getVertexBuffer(kind).isUpdatable();
  18819. stopChecking = !updatable;
  18820. }
  18821. }
  18822. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  18823. geometry.delayLoadState = this.delayLoadState;
  18824. geometry.delayLoadingFile = this.delayLoadingFile;
  18825. geometry._delayLoadingFunction = this._delayLoadingFunction;
  18826. for (kind in this._delayInfo) {
  18827. geometry._delayInfo = geometry._delayInfo || [];
  18828. geometry._delayInfo.push(kind);
  18829. }
  18830. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  18831. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18832. return geometry;
  18833. };
  18834. Geometry.ExtractFromMesh = function (mesh, id) {
  18835. var geometry = mesh._geometry;
  18836. if (!geometry) {
  18837. return null;
  18838. }
  18839. return geometry.copy(id);
  18840. };
  18841. Geometry.RandomId = function () {
  18842. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  18843. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  18844. return v.toString(16);
  18845. });
  18846. };
  18847. return Geometry;
  18848. })();
  18849. BABYLON.Geometry = Geometry;
  18850. (function (Geometry) {
  18851. (function (Primitives) {
  18852. var _Primitive = (function (_super) {
  18853. __extends(_Primitive, _super);
  18854. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  18855. this._beingRegenerated = true;
  18856. this._canBeRegenerated = canBeRegenerated;
  18857. _super.call(this, id, scene, vertexData, false, mesh);
  18858. this._beingRegenerated = false;
  18859. }
  18860. _Primitive.prototype.canBeRegenerated = function () {
  18861. return this._canBeRegenerated;
  18862. };
  18863. _Primitive.prototype.regenerate = function () {
  18864. if (!this._canBeRegenerated) {
  18865. return;
  18866. }
  18867. this._beingRegenerated = true;
  18868. this.setAllVerticesData(this._regenerateVertexData(), false);
  18869. this._beingRegenerated = false;
  18870. };
  18871. _Primitive.prototype.asNewGeometry = function (id) {
  18872. return _super.prototype.copy.call(this, id);
  18873. };
  18874. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  18875. if (!this._beingRegenerated) {
  18876. return;
  18877. }
  18878. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  18879. };
  18880. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  18881. if (!this._beingRegenerated) {
  18882. return;
  18883. }
  18884. _super.prototype.setVerticesData.call(this, kind, data, false);
  18885. };
  18886. _Primitive.prototype._regenerateVertexData = function () {
  18887. throw new Error("Abstract method");
  18888. };
  18889. _Primitive.prototype.copy = function (id) {
  18890. throw new Error("Must be overriden in sub-classes.");
  18891. };
  18892. return _Primitive;
  18893. })(Geometry);
  18894. Primitives._Primitive = _Primitive;
  18895. var Box = (function (_super) {
  18896. __extends(Box, _super);
  18897. function Box(id, scene, size, canBeRegenerated, mesh) {
  18898. this.size = size;
  18899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18900. }
  18901. Box.prototype._regenerateVertexData = function () {
  18902. return BABYLON.VertexData.CreateBox(this.size);
  18903. };
  18904. Box.prototype.copy = function (id) {
  18905. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  18906. };
  18907. return Box;
  18908. })(_Primitive);
  18909. Primitives.Box = Box;
  18910. var Sphere = (function (_super) {
  18911. __extends(Sphere, _super);
  18912. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  18913. this.segments = segments;
  18914. this.diameter = diameter;
  18915. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18916. }
  18917. Sphere.prototype._regenerateVertexData = function () {
  18918. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  18919. };
  18920. Sphere.prototype.copy = function (id) {
  18921. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  18922. };
  18923. return Sphere;
  18924. })(_Primitive);
  18925. Primitives.Sphere = Sphere;
  18926. var Cylinder = (function (_super) {
  18927. __extends(Cylinder, _super);
  18928. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  18929. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  18930. this.height = height;
  18931. this.diameterTop = diameterTop;
  18932. this.diameterBottom = diameterBottom;
  18933. this.tessellation = tessellation;
  18934. this.subdivisions = subdivisions;
  18935. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18936. }
  18937. Cylinder.prototype._regenerateVertexData = function () {
  18938. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  18939. };
  18940. Cylinder.prototype.copy = function (id) {
  18941. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  18942. };
  18943. return Cylinder;
  18944. })(_Primitive);
  18945. Primitives.Cylinder = Cylinder;
  18946. var Torus = (function (_super) {
  18947. __extends(Torus, _super);
  18948. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  18949. this.diameter = diameter;
  18950. this.thickness = thickness;
  18951. this.tessellation = tessellation;
  18952. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18953. }
  18954. Torus.prototype._regenerateVertexData = function () {
  18955. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  18956. };
  18957. Torus.prototype.copy = function (id) {
  18958. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  18959. };
  18960. return Torus;
  18961. })(_Primitive);
  18962. Primitives.Torus = Torus;
  18963. var Ground = (function (_super) {
  18964. __extends(Ground, _super);
  18965. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  18966. this.width = width;
  18967. this.height = height;
  18968. this.subdivisions = subdivisions;
  18969. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18970. }
  18971. Ground.prototype._regenerateVertexData = function () {
  18972. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  18973. };
  18974. Ground.prototype.copy = function (id) {
  18975. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  18976. };
  18977. return Ground;
  18978. })(_Primitive);
  18979. Primitives.Ground = Ground;
  18980. var TiledGround = (function (_super) {
  18981. __extends(TiledGround, _super);
  18982. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  18983. this.xmin = xmin;
  18984. this.zmin = zmin;
  18985. this.xmax = xmax;
  18986. this.zmax = zmax;
  18987. this.subdivisions = subdivisions;
  18988. this.precision = precision;
  18989. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  18990. }
  18991. TiledGround.prototype._regenerateVertexData = function () {
  18992. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  18993. };
  18994. TiledGround.prototype.copy = function (id) {
  18995. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  18996. };
  18997. return TiledGround;
  18998. })(_Primitive);
  18999. Primitives.TiledGround = TiledGround;
  19000. var Plane = (function (_super) {
  19001. __extends(Plane, _super);
  19002. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19003. this.size = size;
  19004. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19005. }
  19006. Plane.prototype._regenerateVertexData = function () {
  19007. return BABYLON.VertexData.CreatePlane(this.size);
  19008. };
  19009. Plane.prototype.copy = function (id) {
  19010. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19011. };
  19012. return Plane;
  19013. })(_Primitive);
  19014. Primitives.Plane = Plane;
  19015. var TorusKnot = (function (_super) {
  19016. __extends(TorusKnot, _super);
  19017. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19018. this.radius = radius;
  19019. this.tube = tube;
  19020. this.radialSegments = radialSegments;
  19021. this.tubularSegments = tubularSegments;
  19022. this.p = p;
  19023. this.q = q;
  19024. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19025. }
  19026. TorusKnot.prototype._regenerateVertexData = function () {
  19027. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19028. };
  19029. TorusKnot.prototype.copy = function (id) {
  19030. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19031. };
  19032. return TorusKnot;
  19033. })(_Primitive);
  19034. Primitives.TorusKnot = TorusKnot;
  19035. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19036. var Primitives = Geometry.Primitives;
  19037. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19038. var Geometry = BABYLON.Geometry;
  19039. })(BABYLON || (BABYLON = {}));
  19040. var __extends = this.__extends || function (d, b) {
  19041. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19042. function __() { this.constructor = d; }
  19043. __.prototype = b.prototype;
  19044. d.prototype = new __();
  19045. };
  19046. var BABYLON;
  19047. (function (BABYLON) {
  19048. var Gamepads = (function () {
  19049. function Gamepads(ongamedpadconnected) {
  19050. var _this = this;
  19051. this.babylonGamepads = [];
  19052. this.oneGamepadConnected = false;
  19053. this.isMonitoring = false;
  19054. this.gamepadEventSupported = 'GamepadEvent' in window;
  19055. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19056. 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=";
  19057. this._callbackGamepadConnected = ongamedpadconnected;
  19058. if (this.gamepadSupportAvailable) {
  19059. if (this.gamepadEventSupported) {
  19060. window.addEventListener('gamepadconnected', function (evt) {
  19061. _this._onGamepadConnected(evt);
  19062. }, false);
  19063. window.addEventListener('gamepaddisconnected', function (evt) {
  19064. _this._onGamepadDisconnected(evt);
  19065. }, false);
  19066. } else {
  19067. this._startMonitoringGamepads();
  19068. }
  19069. if (!this.oneGamepadConnected) {
  19070. this._insertGamepadDOMInstructions();
  19071. }
  19072. } else {
  19073. this._insertGamepadDOMNotSupported();
  19074. }
  19075. }
  19076. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19077. Gamepads.gamepadDOMInfo = document.createElement("div");
  19078. var buttonAImage = document.createElement("img");
  19079. buttonAImage.src = this.buttonADataURL;
  19080. var spanMessage = document.createElement("span");
  19081. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19082. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19083. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19084. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19085. Gamepads.gamepadDOMInfo.style.width = "100%";
  19086. Gamepads.gamepadDOMInfo.style.height = "48px";
  19087. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19088. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19089. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19090. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19091. buttonAImage.style.position = "relative";
  19092. buttonAImage.style.bottom = "8px";
  19093. spanMessage.style.position = "relative";
  19094. spanMessage.style.fontSize = "32px";
  19095. spanMessage.style.bottom = "32px";
  19096. spanMessage.style.color = "green";
  19097. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19098. };
  19099. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19100. Gamepads.gamepadDOMInfo = document.createElement("div");
  19101. var spanMessage = document.createElement("span");
  19102. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19103. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19104. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19105. Gamepads.gamepadDOMInfo.style.width = "100%";
  19106. Gamepads.gamepadDOMInfo.style.height = "40px";
  19107. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19108. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19109. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19110. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19111. spanMessage.style.position = "relative";
  19112. spanMessage.style.fontSize = "32px";
  19113. spanMessage.style.color = "red";
  19114. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19115. };
  19116. Gamepads.prototype.dispose = function () {
  19117. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19118. };
  19119. Gamepads.prototype._onGamepadConnected = function (evt) {
  19120. var newGamepad = this._addNewGamepad(evt.gamepad);
  19121. if (this._callbackGamepadConnected)
  19122. this._callbackGamepadConnected(newGamepad);
  19123. this._startMonitoringGamepads();
  19124. };
  19125. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19126. if (!this.oneGamepadConnected) {
  19127. this.oneGamepadConnected = true;
  19128. if (Gamepads.gamepadDOMInfo) {
  19129. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19130. Gamepads.gamepadDOMInfo = null;
  19131. }
  19132. }
  19133. var newGamepad;
  19134. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19135. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19136. } else {
  19137. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19138. }
  19139. this.babylonGamepads.push(newGamepad);
  19140. return newGamepad;
  19141. };
  19142. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19143. for (var i in this.babylonGamepads) {
  19144. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19145. this.babylonGamepads.splice(i, 1);
  19146. break;
  19147. }
  19148. }
  19149. if (this.babylonGamepads.length == 0) {
  19150. this._stopMonitoringGamepads();
  19151. }
  19152. };
  19153. Gamepads.prototype._startMonitoringGamepads = function () {
  19154. if (!this.isMonitoring) {
  19155. this.isMonitoring = true;
  19156. this._checkGamepadsStatus();
  19157. }
  19158. };
  19159. Gamepads.prototype._stopMonitoringGamepads = function () {
  19160. this.isMonitoring = false;
  19161. };
  19162. Gamepads.prototype._checkGamepadsStatus = function () {
  19163. var _this = this;
  19164. this._updateGamepadObjects();
  19165. for (var i in this.babylonGamepads) {
  19166. this.babylonGamepads[i].update();
  19167. }
  19168. if (this.isMonitoring) {
  19169. if (window.requestAnimationFrame) {
  19170. window.requestAnimationFrame(function () {
  19171. _this._checkGamepadsStatus();
  19172. });
  19173. } else if (window.mozRequestAnimationFrame) {
  19174. window.mozRequestAnimationFrame(function () {
  19175. _this._checkGamepadsStatus();
  19176. });
  19177. } else if (window.webkitRequestAnimationFrame) {
  19178. window.webkitRequestAnimationFrame(function () {
  19179. _this._checkGamepadsStatus();
  19180. });
  19181. }
  19182. }
  19183. };
  19184. Gamepads.prototype._updateGamepadObjects = function () {
  19185. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19186. for (var i = 0; i < gamepads.length; i++) {
  19187. if (gamepads[i]) {
  19188. if (!(gamepads[i].index in this.babylonGamepads)) {
  19189. var newGamepad = this._addNewGamepad(gamepads[i]);
  19190. if (this._callbackGamepadConnected) {
  19191. this._callbackGamepadConnected(newGamepad);
  19192. }
  19193. } else {
  19194. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19195. }
  19196. }
  19197. }
  19198. };
  19199. return Gamepads;
  19200. })();
  19201. BABYLON.Gamepads = Gamepads;
  19202. var StickValues = (function () {
  19203. function StickValues(x, y) {
  19204. this.x = x;
  19205. this.y = y;
  19206. }
  19207. return StickValues;
  19208. })();
  19209. BABYLON.StickValues = StickValues;
  19210. var Gamepad = (function () {
  19211. function Gamepad(id, index, browserGamepad) {
  19212. this.id = id;
  19213. this.index = index;
  19214. this.browserGamepad = browserGamepad;
  19215. if (this.browserGamepad.axes.length >= 2) {
  19216. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19217. }
  19218. if (this.browserGamepad.axes.length >= 4) {
  19219. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19220. }
  19221. }
  19222. Gamepad.prototype.onleftstickchanged = function (callback) {
  19223. this._onleftstickchanged = callback;
  19224. };
  19225. Gamepad.prototype.onrightstickchanged = function (callback) {
  19226. this._onrightstickchanged = callback;
  19227. };
  19228. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19229. get: function () {
  19230. return this._leftStick;
  19231. },
  19232. set: function (newValues) {
  19233. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19234. this._onleftstickchanged(newValues);
  19235. }
  19236. this._leftStick = newValues;
  19237. },
  19238. enumerable: true,
  19239. configurable: true
  19240. });
  19241. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19242. get: function () {
  19243. return this._rightStick;
  19244. },
  19245. set: function (newValues) {
  19246. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19247. this._onrightstickchanged(newValues);
  19248. }
  19249. this._rightStick = newValues;
  19250. },
  19251. enumerable: true,
  19252. configurable: true
  19253. });
  19254. Gamepad.prototype.update = function () {
  19255. if (this._leftStick) {
  19256. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19257. }
  19258. if (this._rightStick) {
  19259. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19260. }
  19261. };
  19262. return Gamepad;
  19263. })();
  19264. BABYLON.Gamepad = Gamepad;
  19265. var GenericPad = (function (_super) {
  19266. __extends(GenericPad, _super);
  19267. function GenericPad(id, index, gamepad) {
  19268. _super.call(this, id, index, gamepad);
  19269. this.id = id;
  19270. this.index = index;
  19271. this.gamepad = gamepad;
  19272. this._buttons = new Array(gamepad.buttons.length);
  19273. }
  19274. GenericPad.prototype.onbuttondown = function (callback) {
  19275. this._onbuttondown = callback;
  19276. };
  19277. GenericPad.prototype.onbuttonup = function (callback) {
  19278. this._onbuttonup = callback;
  19279. };
  19280. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19281. if (newValue !== currentValue) {
  19282. if (this._onbuttondown && newValue === 1) {
  19283. this._onbuttondown(buttonIndex);
  19284. }
  19285. if (this._onbuttonup && newValue === 0) {
  19286. this._onbuttonup(buttonIndex);
  19287. }
  19288. }
  19289. return newValue;
  19290. };
  19291. GenericPad.prototype.update = function () {
  19292. _super.prototype.update.call(this);
  19293. for (var index = 0; index < this._buttons.length; index++) {
  19294. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19295. }
  19296. };
  19297. return GenericPad;
  19298. })(Gamepad);
  19299. BABYLON.GenericPad = GenericPad;
  19300. (function (Xbox360Button) {
  19301. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19302. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19303. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19304. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19305. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19306. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19307. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19308. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19309. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19310. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19311. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19312. var Xbox360Button = BABYLON.Xbox360Button;
  19313. (function (Xbox360Dpad) {
  19314. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19315. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19316. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19317. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19318. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19319. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19320. var Xbox360Pad = (function (_super) {
  19321. __extends(Xbox360Pad, _super);
  19322. function Xbox360Pad() {
  19323. _super.apply(this, arguments);
  19324. this._leftTrigger = 0;
  19325. this._rightTrigger = 0;
  19326. this._buttonA = 0;
  19327. this._buttonB = 0;
  19328. this._buttonX = 0;
  19329. this._buttonY = 0;
  19330. this._buttonBack = 0;
  19331. this._buttonStart = 0;
  19332. this._buttonLB = 0;
  19333. this._buttonRB = 0;
  19334. this._buttonLeftStick = 0;
  19335. this._buttonRightStick = 0;
  19336. this._dPadUp = 0;
  19337. this._dPadDown = 0;
  19338. this._dPadLeft = 0;
  19339. this._dPadRight = 0;
  19340. }
  19341. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19342. this._onlefttriggerchanged = callback;
  19343. };
  19344. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19345. this._onrighttriggerchanged = callback;
  19346. };
  19347. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19348. get: function () {
  19349. return this._leftTrigger;
  19350. },
  19351. set: function (newValue) {
  19352. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19353. this._onlefttriggerchanged(newValue);
  19354. }
  19355. this._leftTrigger = newValue;
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19361. get: function () {
  19362. return this._rightTrigger;
  19363. },
  19364. set: function (newValue) {
  19365. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19366. this._onrighttriggerchanged(newValue);
  19367. }
  19368. this._rightTrigger = newValue;
  19369. },
  19370. enumerable: true,
  19371. configurable: true
  19372. });
  19373. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19374. this._onbuttondown = callback;
  19375. };
  19376. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19377. this._onbuttonup = callback;
  19378. };
  19379. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19380. this._ondpaddown = callback;
  19381. };
  19382. Xbox360Pad.prototype.ondpadup = function (callback) {
  19383. this._ondpadup = callback;
  19384. };
  19385. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19386. if (newValue !== currentValue) {
  19387. if (this._onbuttondown && newValue === 1) {
  19388. this._onbuttondown(buttonType);
  19389. }
  19390. if (this._onbuttonup && newValue === 0) {
  19391. this._onbuttonup(buttonType);
  19392. }
  19393. }
  19394. return newValue;
  19395. };
  19396. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19397. if (newValue !== currentValue) {
  19398. if (this._ondpaddown && newValue === 1) {
  19399. this._ondpaddown(buttonType);
  19400. }
  19401. if (this._ondpadup && newValue === 0) {
  19402. this._ondpadup(buttonType);
  19403. }
  19404. }
  19405. return newValue;
  19406. };
  19407. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19408. get: function () {
  19409. return this._buttonA;
  19410. },
  19411. set: function (value) {
  19412. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19413. },
  19414. enumerable: true,
  19415. configurable: true
  19416. });
  19417. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19418. get: function () {
  19419. return this._buttonB;
  19420. },
  19421. set: function (value) {
  19422. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19423. },
  19424. enumerable: true,
  19425. configurable: true
  19426. });
  19427. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19428. get: function () {
  19429. return this._buttonX;
  19430. },
  19431. set: function (value) {
  19432. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19433. },
  19434. enumerable: true,
  19435. configurable: true
  19436. });
  19437. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19438. get: function () {
  19439. return this._buttonY;
  19440. },
  19441. set: function (value) {
  19442. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19448. get: function () {
  19449. return this._buttonStart;
  19450. },
  19451. set: function (value) {
  19452. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19458. get: function () {
  19459. return this._buttonBack;
  19460. },
  19461. set: function (value) {
  19462. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19463. },
  19464. enumerable: true,
  19465. configurable: true
  19466. });
  19467. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19468. get: function () {
  19469. return this._buttonLB;
  19470. },
  19471. set: function (value) {
  19472. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19478. get: function () {
  19479. return this._buttonRB;
  19480. },
  19481. set: function (value) {
  19482. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19483. },
  19484. enumerable: true,
  19485. configurable: true
  19486. });
  19487. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19488. get: function () {
  19489. return this._buttonLeftStick;
  19490. },
  19491. set: function (value) {
  19492. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19498. get: function () {
  19499. return this._buttonRightStick;
  19500. },
  19501. set: function (value) {
  19502. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19508. get: function () {
  19509. return this._dPadUp;
  19510. },
  19511. set: function (value) {
  19512. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19513. },
  19514. enumerable: true,
  19515. configurable: true
  19516. });
  19517. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19518. get: function () {
  19519. return this._dPadDown;
  19520. },
  19521. set: function (value) {
  19522. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19528. get: function () {
  19529. return this._dPadLeft;
  19530. },
  19531. set: function (value) {
  19532. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19538. get: function () {
  19539. return this._dPadRight;
  19540. },
  19541. set: function (value) {
  19542. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19543. },
  19544. enumerable: true,
  19545. configurable: true
  19546. });
  19547. Xbox360Pad.prototype.update = function () {
  19548. _super.prototype.update.call(this);
  19549. this.buttonA = this.browserGamepad.buttons[0].value;
  19550. this.buttonB = this.browserGamepad.buttons[1].value;
  19551. this.buttonX = this.browserGamepad.buttons[2].value;
  19552. this.buttonY = this.browserGamepad.buttons[3].value;
  19553. this.buttonLB = this.browserGamepad.buttons[4].value;
  19554. this.buttonRB = this.browserGamepad.buttons[5].value;
  19555. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19556. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19557. this.buttonBack = this.browserGamepad.buttons[8].value;
  19558. this.buttonStart = this.browserGamepad.buttons[9].value;
  19559. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19560. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19561. this.dPadUp = this.browserGamepad.buttons[12].value;
  19562. this.dPadDown = this.browserGamepad.buttons[13].value;
  19563. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19564. this.dPadRight = this.browserGamepad.buttons[15].value;
  19565. };
  19566. return Xbox360Pad;
  19567. })(Gamepad);
  19568. BABYLON.Xbox360Pad = Xbox360Pad;
  19569. })(BABYLON || (BABYLON = {}));
  19570. var __extends = this.__extends || function (d, b) {
  19571. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19572. function __() { this.constructor = d; }
  19573. __.prototype = b.prototype;
  19574. d.prototype = new __();
  19575. };
  19576. var BABYLON;
  19577. (function (BABYLON) {
  19578. var GamepadCamera = (function (_super) {
  19579. __extends(GamepadCamera, _super);
  19580. function GamepadCamera(name, position, scene) {
  19581. var _this = this;
  19582. _super.call(this, name, position, scene);
  19583. this.angularSensibility = 200;
  19584. this.moveSensibility = 75;
  19585. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19586. _this._onNewGameConnected(gamepad);
  19587. });
  19588. }
  19589. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19590. if (gamepad.index === 0) {
  19591. this._gamepad = gamepad;
  19592. }
  19593. };
  19594. GamepadCamera.prototype._checkInputs = function () {
  19595. if (!this._gamepad) {
  19596. return;
  19597. }
  19598. var LSValues = this._gamepad.leftStick;
  19599. var normalizedLX = LSValues.x / this.moveSensibility;
  19600. var normalizedLY = LSValues.y / this.moveSensibility;
  19601. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19602. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19603. var RSValues = this._gamepad.rightStick;
  19604. var normalizedRX = RSValues.x / this.angularSensibility;
  19605. var normalizedRY = RSValues.y / this.angularSensibility;
  19606. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19607. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19608. ;
  19609. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19610. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19611. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19612. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19613. };
  19614. GamepadCamera.prototype.dispose = function () {
  19615. this._gamepads.dispose();
  19616. _super.prototype.dispose.call(this);
  19617. };
  19618. return GamepadCamera;
  19619. })(BABYLON.FreeCamera);
  19620. BABYLON.GamepadCamera = GamepadCamera;
  19621. })(BABYLON || (BABYLON = {}));
  19622. var __extends = this.__extends || function (d, b) {
  19623. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19624. function __() { this.constructor = d; }
  19625. __.prototype = b.prototype;
  19626. d.prototype = new __();
  19627. };
  19628. var BABYLON;
  19629. (function (BABYLON) {
  19630. var LinesMesh = (function (_super) {
  19631. __extends(LinesMesh, _super);
  19632. function LinesMesh(name, scene, updatable) {
  19633. if (typeof updatable === "undefined") { updatable = false; }
  19634. _super.call(this, name, scene);
  19635. this.color = new BABYLON.Color3(1, 1, 1);
  19636. this.alpha = 1;
  19637. this._indices = new Array();
  19638. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19639. attributes: ["position"],
  19640. uniforms: ["worldViewProjection", "color"],
  19641. needAlphaBlending: true
  19642. });
  19643. }
  19644. Object.defineProperty(LinesMesh.prototype, "material", {
  19645. get: function () {
  19646. return this._colorShader;
  19647. },
  19648. enumerable: true,
  19649. configurable: true
  19650. });
  19651. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19652. get: function () {
  19653. return false;
  19654. },
  19655. enumerable: true,
  19656. configurable: true
  19657. });
  19658. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19659. get: function () {
  19660. return false;
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19666. var engine = this.getScene().getEngine();
  19667. var indexToBind = this._geometry.getIndexBuffer();
  19668. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19669. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19670. };
  19671. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19672. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19673. return;
  19674. }
  19675. var engine = this.getScene().getEngine();
  19676. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19677. };
  19678. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19679. return null;
  19680. };
  19681. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19682. this._colorShader.dispose();
  19683. _super.prototype.dispose.call(this, doNotRecurse);
  19684. };
  19685. return LinesMesh;
  19686. })(BABYLON.Mesh);
  19687. BABYLON.LinesMesh = LinesMesh;
  19688. })(BABYLON || (BABYLON = {}));
  19689. var BABYLON;
  19690. (function (BABYLON) {
  19691. var OutlineRenderer = (function () {
  19692. function OutlineRenderer(scene) {
  19693. this._scene = scene;
  19694. }
  19695. OutlineRenderer.prototype.render = function (subMesh, batch) {
  19696. var scene = this._scene;
  19697. var engine = this._scene.getEngine();
  19698. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  19699. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  19700. return;
  19701. }
  19702. var mesh = subMesh.getRenderingMesh();
  19703. var material = subMesh.getMaterial();
  19704. engine.enableEffect(this._effect);
  19705. this._effect.setFloat("offset", mesh.outlineWidth);
  19706. this._effect.setColor3("color", mesh.outlineColor);
  19707. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19708. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  19709. if (useBones) {
  19710. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19711. }
  19712. mesh._bind(subMesh, this._effect, false);
  19713. if (material && material.needAlphaTesting()) {
  19714. var alphaTexture = material.getAlphaTestTexture();
  19715. this._effect.setTexture("diffuseSampler", alphaTexture);
  19716. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  19717. }
  19718. if (hardwareInstancedRendering) {
  19719. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  19720. } else {
  19721. if (batch.renderSelf[subMesh._id]) {
  19722. this._effect.setMatrix("world", mesh.getWorldMatrix());
  19723. mesh._draw(subMesh, true);
  19724. }
  19725. if (batch.visibleInstances[subMesh._id]) {
  19726. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19727. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19728. this._effect.setMatrix("world", instance.getWorldMatrix());
  19729. mesh._draw(subMesh, true);
  19730. }
  19731. }
  19732. }
  19733. };
  19734. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  19735. var defines = [];
  19736. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  19737. var mesh = subMesh.getMesh();
  19738. var material = subMesh.getMaterial();
  19739. if (material && material.needAlphaTesting()) {
  19740. defines.push("#define ALPHATEST");
  19741. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19742. attribs.push(BABYLON.VertexBuffer.UVKind);
  19743. defines.push("#define UV1");
  19744. }
  19745. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19746. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19747. defines.push("#define UV2");
  19748. }
  19749. }
  19750. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19751. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19752. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19753. defines.push("#define BONES");
  19754. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  19755. }
  19756. if (useInstances) {
  19757. defines.push("#define INSTANCES");
  19758. attribs.push("world0");
  19759. attribs.push("world1");
  19760. attribs.push("world2");
  19761. attribs.push("world3");
  19762. }
  19763. var join = defines.join("\n");
  19764. if (this._cachedDefines != join) {
  19765. this._cachedDefines = join;
  19766. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  19767. }
  19768. return this._effect.isReady();
  19769. };
  19770. return OutlineRenderer;
  19771. })();
  19772. BABYLON.OutlineRenderer = OutlineRenderer;
  19773. })(BABYLON || (BABYLON = {}));
  19774. var BABYLON;
  19775. (function (BABYLON) {
  19776. var MeshAssetTask = (function () {
  19777. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  19778. this.name = name;
  19779. this.meshesNames = meshesNames;
  19780. this.rootUrl = rootUrl;
  19781. this.sceneFilename = sceneFilename;
  19782. this.isCompleted = false;
  19783. }
  19784. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19785. var _this = this;
  19786. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  19787. _this.loadedMeshes = meshes;
  19788. _this.loadedParticleSystems = particleSystems;
  19789. _this.loadedSkeletons = skeletons;
  19790. _this.isCompleted = true;
  19791. if (_this.onSuccess) {
  19792. _this.onSuccess(_this);
  19793. }
  19794. onSuccess();
  19795. }, null, function () {
  19796. if (_this.onError) {
  19797. _this.onError(_this);
  19798. }
  19799. onError();
  19800. });
  19801. };
  19802. return MeshAssetTask;
  19803. })();
  19804. BABYLON.MeshAssetTask = MeshAssetTask;
  19805. var TextFileAssetTask = (function () {
  19806. function TextFileAssetTask(name, url) {
  19807. this.name = name;
  19808. this.url = url;
  19809. this.isCompleted = false;
  19810. }
  19811. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19812. var _this = this;
  19813. BABYLON.Tools.LoadFile(this.url, function (data) {
  19814. _this.text = data;
  19815. _this.isCompleted = true;
  19816. if (_this.onSuccess) {
  19817. _this.onSuccess(_this);
  19818. }
  19819. onSuccess();
  19820. }, null, scene.database, false, function () {
  19821. if (_this.onError) {
  19822. _this.onError(_this);
  19823. }
  19824. onError();
  19825. });
  19826. };
  19827. return TextFileAssetTask;
  19828. })();
  19829. BABYLON.TextFileAssetTask = TextFileAssetTask;
  19830. var BinaryFileAssetTask = (function () {
  19831. function BinaryFileAssetTask(name, url) {
  19832. this.name = name;
  19833. this.url = url;
  19834. this.isCompleted = false;
  19835. }
  19836. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19837. var _this = this;
  19838. BABYLON.Tools.LoadFile(this.url, function (data) {
  19839. _this.data = data;
  19840. _this.isCompleted = true;
  19841. if (_this.onSuccess) {
  19842. _this.onSuccess(_this);
  19843. }
  19844. onSuccess();
  19845. }, null, scene.database, true, function () {
  19846. if (_this.onError) {
  19847. _this.onError(_this);
  19848. }
  19849. onError();
  19850. });
  19851. };
  19852. return BinaryFileAssetTask;
  19853. })();
  19854. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  19855. var AssetsManager = (function () {
  19856. function AssetsManager(scene) {
  19857. this._tasks = new Array();
  19858. this._waitingTasksCount = 0;
  19859. this.useDefaultLoadingScreen = true;
  19860. this._scene = scene;
  19861. }
  19862. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  19863. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  19864. this._tasks.push(task);
  19865. return task;
  19866. };
  19867. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  19868. var task = new TextFileAssetTask(taskName, url);
  19869. this._tasks.push(task);
  19870. return task;
  19871. };
  19872. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  19873. var task = new BinaryFileAssetTask(taskName, url);
  19874. this._tasks.push(task);
  19875. return task;
  19876. };
  19877. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  19878. this._waitingTasksCount--;
  19879. if (this._waitingTasksCount === 0) {
  19880. if (this.onFinish) {
  19881. this.onFinish(this._tasks);
  19882. }
  19883. this._scene.getEngine().hideLoadingUI();
  19884. }
  19885. };
  19886. AssetsManager.prototype._runTask = function (task) {
  19887. var _this = this;
  19888. task.run(this._scene, function () {
  19889. if (_this.onTaskSuccess) {
  19890. _this.onTaskSuccess(task);
  19891. }
  19892. _this._decreaseWaitingTasksCount();
  19893. }, function () {
  19894. if (_this.onTaskError) {
  19895. _this.onTaskError(task);
  19896. }
  19897. _this._decreaseWaitingTasksCount();
  19898. });
  19899. };
  19900. AssetsManager.prototype.reset = function () {
  19901. this._tasks = new Array();
  19902. return this;
  19903. };
  19904. AssetsManager.prototype.load = function () {
  19905. this._waitingTasksCount = this._tasks.length;
  19906. if (this._waitingTasksCount === 0) {
  19907. if (this.onFinish) {
  19908. this.onFinish(this._tasks);
  19909. }
  19910. return this;
  19911. }
  19912. if (this.useDefaultLoadingScreen) {
  19913. this._scene.getEngine().displayLoadingUI();
  19914. }
  19915. for (var index = 0; index < this._tasks.length; index++) {
  19916. var task = this._tasks[index];
  19917. this._runTask(task);
  19918. }
  19919. return this;
  19920. };
  19921. return AssetsManager;
  19922. })();
  19923. BABYLON.AssetsManager = AssetsManager;
  19924. })(BABYLON || (BABYLON = {}));