babylon.max.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  807. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  808. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  809. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  810. vector = vector.scale(1.0 / num);
  811. }
  812. return vector;
  813. };
  814. Vector3.Minimize = function (left, right) {
  815. var min = left.clone();
  816. min.MinimizeInPlace(right);
  817. return min;
  818. };
  819. Vector3.Maximize = function (left, right) {
  820. var max = left.clone();
  821. max.MaximizeInPlace(right);
  822. return max;
  823. };
  824. Vector3.Distance = function (value1, value2) {
  825. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  826. };
  827. Vector3.DistanceSquared = function (value1, value2) {
  828. var x = value1.x - value2.x;
  829. var y = value1.y - value2.y;
  830. var z = value1.z - value2.z;
  831. return (x * x) + (y * y) + (z * z);
  832. };
  833. Vector3.Center = function (value1, value2) {
  834. var center = value1.add(value2);
  835. center.scaleInPlace(0.5);
  836. return center;
  837. };
  838. /**
  839. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  840. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  841. * to something in order to rotate it from its local system to the given target system.
  842. */
  843. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  844. var rotation = Vector3.Zero();
  845. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  846. return rotation;
  847. };
  848. /**
  849. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  850. */
  851. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  852. var u = Vector3.Normalize(axis1);
  853. var w = Vector3.Normalize(axis3);
  854. // world axis
  855. var X = Axis.X;
  856. var Y = Axis.Y;
  857. // equation unknowns and vars
  858. var yaw = 0.0;
  859. var pitch = 0.0;
  860. var roll = 0.0;
  861. var x = 0.0;
  862. var y = 0.0;
  863. var z = 0.0;
  864. var t = 0.0;
  865. var sign = -1.0;
  866. var nbRevert = 0;
  867. var cross;
  868. var dot = 0.0;
  869. // step 1 : rotation around w
  870. // Rv3(u) = u1, and u1 belongs to plane xOz
  871. // Rv3(w) = w1 = w invariant
  872. var u1;
  873. var v1;
  874. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  875. z = 1.0;
  876. }
  877. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  878. x = 1.0;
  879. }
  880. else {
  881. t = w.z / w.x;
  882. x = -t * Math.sqrt(1 / (1 + t * t));
  883. z = Math.sqrt(1 / (1 + t * t));
  884. }
  885. u1 = new Vector3(x, y, z);
  886. u1.normalize();
  887. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  888. v1.normalize();
  889. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  890. cross.normalize();
  891. if (Vector3.Dot(w, cross) < 0) {
  892. sign = 1.0;
  893. }
  894. dot = Vector3.Dot(u, u1);
  895. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  896. roll = Math.acos(dot) * sign;
  897. if (Vector3.Dot(u1, X) < 0) {
  898. roll = Math.PI + roll;
  899. u1 = u1.scaleInPlace(-1);
  900. v1 = v1.scaleInPlace(-1);
  901. nbRevert++;
  902. }
  903. // step 2 : rotate around u1
  904. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  905. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  906. var w2;
  907. var v2;
  908. x = 0.0;
  909. y = 0.0;
  910. z = 0.0;
  911. sign = -1;
  912. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  913. x = 1.0;
  914. }
  915. else {
  916. t = u1.z / u1.x;
  917. x = -t * Math.sqrt(1 / (1 + t * t));
  918. z = Math.sqrt(1 / (1 + t * t));
  919. }
  920. w2 = new Vector3(x, y, z);
  921. w2.normalize();
  922. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  923. v2.normalize();
  924. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  925. cross.normalize();
  926. if (Vector3.Dot(u1, cross) < 0) {
  927. sign = 1.0;
  928. }
  929. dot = Vector3.Dot(w, w2);
  930. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  931. pitch = Math.acos(dot) * sign;
  932. if (Vector3.Dot(v2, Y) < 0) {
  933. pitch = Math.PI + pitch;
  934. v2 = v2.scaleInPlace(-1);
  935. w2 = w2.scaleInPlace(-1);
  936. nbRevert++;
  937. }
  938. // step 3 : rotate around v2
  939. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  940. sign = -1;
  941. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(cross, Y) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(u1, X);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  949. if (dot < 0 && nbRevert < 2) {
  950. yaw = Math.PI + yaw;
  951. }
  952. ref.x = pitch;
  953. ref.y = yaw;
  954. ref.z = roll;
  955. };
  956. return Vector3;
  957. })();
  958. BABYLON.Vector3 = Vector3;
  959. //Vector4 class created for EulerAngle class conversion to Quaternion
  960. var Vector4 = (function () {
  961. function Vector4(x, y, z, w) {
  962. this.x = x;
  963. this.y = y;
  964. this.z = z;
  965. this.w = w;
  966. }
  967. Vector4.prototype.toString = function () {
  968. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  969. };
  970. // Operators
  971. Vector4.prototype.asArray = function () {
  972. var result = [];
  973. this.toArray(result, 0);
  974. return result;
  975. };
  976. Vector4.prototype.toArray = function (array, index) {
  977. if (index === undefined) {
  978. index = 0;
  979. }
  980. array[index] = this.x;
  981. array[index + 1] = this.y;
  982. array[index + 2] = this.z;
  983. array[index + 3] = this.w;
  984. return this;
  985. };
  986. Vector4.prototype.addInPlace = function (otherVector) {
  987. this.x += otherVector.x;
  988. this.y += otherVector.y;
  989. this.z += otherVector.z;
  990. this.w += otherVector.w;
  991. return this;
  992. };
  993. Vector4.prototype.add = function (otherVector) {
  994. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  995. };
  996. Vector4.prototype.addToRef = function (otherVector, result) {
  997. result.x = this.x + otherVector.x;
  998. result.y = this.y + otherVector.y;
  999. result.z = this.z + otherVector.z;
  1000. result.w = this.w + otherVector.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.subtractInPlace = function (otherVector) {
  1004. this.x -= otherVector.x;
  1005. this.y -= otherVector.y;
  1006. this.z -= otherVector.z;
  1007. this.w -= otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.subtract = function (otherVector) {
  1011. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1012. };
  1013. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1014. result.x = this.x - otherVector.x;
  1015. result.y = this.y - otherVector.y;
  1016. result.z = this.z - otherVector.z;
  1017. result.w = this.w - otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1021. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1022. };
  1023. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1024. result.x = this.x - x;
  1025. result.y = this.y - y;
  1026. result.z = this.z - z;
  1027. result.w = this.w - w;
  1028. return this;
  1029. };
  1030. Vector4.prototype.negate = function () {
  1031. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1032. };
  1033. Vector4.prototype.scaleInPlace = function (scale) {
  1034. this.x *= scale;
  1035. this.y *= scale;
  1036. this.z *= scale;
  1037. this.w *= scale;
  1038. return this;
  1039. };
  1040. Vector4.prototype.scale = function (scale) {
  1041. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1042. };
  1043. Vector4.prototype.scaleToRef = function (scale, result) {
  1044. result.x = this.x * scale;
  1045. result.y = this.y * scale;
  1046. result.z = this.z * scale;
  1047. result.w = this.w * scale;
  1048. };
  1049. Vector4.prototype.equals = function (otherVector) {
  1050. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1051. };
  1052. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1053. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1054. return otherVector
  1055. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1056. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1057. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1059. };
  1060. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1061. return this.x === x && this.y === y && this.z === z && this.w === w;
  1062. };
  1063. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1064. this.x *= otherVector.x;
  1065. this.y *= otherVector.y;
  1066. this.z *= otherVector.z;
  1067. this.w *= otherVector.w;
  1068. return this;
  1069. };
  1070. Vector4.prototype.multiply = function (otherVector) {
  1071. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1072. };
  1073. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1074. result.x = this.x * otherVector.x;
  1075. result.y = this.y * otherVector.y;
  1076. result.z = this.z * otherVector.z;
  1077. result.w = this.w * otherVector.w;
  1078. return this;
  1079. };
  1080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1082. };
  1083. Vector4.prototype.divide = function (otherVector) {
  1084. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1085. };
  1086. Vector4.prototype.divideToRef = function (otherVector, result) {
  1087. result.x = this.x / otherVector.x;
  1088. result.y = this.y / otherVector.y;
  1089. result.z = this.z / otherVector.z;
  1090. result.w = this.w / otherVector.w;
  1091. return this;
  1092. };
  1093. Vector4.prototype.MinimizeInPlace = function (other) {
  1094. if (other.x < this.x)
  1095. this.x = other.x;
  1096. if (other.y < this.y)
  1097. this.y = other.y;
  1098. if (other.z < this.z)
  1099. this.z = other.z;
  1100. if (other.w < this.w)
  1101. this.w = other.w;
  1102. return this;
  1103. };
  1104. Vector4.prototype.MaximizeInPlace = function (other) {
  1105. if (other.x > this.x)
  1106. this.x = other.x;
  1107. if (other.y > this.y)
  1108. this.y = other.y;
  1109. if (other.z > this.z)
  1110. this.z = other.z;
  1111. if (other.w > this.w)
  1112. this.w = other.w;
  1113. return this;
  1114. };
  1115. // Properties
  1116. Vector4.prototype.length = function () {
  1117. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1118. };
  1119. Vector4.prototype.lengthSquared = function () {
  1120. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1121. };
  1122. // Methods
  1123. Vector4.prototype.normalize = function () {
  1124. var len = this.length();
  1125. if (len === 0)
  1126. return this;
  1127. var num = 1.0 / len;
  1128. this.x *= num;
  1129. this.y *= num;
  1130. this.z *= num;
  1131. this.w *= num;
  1132. return this;
  1133. };
  1134. Vector4.prototype.clone = function () {
  1135. return new Vector4(this.x, this.y, this.z, this.w);
  1136. };
  1137. Vector4.prototype.copyFrom = function (source) {
  1138. this.x = source.x;
  1139. this.y = source.y;
  1140. this.z = source.z;
  1141. this.w = source.w;
  1142. return this;
  1143. };
  1144. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1145. this.x = x;
  1146. this.y = y;
  1147. this.z = z;
  1148. this.w = w;
  1149. return this;
  1150. };
  1151. // Statics
  1152. Vector4.FromArray = function (array, offset) {
  1153. if (!offset) {
  1154. offset = 0;
  1155. }
  1156. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1157. };
  1158. Vector4.FromArrayToRef = function (array, offset, result) {
  1159. result.x = array[offset];
  1160. result.y = array[offset + 1];
  1161. result.z = array[offset + 2];
  1162. result.w = array[offset + 3];
  1163. };
  1164. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1165. result.x = array[offset];
  1166. result.y = array[offset + 1];
  1167. result.z = array[offset + 2];
  1168. result.w = array[offset + 3];
  1169. };
  1170. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1171. result.x = x;
  1172. result.y = y;
  1173. result.z = z;
  1174. result.w = w;
  1175. };
  1176. Vector4.Zero = function () {
  1177. return new Vector4(0, 0, 0, 0);
  1178. };
  1179. Vector4.Normalize = function (vector) {
  1180. var result = Vector4.Zero();
  1181. Vector4.NormalizeToRef(vector, result);
  1182. return result;
  1183. };
  1184. Vector4.NormalizeToRef = function (vector, result) {
  1185. result.copyFrom(vector);
  1186. result.normalize();
  1187. };
  1188. Vector4.Minimize = function (left, right) {
  1189. var min = left.clone();
  1190. min.MinimizeInPlace(right);
  1191. return min;
  1192. };
  1193. Vector4.Maximize = function (left, right) {
  1194. var max = left.clone();
  1195. max.MaximizeInPlace(right);
  1196. return max;
  1197. };
  1198. Vector4.Distance = function (value1, value2) {
  1199. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1200. };
  1201. Vector4.DistanceSquared = function (value1, value2) {
  1202. var x = value1.x - value2.x;
  1203. var y = value1.y - value2.y;
  1204. var z = value1.z - value2.z;
  1205. var w = value1.w - value2.w;
  1206. return (x * x) + (y * y) + (z * z) + (w * w);
  1207. };
  1208. Vector4.Center = function (value1, value2) {
  1209. var center = value1.add(value2);
  1210. center.scaleInPlace(0.5);
  1211. return center;
  1212. };
  1213. return Vector4;
  1214. })();
  1215. BABYLON.Vector4 = Vector4;
  1216. var Quaternion = (function () {
  1217. function Quaternion(x, y, z, w) {
  1218. if (x === void 0) { x = 0; }
  1219. if (y === void 0) { y = 0; }
  1220. if (z === void 0) { z = 0; }
  1221. if (w === void 0) { w = 1; }
  1222. this.x = x;
  1223. this.y = y;
  1224. this.z = z;
  1225. this.w = w;
  1226. }
  1227. Quaternion.prototype.toString = function () {
  1228. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1229. };
  1230. Quaternion.prototype.asArray = function () {
  1231. return [this.x, this.y, this.z, this.w];
  1232. };
  1233. Quaternion.prototype.equals = function (otherQuaternion) {
  1234. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1235. };
  1236. Quaternion.prototype.clone = function () {
  1237. return new Quaternion(this.x, this.y, this.z, this.w);
  1238. };
  1239. Quaternion.prototype.copyFrom = function (other) {
  1240. this.x = other.x;
  1241. this.y = other.y;
  1242. this.z = other.z;
  1243. this.w = other.w;
  1244. return this;
  1245. };
  1246. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1247. this.x = x;
  1248. this.y = y;
  1249. this.z = z;
  1250. this.w = w;
  1251. return this;
  1252. };
  1253. Quaternion.prototype.add = function (other) {
  1254. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1255. };
  1256. Quaternion.prototype.subtract = function (other) {
  1257. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1258. };
  1259. Quaternion.prototype.scale = function (value) {
  1260. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1261. };
  1262. Quaternion.prototype.multiply = function (q1) {
  1263. var result = new Quaternion(0, 0, 0, 1.0);
  1264. this.multiplyToRef(q1, result);
  1265. return result;
  1266. };
  1267. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1268. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1269. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1270. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1271. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1272. result.copyFromFloats(x, y, z, w);
  1273. return this;
  1274. };
  1275. Quaternion.prototype.length = function () {
  1276. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1277. };
  1278. Quaternion.prototype.normalize = function () {
  1279. var length = 1.0 / this.length();
  1280. this.x *= length;
  1281. this.y *= length;
  1282. this.z *= length;
  1283. this.w *= length;
  1284. return this;
  1285. };
  1286. Quaternion.prototype.toEulerAngles = function () {
  1287. var result = Vector3.Zero();
  1288. this.toEulerAnglesToRef(result);
  1289. return result;
  1290. };
  1291. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1292. //result is an EulerAngles in the in the z-x-z convention
  1293. var qx = this.x;
  1294. var qy = this.y;
  1295. var qz = this.z;
  1296. var qw = this.w;
  1297. var qxy = qx * qy;
  1298. var qxz = qx * qz;
  1299. var qwy = qw * qy;
  1300. var qwz = qw * qz;
  1301. var qwx = qw * qx;
  1302. var qyz = qy * qz;
  1303. var sqx = qx * qx;
  1304. var sqy = qy * qy;
  1305. var determinant = sqx + sqy;
  1306. if (determinant !== 0.000 && determinant !== 1.000) {
  1307. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1308. result.y = Math.acos(1 - 2 * determinant);
  1309. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1310. }
  1311. else {
  1312. if (determinant === 0.0) {
  1313. result.x = 0.0;
  1314. result.y = 0.0;
  1315. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1316. }
  1317. else {
  1318. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1319. result.y = Math.PI;
  1320. result.z = 0.0;
  1321. }
  1322. }
  1323. return this;
  1324. };
  1325. Quaternion.prototype.toRotationMatrix = function (result) {
  1326. var xx = this.x * this.x;
  1327. var yy = this.y * this.y;
  1328. var zz = this.z * this.z;
  1329. var xy = this.x * this.y;
  1330. var zw = this.z * this.w;
  1331. var zx = this.z * this.x;
  1332. var yw = this.y * this.w;
  1333. var yz = this.y * this.z;
  1334. var xw = this.x * this.w;
  1335. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1336. result.m[1] = 2.0 * (xy + zw);
  1337. result.m[2] = 2.0 * (zx - yw);
  1338. result.m[3] = 0;
  1339. result.m[4] = 2.0 * (xy - zw);
  1340. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1341. result.m[6] = 2.0 * (yz + xw);
  1342. result.m[7] = 0;
  1343. result.m[8] = 2.0 * (zx + yw);
  1344. result.m[9] = 2.0 * (yz - xw);
  1345. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1346. result.m[11] = 0;
  1347. result.m[12] = 0;
  1348. result.m[13] = 0;
  1349. result.m[14] = 0;
  1350. result.m[15] = 1.0;
  1351. return this;
  1352. };
  1353. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1354. Quaternion.FromRotationMatrixToRef(matrix, this);
  1355. return this;
  1356. };
  1357. // Statics
  1358. Quaternion.FromRotationMatrix = function (matrix) {
  1359. var result = new Quaternion();
  1360. Quaternion.FromRotationMatrixToRef(matrix, result);
  1361. return result;
  1362. };
  1363. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1364. var data = matrix.m;
  1365. var m11 = data[0], m12 = data[4], m13 = data[8];
  1366. var m21 = data[1], m22 = data[5], m23 = data[9];
  1367. var m31 = data[2], m32 = data[6], m33 = data[10];
  1368. var trace = m11 + m22 + m33;
  1369. var s;
  1370. if (trace > 0) {
  1371. s = 0.5 / Math.sqrt(trace + 1.0);
  1372. result.w = 0.25 / s;
  1373. result.x = (m32 - m23) * s;
  1374. result.y = (m13 - m31) * s;
  1375. result.z = (m21 - m12) * s;
  1376. }
  1377. else if (m11 > m22 && m11 > m33) {
  1378. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1379. result.w = (m32 - m23) / s;
  1380. result.x = 0.25 * s;
  1381. result.y = (m12 + m21) / s;
  1382. result.z = (m13 + m31) / s;
  1383. }
  1384. else if (m22 > m33) {
  1385. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1386. result.w = (m13 - m31) / s;
  1387. result.x = (m12 + m21) / s;
  1388. result.y = 0.25 * s;
  1389. result.z = (m23 + m32) / s;
  1390. }
  1391. else {
  1392. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1393. result.w = (m21 - m12) / s;
  1394. result.x = (m13 + m31) / s;
  1395. result.y = (m23 + m32) / s;
  1396. result.z = 0.25 * s;
  1397. }
  1398. };
  1399. Quaternion.Inverse = function (q) {
  1400. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1401. };
  1402. Quaternion.Identity = function () {
  1403. return new Quaternion(0, 0, 0, 1);
  1404. };
  1405. Quaternion.RotationAxis = function (axis, angle) {
  1406. var result = new Quaternion();
  1407. var sin = Math.sin(angle / 2);
  1408. axis.normalize();
  1409. result.w = Math.cos(angle / 2);
  1410. result.x = axis.x * sin;
  1411. result.y = axis.y * sin;
  1412. result.z = axis.z * sin;
  1413. return result;
  1414. };
  1415. Quaternion.FromArray = function (array, offset) {
  1416. if (!offset) {
  1417. offset = 0;
  1418. }
  1419. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1420. };
  1421. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1422. var result = new Quaternion();
  1423. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1424. return result;
  1425. };
  1426. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1427. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1428. var halfRoll = roll * 0.5;
  1429. var halfPitch = pitch * 0.5;
  1430. var halfYaw = yaw * 0.5;
  1431. var sinRoll = Math.sin(halfRoll);
  1432. var cosRoll = Math.cos(halfRoll);
  1433. var sinPitch = Math.sin(halfPitch);
  1434. var cosPitch = Math.cos(halfPitch);
  1435. var sinYaw = Math.sin(halfYaw);
  1436. var cosYaw = Math.cos(halfYaw);
  1437. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1438. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1439. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1440. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1441. };
  1442. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1448. // Produces a quaternion from Euler angles in the z-x-z orientation
  1449. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1450. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1451. var halfBeta = beta * 0.5;
  1452. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1453. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1454. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1455. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1456. };
  1457. Quaternion.Slerp = function (left, right, amount) {
  1458. var num2;
  1459. var num3;
  1460. var num = amount;
  1461. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1462. var flag = false;
  1463. if (num4 < 0) {
  1464. flag = true;
  1465. num4 = -num4;
  1466. }
  1467. if (num4 > 0.999999) {
  1468. num3 = 1 - num;
  1469. num2 = flag ? -num : num;
  1470. }
  1471. else {
  1472. var num5 = Math.acos(num4);
  1473. var num6 = (1.0 / Math.sin(num5));
  1474. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1475. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1476. }
  1477. 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));
  1478. };
  1479. return Quaternion;
  1480. })();
  1481. BABYLON.Quaternion = Quaternion;
  1482. var Matrix = (function () {
  1483. function Matrix() {
  1484. this.m = new Float32Array(16);
  1485. }
  1486. // Properties
  1487. Matrix.prototype.isIdentity = function () {
  1488. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1489. return false;
  1490. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1491. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1492. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1493. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1494. return false;
  1495. return true;
  1496. };
  1497. Matrix.prototype.determinant = function () {
  1498. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1499. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1500. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1501. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1502. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1503. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1504. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1505. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1506. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1507. };
  1508. // Methods
  1509. Matrix.prototype.toArray = function () {
  1510. return this.m;
  1511. };
  1512. Matrix.prototype.asArray = function () {
  1513. return this.toArray();
  1514. };
  1515. Matrix.prototype.invert = function () {
  1516. this.invertToRef(this);
  1517. return this;
  1518. };
  1519. Matrix.prototype.reset = function () {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = 0;
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.add = function (other) {
  1526. var result = new Matrix();
  1527. this.addToRef(other, result);
  1528. return result;
  1529. };
  1530. Matrix.prototype.addToRef = function (other, result) {
  1531. for (var index = 0; index < 16; index++) {
  1532. result.m[index] = this.m[index] + other.m[index];
  1533. }
  1534. return this;
  1535. };
  1536. Matrix.prototype.addToSelf = function (other) {
  1537. for (var index = 0; index < 16; index++) {
  1538. this.m[index] += other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.invertToRef = function (other) {
  1543. var l1 = this.m[0];
  1544. var l2 = this.m[1];
  1545. var l3 = this.m[2];
  1546. var l4 = this.m[3];
  1547. var l5 = this.m[4];
  1548. var l6 = this.m[5];
  1549. var l7 = this.m[6];
  1550. var l8 = this.m[7];
  1551. var l9 = this.m[8];
  1552. var l10 = this.m[9];
  1553. var l11 = this.m[10];
  1554. var l12 = this.m[11];
  1555. var l13 = this.m[12];
  1556. var l14 = this.m[13];
  1557. var l15 = this.m[14];
  1558. var l16 = this.m[15];
  1559. var l17 = (l11 * l16) - (l12 * l15);
  1560. var l18 = (l10 * l16) - (l12 * l14);
  1561. var l19 = (l10 * l15) - (l11 * l14);
  1562. var l20 = (l9 * l16) - (l12 * l13);
  1563. var l21 = (l9 * l15) - (l11 * l13);
  1564. var l22 = (l9 * l14) - (l10 * l13);
  1565. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1566. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1567. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1568. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1569. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1570. var l28 = (l7 * l16) - (l8 * l15);
  1571. var l29 = (l6 * l16) - (l8 * l14);
  1572. var l30 = (l6 * l15) - (l7 * l14);
  1573. var l31 = (l5 * l16) - (l8 * l13);
  1574. var l32 = (l5 * l15) - (l7 * l13);
  1575. var l33 = (l5 * l14) - (l6 * l13);
  1576. var l34 = (l7 * l12) - (l8 * l11);
  1577. var l35 = (l6 * l12) - (l8 * l10);
  1578. var l36 = (l6 * l11) - (l7 * l10);
  1579. var l37 = (l5 * l12) - (l8 * l9);
  1580. var l38 = (l5 * l11) - (l7 * l9);
  1581. var l39 = (l5 * l10) - (l6 * l9);
  1582. other.m[0] = l23 * l27;
  1583. other.m[4] = l24 * l27;
  1584. other.m[8] = l25 * l27;
  1585. other.m[12] = l26 * l27;
  1586. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1587. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1588. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1589. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1590. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1591. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1592. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1593. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1594. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1595. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1596. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1597. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1598. return this;
  1599. };
  1600. Matrix.prototype.invertToRefSIMD = function (other) {
  1601. var src = this.m;
  1602. var dest = other.m;
  1603. var row0, row1, row2, row3;
  1604. var tmp1;
  1605. var minor0, minor1, minor2, minor3;
  1606. var det;
  1607. // Load the 4 rows
  1608. var src0 = SIMD.float32x4.load(src, 0);
  1609. var src1 = SIMD.float32x4.load(src, 4);
  1610. var src2 = SIMD.float32x4.load(src, 8);
  1611. var src3 = SIMD.float32x4.load(src, 12);
  1612. // Transpose the source matrix. Sort of. Not a true transpose operation
  1613. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1614. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1615. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1616. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1617. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1618. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1619. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1620. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1621. // This is a true transposition, but it will lead to an incorrect result
  1622. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1623. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1624. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1625. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1626. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1627. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1628. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1629. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1630. // ----
  1631. tmp1 = SIMD.float32x4.mul(row2, row3);
  1632. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1633. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1634. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1635. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1636. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1637. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1638. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1639. // ----
  1640. tmp1 = SIMD.float32x4.mul(row1, row2);
  1641. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1643. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1646. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1647. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1652. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1653. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1654. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1655. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1656. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1657. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1658. // ----
  1659. tmp1 = SIMD.float32x4.mul(row0, row1);
  1660. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1661. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1662. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1663. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1664. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1665. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1666. // ----
  1667. tmp1 = SIMD.float32x4.mul(row0, row3);
  1668. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1669. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1670. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1671. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1672. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1673. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1674. // ----
  1675. tmp1 = SIMD.float32x4.mul(row0, row2);
  1676. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1677. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1678. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1679. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1680. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1681. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1682. // Compute determinant
  1683. det = SIMD.float32x4.mul(row0, minor0);
  1684. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1685. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1686. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1687. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1688. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1689. // These shuffles aren't necessary if the faulty transposition is done
  1690. // up at the top of this function.
  1691. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1692. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1693. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1694. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1695. // Compute final values by multiplying with 1/det
  1696. minor0 = SIMD.float32x4.mul(det, minor0);
  1697. minor1 = SIMD.float32x4.mul(det, minor1);
  1698. minor2 = SIMD.float32x4.mul(det, minor2);
  1699. minor3 = SIMD.float32x4.mul(det, minor3);
  1700. SIMD.float32x4.store(dest, 0, minor0);
  1701. SIMD.float32x4.store(dest, 4, minor1);
  1702. SIMD.float32x4.store(dest, 8, minor2);
  1703. SIMD.float32x4.store(dest, 12, minor3);
  1704. return this;
  1705. };
  1706. Matrix.prototype.setTranslation = function (vector3) {
  1707. this.m[12] = vector3.x;
  1708. this.m[13] = vector3.y;
  1709. this.m[14] = vector3.z;
  1710. return this;
  1711. };
  1712. Matrix.prototype.multiply = function (other) {
  1713. var result = new Matrix();
  1714. this.multiplyToRef(other, result);
  1715. return result;
  1716. };
  1717. Matrix.prototype.copyFrom = function (other) {
  1718. for (var index = 0; index < 16; index++) {
  1719. this.m[index] = other.m[index];
  1720. }
  1721. return this;
  1722. };
  1723. Matrix.prototype.copyToArray = function (array, offset) {
  1724. if (offset === void 0) { offset = 0; }
  1725. for (var index = 0; index < 16; index++) {
  1726. array[offset + index] = this.m[index];
  1727. }
  1728. return this;
  1729. };
  1730. Matrix.prototype.multiplyToRef = function (other, result) {
  1731. this.multiplyToArray(other, result.m, 0);
  1732. return this;
  1733. };
  1734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1735. var tm0 = this.m[0];
  1736. var tm1 = this.m[1];
  1737. var tm2 = this.m[2];
  1738. var tm3 = this.m[3];
  1739. var tm4 = this.m[4];
  1740. var tm5 = this.m[5];
  1741. var tm6 = this.m[6];
  1742. var tm7 = this.m[7];
  1743. var tm8 = this.m[8];
  1744. var tm9 = this.m[9];
  1745. var tm10 = this.m[10];
  1746. var tm11 = this.m[11];
  1747. var tm12 = this.m[12];
  1748. var tm13 = this.m[13];
  1749. var tm14 = this.m[14];
  1750. var tm15 = this.m[15];
  1751. var om0 = other.m[0];
  1752. var om1 = other.m[1];
  1753. var om2 = other.m[2];
  1754. var om3 = other.m[3];
  1755. var om4 = other.m[4];
  1756. var om5 = other.m[5];
  1757. var om6 = other.m[6];
  1758. var om7 = other.m[7];
  1759. var om8 = other.m[8];
  1760. var om9 = other.m[9];
  1761. var om10 = other.m[10];
  1762. var om11 = other.m[11];
  1763. var om12 = other.m[12];
  1764. var om13 = other.m[13];
  1765. var om14 = other.m[14];
  1766. var om15 = other.m[15];
  1767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1783. return this;
  1784. };
  1785. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1786. if (offset === void 0) { offset = 0; }
  1787. var tm = this.m;
  1788. var om = other.m;
  1789. var om0 = SIMD.float32x4.load(om, 0);
  1790. var om1 = SIMD.float32x4.load(om, 4);
  1791. var om2 = SIMD.float32x4.load(om, 8);
  1792. var om3 = SIMD.float32x4.load(om, 12);
  1793. var tm0 = SIMD.float32x4.load(tm, 0);
  1794. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1795. var tm1 = SIMD.float32x4.load(tm, 4);
  1796. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1797. var tm2 = SIMD.float32x4.load(tm, 8);
  1798. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1799. var tm3 = SIMD.float32x4.load(tm, 12);
  1800. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1801. };
  1802. Matrix.prototype.equals = function (value) {
  1803. return value &&
  1804. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1805. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1806. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1807. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1808. };
  1809. Matrix.prototype.clone = function () {
  1810. 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]);
  1811. };
  1812. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1813. translation.x = this.m[12];
  1814. translation.y = this.m[13];
  1815. translation.z = this.m[14];
  1816. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1817. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1818. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1819. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1820. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1821. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1822. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1823. rotation.x = 0;
  1824. rotation.y = 0;
  1825. rotation.z = 0;
  1826. rotation.w = 1;
  1827. return false;
  1828. }
  1829. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1830. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1831. return true;
  1832. };
  1833. // Statics
  1834. Matrix.FromArray = function (array, offset) {
  1835. var result = new Matrix();
  1836. if (!offset) {
  1837. offset = 0;
  1838. }
  1839. Matrix.FromArrayToRef(array, offset, result);
  1840. return result;
  1841. };
  1842. Matrix.FromArrayToRef = function (array, offset, result) {
  1843. for (var index = 0; index < 16; index++) {
  1844. result.m[index] = array[index + offset];
  1845. }
  1846. };
  1847. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1848. for (var index = 0; index < 16; index++) {
  1849. result.m[index] = array[index + offset] * scale;
  1850. }
  1851. };
  1852. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1853. result.m[0] = initialM11;
  1854. result.m[1] = initialM12;
  1855. result.m[2] = initialM13;
  1856. result.m[3] = initialM14;
  1857. result.m[4] = initialM21;
  1858. result.m[5] = initialM22;
  1859. result.m[6] = initialM23;
  1860. result.m[7] = initialM24;
  1861. result.m[8] = initialM31;
  1862. result.m[9] = initialM32;
  1863. result.m[10] = initialM33;
  1864. result.m[11] = initialM34;
  1865. result.m[12] = initialM41;
  1866. result.m[13] = initialM42;
  1867. result.m[14] = initialM43;
  1868. result.m[15] = initialM44;
  1869. };
  1870. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1871. var result = new Matrix();
  1872. result.m[0] = initialM11;
  1873. result.m[1] = initialM12;
  1874. result.m[2] = initialM13;
  1875. result.m[3] = initialM14;
  1876. result.m[4] = initialM21;
  1877. result.m[5] = initialM22;
  1878. result.m[6] = initialM23;
  1879. result.m[7] = initialM24;
  1880. result.m[8] = initialM31;
  1881. result.m[9] = initialM32;
  1882. result.m[10] = initialM33;
  1883. result.m[11] = initialM34;
  1884. result.m[12] = initialM41;
  1885. result.m[13] = initialM42;
  1886. result.m[14] = initialM43;
  1887. result.m[15] = initialM44;
  1888. return result;
  1889. };
  1890. Matrix.Compose = function (scale, rotation, translation) {
  1891. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1892. var rotationMatrix = Matrix.Identity();
  1893. rotation.toRotationMatrix(rotationMatrix);
  1894. result = result.multiply(rotationMatrix);
  1895. result.setTranslation(translation);
  1896. return result;
  1897. };
  1898. Matrix.Identity = function () {
  1899. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1900. };
  1901. Matrix.IdentityToRef = function (result) {
  1902. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1903. };
  1904. Matrix.Zero = function () {
  1905. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1906. };
  1907. Matrix.RotationX = function (angle) {
  1908. var result = new Matrix();
  1909. Matrix.RotationXToRef(angle, result);
  1910. return result;
  1911. };
  1912. Matrix.Invert = function (source) {
  1913. var result = new Matrix();
  1914. source.invertToRef(result);
  1915. return result;
  1916. };
  1917. Matrix.RotationXToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[0] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[5] = c;
  1923. result.m[10] = c;
  1924. result.m[9] = -s;
  1925. result.m[6] = s;
  1926. result.m[1] = 0;
  1927. result.m[2] = 0;
  1928. result.m[3] = 0;
  1929. result.m[4] = 0;
  1930. result.m[7] = 0;
  1931. result.m[8] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationY = function (angle) {
  1938. var result = new Matrix();
  1939. Matrix.RotationYToRef(angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationYToRef = function (angle, result) {
  1943. var s = Math.sin(angle);
  1944. var c = Math.cos(angle);
  1945. result.m[5] = 1.0;
  1946. result.m[15] = 1.0;
  1947. result.m[0] = c;
  1948. result.m[2] = -s;
  1949. result.m[8] = s;
  1950. result.m[10] = c;
  1951. result.m[1] = 0;
  1952. result.m[3] = 0;
  1953. result.m[4] = 0;
  1954. result.m[6] = 0;
  1955. result.m[7] = 0;
  1956. result.m[9] = 0;
  1957. result.m[11] = 0;
  1958. result.m[12] = 0;
  1959. result.m[13] = 0;
  1960. result.m[14] = 0;
  1961. };
  1962. Matrix.RotationZ = function (angle) {
  1963. var result = new Matrix();
  1964. Matrix.RotationZToRef(angle, result);
  1965. return result;
  1966. };
  1967. Matrix.RotationZToRef = function (angle, result) {
  1968. var s = Math.sin(angle);
  1969. var c = Math.cos(angle);
  1970. result.m[10] = 1.0;
  1971. result.m[15] = 1.0;
  1972. result.m[0] = c;
  1973. result.m[1] = s;
  1974. result.m[4] = -s;
  1975. result.m[5] = c;
  1976. result.m[2] = 0;
  1977. result.m[3] = 0;
  1978. result.m[6] = 0;
  1979. result.m[7] = 0;
  1980. result.m[8] = 0;
  1981. result.m[9] = 0;
  1982. result.m[11] = 0;
  1983. result.m[12] = 0;
  1984. result.m[13] = 0;
  1985. result.m[14] = 0;
  1986. };
  1987. Matrix.RotationAxis = function (axis, angle) {
  1988. var s = Math.sin(-angle);
  1989. var c = Math.cos(-angle);
  1990. var c1 = 1 - c;
  1991. axis.normalize();
  1992. var result = Matrix.Zero();
  1993. result.m[0] = (axis.x * axis.x) * c1 + c;
  1994. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1995. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1996. result.m[3] = 0.0;
  1997. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1998. result.m[5] = (axis.y * axis.y) * c1 + c;
  1999. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2000. result.m[7] = 0.0;
  2001. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2002. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2003. result.m[10] = (axis.z * axis.z) * c1 + c;
  2004. result.m[11] = 0.0;
  2005. result.m[15] = 1.0;
  2006. return result;
  2007. };
  2008. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2009. var result = new Matrix();
  2010. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2011. return result;
  2012. };
  2013. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2014. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2015. this._tempQuaternion.toRotationMatrix(result);
  2016. };
  2017. Matrix.Scaling = function (x, y, z) {
  2018. var result = Matrix.Zero();
  2019. Matrix.ScalingToRef(x, y, z, result);
  2020. return result;
  2021. };
  2022. Matrix.ScalingToRef = function (x, y, z, result) {
  2023. result.m[0] = x;
  2024. result.m[1] = 0;
  2025. result.m[2] = 0;
  2026. result.m[3] = 0;
  2027. result.m[4] = 0;
  2028. result.m[5] = y;
  2029. result.m[6] = 0;
  2030. result.m[7] = 0;
  2031. result.m[8] = 0;
  2032. result.m[9] = 0;
  2033. result.m[10] = z;
  2034. result.m[11] = 0;
  2035. result.m[12] = 0;
  2036. result.m[13] = 0;
  2037. result.m[14] = 0;
  2038. result.m[15] = 1.0;
  2039. };
  2040. Matrix.Translation = function (x, y, z) {
  2041. var result = Matrix.Identity();
  2042. Matrix.TranslationToRef(x, y, z, result);
  2043. return result;
  2044. };
  2045. Matrix.TranslationToRef = function (x, y, z, result) {
  2046. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2047. };
  2048. Matrix.LookAtLH = function (eye, target, up) {
  2049. var result = Matrix.Zero();
  2050. Matrix.LookAtLHToRef(eye, target, up, result);
  2051. return result;
  2052. };
  2053. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2054. // Z axis
  2055. target.subtractToRef(eye, this._zAxis);
  2056. this._zAxis.normalize();
  2057. // X axis
  2058. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2059. if (this._xAxis.lengthSquared() === 0) {
  2060. this._xAxis.x = 1.0;
  2061. }
  2062. else {
  2063. this._xAxis.normalize();
  2064. }
  2065. // Y axis
  2066. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2067. this._yAxis.normalize();
  2068. // Eye angles
  2069. var ex = -Vector3.Dot(this._xAxis, eye);
  2070. var ey = -Vector3.Dot(this._yAxis, eye);
  2071. var ez = -Vector3.Dot(this._zAxis, eye);
  2072. 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);
  2073. };
  2074. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2075. var out = result.m;
  2076. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2077. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2078. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2079. // cc.kmVec3Subtract(f, pCenter, pEye);
  2080. var f = SIMD.float32x4.sub(center, eye);
  2081. // cc.kmVec3Normalize(f, f);
  2082. var tmp = SIMD.float32x4.mul(f, f);
  2083. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2084. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2085. // cc.kmVec3Assign(up, pUp);
  2086. // cc.kmVec3Normalize(up, up);
  2087. tmp = SIMD.float32x4.mul(up, up);
  2088. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2089. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2090. // cc.kmVec3Cross(s, f, up);
  2091. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  2092. // cc.kmVec3Normalize(s, s);
  2093. tmp = SIMD.float32x4.mul(s, s);
  2094. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2095. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2096. // cc.kmVec3Cross(u, s, f);
  2097. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  2098. // cc.kmVec3Normalize(s, s);
  2099. tmp = SIMD.float32x4.mul(s, s);
  2100. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2101. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2102. var zero = SIMD.float32x4.splat(0.0);
  2103. s = SIMD.float32x4.neg(s);
  2104. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2105. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2106. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2107. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2108. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2109. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2110. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2111. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2112. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2113. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2114. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2115. var b3 = SIMD.float32x4.neg(eye);
  2116. b3 = SIMD.float32x4.withW(b3, 1.0);
  2117. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2118. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2119. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2120. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2121. };
  2122. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2123. var matrix = Matrix.Zero();
  2124. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2125. return matrix;
  2126. };
  2127. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2128. var hw = 2.0 / width;
  2129. var hh = 2.0 / height;
  2130. var id = 1.0 / (zfar - znear);
  2131. var nid = znear / (znear - zfar);
  2132. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2133. };
  2134. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2135. var matrix = Matrix.Zero();
  2136. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2137. return matrix;
  2138. };
  2139. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2140. result.m[0] = 2.0 / (right - left);
  2141. result.m[1] = result.m[2] = result.m[3] = 0;
  2142. result.m[5] = 2.0 / (top - bottom);
  2143. result.m[4] = result.m[6] = result.m[7] = 0;
  2144. result.m[10] = -1.0 / (znear - zfar);
  2145. result.m[8] = result.m[9] = result.m[11] = 0;
  2146. result.m[12] = (left + right) / (left - right);
  2147. result.m[13] = (top + bottom) / (bottom - top);
  2148. result.m[14] = znear / (znear - zfar);
  2149. result.m[15] = 1.0;
  2150. };
  2151. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2152. var matrix = Matrix.Zero();
  2153. matrix.m[0] = (2.0 * znear) / width;
  2154. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2155. matrix.m[5] = (2.0 * znear) / height;
  2156. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2157. matrix.m[10] = -zfar / (znear - zfar);
  2158. matrix.m[8] = matrix.m[9] = 0.0;
  2159. matrix.m[11] = 1.0;
  2160. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2161. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2162. return matrix;
  2163. };
  2164. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2165. var matrix = Matrix.Zero();
  2166. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2167. return matrix;
  2168. };
  2169. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2170. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2171. var tan = 1.0 / (Math.tan(fov * 0.5));
  2172. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2173. if (v_fixed) {
  2174. result.m[0] = tan / aspect;
  2175. }
  2176. else {
  2177. result.m[0] = tan;
  2178. }
  2179. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2180. if (v_fixed) {
  2181. result.m[5] = tan;
  2182. }
  2183. else {
  2184. result.m[5] = tan * aspect;
  2185. }
  2186. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2187. result.m[8] = result.m[9] = 0.0;
  2188. result.m[10] = -zfar / (znear - zfar);
  2189. result.m[11] = 1.0;
  2190. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2191. result.m[14] = (znear * zfar) / (znear - zfar);
  2192. };
  2193. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2194. var cw = viewport.width;
  2195. var ch = viewport.height;
  2196. var cx = viewport.x;
  2197. var cy = viewport.y;
  2198. 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);
  2199. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2200. };
  2201. Matrix.GetAsMatrix2x2 = function (matrix) {
  2202. return new Float32Array([
  2203. matrix.m[0], matrix.m[1],
  2204. matrix.m[4], matrix.m[5]
  2205. ]);
  2206. };
  2207. Matrix.GetAsMatrix3x3 = function (matrix) {
  2208. return new Float32Array([
  2209. matrix.m[0], matrix.m[1], matrix.m[2],
  2210. matrix.m[4], matrix.m[5], matrix.m[6],
  2211. matrix.m[8], matrix.m[9], matrix.m[10]
  2212. ]);
  2213. };
  2214. Matrix.Transpose = function (matrix) {
  2215. var result = new Matrix();
  2216. result.m[0] = matrix.m[0];
  2217. result.m[1] = matrix.m[4];
  2218. result.m[2] = matrix.m[8];
  2219. result.m[3] = matrix.m[12];
  2220. result.m[4] = matrix.m[1];
  2221. result.m[5] = matrix.m[5];
  2222. result.m[6] = matrix.m[9];
  2223. result.m[7] = matrix.m[13];
  2224. result.m[8] = matrix.m[2];
  2225. result.m[9] = matrix.m[6];
  2226. result.m[10] = matrix.m[10];
  2227. result.m[11] = matrix.m[14];
  2228. result.m[12] = matrix.m[3];
  2229. result.m[13] = matrix.m[7];
  2230. result.m[14] = matrix.m[11];
  2231. result.m[15] = matrix.m[15];
  2232. return result;
  2233. };
  2234. Matrix.Reflection = function (plane) {
  2235. var matrix = new Matrix();
  2236. Matrix.ReflectionToRef(plane, matrix);
  2237. return matrix;
  2238. };
  2239. Matrix.ReflectionToRef = function (plane, result) {
  2240. plane.normalize();
  2241. var x = plane.normal.x;
  2242. var y = plane.normal.y;
  2243. var z = plane.normal.z;
  2244. var temp = -2 * x;
  2245. var temp2 = -2 * y;
  2246. var temp3 = -2 * z;
  2247. result.m[0] = (temp * x) + 1;
  2248. result.m[1] = temp2 * x;
  2249. result.m[2] = temp3 * x;
  2250. result.m[3] = 0.0;
  2251. result.m[4] = temp * y;
  2252. result.m[5] = (temp2 * y) + 1;
  2253. result.m[6] = temp3 * y;
  2254. result.m[7] = 0.0;
  2255. result.m[8] = temp * z;
  2256. result.m[9] = temp2 * z;
  2257. result.m[10] = (temp3 * z) + 1;
  2258. result.m[11] = 0.0;
  2259. result.m[12] = temp * plane.d;
  2260. result.m[13] = temp2 * plane.d;
  2261. result.m[14] = temp3 * plane.d;
  2262. result.m[15] = 1.0;
  2263. };
  2264. Matrix._tempQuaternion = new Quaternion();
  2265. Matrix._xAxis = Vector3.Zero();
  2266. Matrix._yAxis = Vector3.Zero();
  2267. Matrix._zAxis = Vector3.Zero();
  2268. return Matrix;
  2269. })();
  2270. BABYLON.Matrix = Matrix;
  2271. var Plane = (function () {
  2272. function Plane(a, b, c, d) {
  2273. this.normal = new Vector3(a, b, c);
  2274. this.d = d;
  2275. }
  2276. Plane.prototype.asArray = function () {
  2277. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2278. };
  2279. // Methods
  2280. Plane.prototype.clone = function () {
  2281. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2282. };
  2283. Plane.prototype.normalize = function () {
  2284. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2285. var magnitude = 0;
  2286. if (norm !== 0) {
  2287. magnitude = 1.0 / norm;
  2288. }
  2289. this.normal.x *= magnitude;
  2290. this.normal.y *= magnitude;
  2291. this.normal.z *= magnitude;
  2292. this.d *= magnitude;
  2293. return this;
  2294. };
  2295. Plane.prototype.transform = function (transformation) {
  2296. var transposedMatrix = Matrix.Transpose(transformation);
  2297. var x = this.normal.x;
  2298. var y = this.normal.y;
  2299. var z = this.normal.z;
  2300. var d = this.d;
  2301. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2302. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2303. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2304. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2305. return new Plane(normalX, normalY, normalZ, finalD);
  2306. };
  2307. Plane.prototype.dotCoordinate = function (point) {
  2308. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2309. };
  2310. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2311. var x1 = point2.x - point1.x;
  2312. var y1 = point2.y - point1.y;
  2313. var z1 = point2.z - point1.z;
  2314. var x2 = point3.x - point1.x;
  2315. var y2 = point3.y - point1.y;
  2316. var z2 = point3.z - point1.z;
  2317. var yz = (y1 * z2) - (z1 * y2);
  2318. var xz = (z1 * x2) - (x1 * z2);
  2319. var xy = (x1 * y2) - (y1 * x2);
  2320. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2321. var invPyth;
  2322. if (pyth !== 0) {
  2323. invPyth = 1.0 / pyth;
  2324. }
  2325. else {
  2326. invPyth = 0;
  2327. }
  2328. this.normal.x = yz * invPyth;
  2329. this.normal.y = xz * invPyth;
  2330. this.normal.z = xy * invPyth;
  2331. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2332. return this;
  2333. };
  2334. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2335. var dot = Vector3.Dot(this.normal, direction);
  2336. return (dot <= epsilon);
  2337. };
  2338. Plane.prototype.signedDistanceTo = function (point) {
  2339. return Vector3.Dot(point, this.normal) + this.d;
  2340. };
  2341. // Statics
  2342. Plane.FromArray = function (array) {
  2343. return new Plane(array[0], array[1], array[2], array[3]);
  2344. };
  2345. Plane.FromPoints = function (point1, point2, point3) {
  2346. var result = new Plane(0, 0, 0, 0);
  2347. result.copyFromPoints(point1, point2, point3);
  2348. return result;
  2349. };
  2350. Plane.FromPositionAndNormal = function (origin, normal) {
  2351. var result = new Plane(0, 0, 0, 0);
  2352. normal.normalize();
  2353. result.normal = normal;
  2354. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2355. return result;
  2356. };
  2357. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2358. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2359. return Vector3.Dot(point, normal) + d;
  2360. };
  2361. return Plane;
  2362. })();
  2363. BABYLON.Plane = Plane;
  2364. var Viewport = (function () {
  2365. function Viewport(x, y, width, height) {
  2366. this.x = x;
  2367. this.y = y;
  2368. this.width = width;
  2369. this.height = height;
  2370. }
  2371. Viewport.prototype.toGlobal = function (engine) {
  2372. var width = engine.getRenderWidth();
  2373. var height = engine.getRenderHeight();
  2374. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2375. };
  2376. return Viewport;
  2377. })();
  2378. BABYLON.Viewport = Viewport;
  2379. var Frustum = (function () {
  2380. function Frustum() {
  2381. }
  2382. Frustum.GetPlanes = function (transform) {
  2383. var frustumPlanes = [];
  2384. for (var index = 0; index < 6; index++) {
  2385. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2386. }
  2387. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2388. return frustumPlanes;
  2389. };
  2390. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2391. // Near
  2392. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2393. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2394. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2395. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2396. frustumPlanes[0].normalize();
  2397. // Far
  2398. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2399. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2400. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2401. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2402. frustumPlanes[1].normalize();
  2403. // Left
  2404. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2405. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2406. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2407. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2408. frustumPlanes[2].normalize();
  2409. // Right
  2410. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2411. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2412. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2413. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2414. frustumPlanes[3].normalize();
  2415. // Top
  2416. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2417. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2418. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2419. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2420. frustumPlanes[4].normalize();
  2421. // Bottom
  2422. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2423. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2424. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2425. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2426. frustumPlanes[5].normalize();
  2427. };
  2428. return Frustum;
  2429. })();
  2430. BABYLON.Frustum = Frustum;
  2431. var Ray = (function () {
  2432. function Ray(origin, direction, length) {
  2433. if (length === void 0) { length = Number.MAX_VALUE; }
  2434. this.origin = origin;
  2435. this.direction = direction;
  2436. this.length = length;
  2437. }
  2438. // Methods
  2439. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2440. var d = 0.0;
  2441. var maxValue = Number.MAX_VALUE;
  2442. var inv;
  2443. var min;
  2444. var max;
  2445. var temp;
  2446. if (Math.abs(this.direction.x) < 0.0000001) {
  2447. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2448. return false;
  2449. }
  2450. }
  2451. else {
  2452. inv = 1.0 / this.direction.x;
  2453. min = (minimum.x - this.origin.x) * inv;
  2454. max = (maximum.x - this.origin.x) * inv;
  2455. if (max === -Infinity) {
  2456. max = Infinity;
  2457. }
  2458. if (min > max) {
  2459. temp = min;
  2460. min = max;
  2461. max = temp;
  2462. }
  2463. d = Math.max(min, d);
  2464. maxValue = Math.min(max, maxValue);
  2465. if (d > maxValue) {
  2466. return false;
  2467. }
  2468. }
  2469. if (Math.abs(this.direction.y) < 0.0000001) {
  2470. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2471. return false;
  2472. }
  2473. }
  2474. else {
  2475. inv = 1.0 / this.direction.y;
  2476. min = (minimum.y - this.origin.y) * inv;
  2477. max = (maximum.y - this.origin.y) * inv;
  2478. if (max === -Infinity) {
  2479. max = Infinity;
  2480. }
  2481. if (min > max) {
  2482. temp = min;
  2483. min = max;
  2484. max = temp;
  2485. }
  2486. d = Math.max(min, d);
  2487. maxValue = Math.min(max, maxValue);
  2488. if (d > maxValue) {
  2489. return false;
  2490. }
  2491. }
  2492. if (Math.abs(this.direction.z) < 0.0000001) {
  2493. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2494. return false;
  2495. }
  2496. }
  2497. else {
  2498. inv = 1.0 / this.direction.z;
  2499. min = (minimum.z - this.origin.z) * inv;
  2500. max = (maximum.z - this.origin.z) * inv;
  2501. if (max === -Infinity) {
  2502. max = Infinity;
  2503. }
  2504. if (min > max) {
  2505. temp = min;
  2506. min = max;
  2507. max = temp;
  2508. }
  2509. d = Math.max(min, d);
  2510. maxValue = Math.min(max, maxValue);
  2511. if (d > maxValue) {
  2512. return false;
  2513. }
  2514. }
  2515. return true;
  2516. };
  2517. Ray.prototype.intersectsBox = function (box) {
  2518. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2519. };
  2520. Ray.prototype.intersectsSphere = function (sphere) {
  2521. var x = sphere.center.x - this.origin.x;
  2522. var y = sphere.center.y - this.origin.y;
  2523. var z = sphere.center.z - this.origin.z;
  2524. var pyth = (x * x) + (y * y) + (z * z);
  2525. var rr = sphere.radius * sphere.radius;
  2526. if (pyth <= rr) {
  2527. return true;
  2528. }
  2529. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2530. if (dot < 0.0) {
  2531. return false;
  2532. }
  2533. var temp = pyth - (dot * dot);
  2534. return temp <= rr;
  2535. };
  2536. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2537. if (!this._edge1) {
  2538. this._edge1 = Vector3.Zero();
  2539. this._edge2 = Vector3.Zero();
  2540. this._pvec = Vector3.Zero();
  2541. this._tvec = Vector3.Zero();
  2542. this._qvec = Vector3.Zero();
  2543. }
  2544. vertex1.subtractToRef(vertex0, this._edge1);
  2545. vertex2.subtractToRef(vertex0, this._edge2);
  2546. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2547. var det = Vector3.Dot(this._edge1, this._pvec);
  2548. if (det === 0) {
  2549. return null;
  2550. }
  2551. var invdet = 1 / det;
  2552. this.origin.subtractToRef(vertex0, this._tvec);
  2553. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2554. if (bu < 0 || bu > 1.0) {
  2555. return null;
  2556. }
  2557. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2558. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2559. if (bv < 0 || bu + bv > 1.0) {
  2560. return null;
  2561. }
  2562. //check if the distance is longer than the predefined length.
  2563. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2564. if (distance > this.length) {
  2565. return null;
  2566. }
  2567. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2568. };
  2569. // Statics
  2570. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2571. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2572. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2573. var direction = end.subtract(start);
  2574. direction.normalize();
  2575. return new Ray(start, direction);
  2576. };
  2577. /**
  2578. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2579. * transformed to the given world matrix.
  2580. * @param origin The origin point
  2581. * @param end The end point
  2582. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2583. */
  2584. Ray.CreateNewFromTo = function (origin, end, world) {
  2585. if (world === void 0) { world = Matrix.Identity(); }
  2586. var direction = end.subtract(origin);
  2587. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2588. direction.normalize();
  2589. return Ray.Transform(new Ray(origin, direction, length), world);
  2590. };
  2591. Ray.Transform = function (ray, matrix) {
  2592. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2593. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2594. return new Ray(newOrigin, newDirection, ray.length);
  2595. };
  2596. return Ray;
  2597. })();
  2598. BABYLON.Ray = Ray;
  2599. (function (Space) {
  2600. Space[Space["LOCAL"] = 0] = "LOCAL";
  2601. Space[Space["WORLD"] = 1] = "WORLD";
  2602. })(BABYLON.Space || (BABYLON.Space = {}));
  2603. var Space = BABYLON.Space;
  2604. var Axis = (function () {
  2605. function Axis() {
  2606. }
  2607. Axis.X = new Vector3(1, 0, 0);
  2608. Axis.Y = new Vector3(0, 1, 0);
  2609. Axis.Z = new Vector3(0, 0, 1);
  2610. return Axis;
  2611. })();
  2612. BABYLON.Axis = Axis;
  2613. ;
  2614. var BezierCurve = (function () {
  2615. function BezierCurve() {
  2616. }
  2617. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2618. // Extract X (which is equal to time here)
  2619. var f0 = 1 - 3 * x2 + 3 * x1;
  2620. var f1 = 3 * x2 - 6 * x1;
  2621. var f2 = 3 * x1;
  2622. var refinedT = t;
  2623. for (var i = 0; i < 5; i++) {
  2624. var refinedT2 = refinedT * refinedT;
  2625. var refinedT3 = refinedT2 * refinedT;
  2626. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2627. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2628. refinedT -= (x - t) * slope;
  2629. refinedT = Math.min(1, Math.max(0, refinedT));
  2630. }
  2631. // Resolve cubic bezier for the given x
  2632. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2633. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2634. Math.pow(refinedT, 3);
  2635. };
  2636. return BezierCurve;
  2637. })();
  2638. BABYLON.BezierCurve = BezierCurve;
  2639. (function (Orientation) {
  2640. Orientation[Orientation["CW"] = 0] = "CW";
  2641. Orientation[Orientation["CCW"] = 1] = "CCW";
  2642. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2643. var Orientation = BABYLON.Orientation;
  2644. var Angle = (function () {
  2645. function Angle(radians) {
  2646. var _this = this;
  2647. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2648. this.radians = function () { return _this._radians; };
  2649. this._radians = radians;
  2650. if (this._radians < 0)
  2651. this._radians += (2 * Math.PI);
  2652. }
  2653. Angle.BetweenTwoPoints = function (a, b) {
  2654. var delta = b.subtract(a);
  2655. var theta = Math.atan2(delta.y, delta.x);
  2656. return new Angle(theta);
  2657. };
  2658. Angle.FromRadians = function (radians) {
  2659. return new Angle(radians);
  2660. };
  2661. Angle.FromDegrees = function (degrees) {
  2662. return new Angle(degrees * Math.PI / 180);
  2663. };
  2664. return Angle;
  2665. })();
  2666. BABYLON.Angle = Angle;
  2667. var Arc2 = (function () {
  2668. function Arc2(startPoint, midPoint, endPoint) {
  2669. this.startPoint = startPoint;
  2670. this.midPoint = midPoint;
  2671. this.endPoint = endPoint;
  2672. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2673. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2674. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2675. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2676. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2677. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2678. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2679. var a1 = this.startAngle.degrees();
  2680. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2681. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2682. // angles correction
  2683. if (a2 - a1 > +180.0)
  2684. a2 -= 360.0;
  2685. if (a2 - a1 < -180.0)
  2686. a2 += 360.0;
  2687. if (a3 - a2 > +180.0)
  2688. a3 -= 360.0;
  2689. if (a3 - a2 < -180.0)
  2690. a3 += 360.0;
  2691. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2692. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2693. }
  2694. return Arc2;
  2695. })();
  2696. BABYLON.Arc2 = Arc2;
  2697. var PathCursor = (function () {
  2698. function PathCursor(path) {
  2699. this.path = path;
  2700. this._onchange = new Array();
  2701. this.value = 0;
  2702. this.animations = new Array();
  2703. }
  2704. PathCursor.prototype.getPoint = function () {
  2705. var point = this.path.getPointAtLengthPosition(this.value);
  2706. return new Vector3(point.x, 0, point.y);
  2707. };
  2708. PathCursor.prototype.moveAhead = function (step) {
  2709. if (step === void 0) { step = 0.002; }
  2710. this.move(step);
  2711. return this;
  2712. };
  2713. PathCursor.prototype.moveBack = function (step) {
  2714. if (step === void 0) { step = 0.002; }
  2715. this.move(-step);
  2716. return this;
  2717. };
  2718. PathCursor.prototype.move = function (step) {
  2719. if (Math.abs(step) > 1) {
  2720. throw "step size should be less than 1.";
  2721. }
  2722. this.value += step;
  2723. this.ensureLimits();
  2724. this.raiseOnChange();
  2725. return this;
  2726. };
  2727. PathCursor.prototype.ensureLimits = function () {
  2728. while (this.value > 1) {
  2729. this.value -= 1;
  2730. }
  2731. while (this.value < 0) {
  2732. this.value += 1;
  2733. }
  2734. return this;
  2735. };
  2736. // used by animation engine
  2737. PathCursor.prototype.markAsDirty = function (propertyName) {
  2738. this.ensureLimits();
  2739. this.raiseOnChange();
  2740. return this;
  2741. };
  2742. PathCursor.prototype.raiseOnChange = function () {
  2743. var _this = this;
  2744. this._onchange.forEach(function (f) { return f(_this); });
  2745. return this;
  2746. };
  2747. PathCursor.prototype.onchange = function (f) {
  2748. this._onchange.push(f);
  2749. return this;
  2750. };
  2751. return PathCursor;
  2752. })();
  2753. BABYLON.PathCursor = PathCursor;
  2754. var Path2 = (function () {
  2755. function Path2(x, y) {
  2756. this._points = new Array();
  2757. this._length = 0;
  2758. this.closed = false;
  2759. this._points.push(new Vector2(x, y));
  2760. }
  2761. Path2.prototype.addLineTo = function (x, y) {
  2762. if (closed) {
  2763. BABYLON.Tools.Error("cannot add lines to closed paths");
  2764. return this;
  2765. }
  2766. var newPoint = new Vector2(x, y);
  2767. var previousPoint = this._points[this._points.length - 1];
  2768. this._points.push(newPoint);
  2769. this._length += newPoint.subtract(previousPoint).length();
  2770. return this;
  2771. };
  2772. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2773. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2774. if (closed) {
  2775. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2776. return this;
  2777. }
  2778. var startPoint = this._points[this._points.length - 1];
  2779. var midPoint = new Vector2(midX, midY);
  2780. var endPoint = new Vector2(endX, endY);
  2781. var arc = new Arc2(startPoint, midPoint, endPoint);
  2782. var increment = arc.angle.radians() / numberOfSegments;
  2783. if (arc.orientation === Orientation.CW)
  2784. increment *= -1;
  2785. var currentAngle = arc.startAngle.radians() + increment;
  2786. for (var i = 0; i < numberOfSegments; i++) {
  2787. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2788. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2789. this.addLineTo(x, y);
  2790. currentAngle += increment;
  2791. }
  2792. return this;
  2793. };
  2794. Path2.prototype.close = function () {
  2795. this.closed = true;
  2796. return this;
  2797. };
  2798. Path2.prototype.length = function () {
  2799. var result = this._length;
  2800. if (!this.closed) {
  2801. var lastPoint = this._points[this._points.length - 1];
  2802. var firstPoint = this._points[0];
  2803. result += (firstPoint.subtract(lastPoint).length());
  2804. }
  2805. return result;
  2806. };
  2807. Path2.prototype.getPoints = function () {
  2808. return this._points;
  2809. };
  2810. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2811. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2812. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2813. return Vector2.Zero();
  2814. }
  2815. var lengthPosition = normalizedLengthPosition * this.length();
  2816. var previousOffset = 0;
  2817. for (var i = 0; i < this._points.length; i++) {
  2818. var j = (i + 1) % this._points.length;
  2819. var a = this._points[i];
  2820. var b = this._points[j];
  2821. var bToA = b.subtract(a);
  2822. var nextOffset = (bToA.length() + previousOffset);
  2823. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2824. var dir = bToA.normalize();
  2825. var localOffset = lengthPosition - previousOffset;
  2826. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2827. }
  2828. previousOffset = nextOffset;
  2829. }
  2830. BABYLON.Tools.Error("internal error");
  2831. return Vector2.Zero();
  2832. };
  2833. Path2.StartingAt = function (x, y) {
  2834. return new Path2(x, y);
  2835. };
  2836. return Path2;
  2837. })();
  2838. BABYLON.Path2 = Path2;
  2839. var Path3D = (function () {
  2840. /**
  2841. * new Path3D(path, normal, raw)
  2842. * path : an array of Vector3, the curve axis of the Path3D
  2843. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2844. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2845. */
  2846. function Path3D(path, firstNormal, raw) {
  2847. this.path = path;
  2848. this._curve = new Array();
  2849. this._distances = new Array();
  2850. this._tangents = new Array();
  2851. this._normals = new Array();
  2852. this._binormals = new Array();
  2853. for (var p = 0; p < path.length; p++) {
  2854. this._curve[p] = path[p].clone(); // hard copy
  2855. }
  2856. this._raw = raw || false;
  2857. this._compute(firstNormal);
  2858. }
  2859. Path3D.prototype.getCurve = function () {
  2860. return this._curve;
  2861. };
  2862. Path3D.prototype.getTangents = function () {
  2863. return this._tangents;
  2864. };
  2865. Path3D.prototype.getNormals = function () {
  2866. return this._normals;
  2867. };
  2868. Path3D.prototype.getBinormals = function () {
  2869. return this._binormals;
  2870. };
  2871. Path3D.prototype.getDistances = function () {
  2872. return this._distances;
  2873. };
  2874. Path3D.prototype.update = function (path, firstNormal) {
  2875. for (var p = 0; p < path.length; p++) {
  2876. this._curve[p].x = path[p].x;
  2877. this._curve[p].y = path[p].y;
  2878. this._curve[p].z = path[p].z;
  2879. }
  2880. this._compute(firstNormal);
  2881. return this;
  2882. };
  2883. // private function compute() : computes tangents, normals and binormals
  2884. Path3D.prototype._compute = function (firstNormal) {
  2885. var l = this._curve.length;
  2886. // first and last tangents
  2887. this._tangents[0] = this._getFirstNonNullVector(0);
  2888. if (!this._raw) {
  2889. this._tangents[0].normalize();
  2890. }
  2891. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2892. if (!this._raw) {
  2893. this._tangents[l - 1].normalize();
  2894. }
  2895. // normals and binormals at first point : arbitrary vector with _normalVector()
  2896. var tg0 = this._tangents[0];
  2897. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2898. this._normals[0] = pp0;
  2899. if (!this._raw) {
  2900. this._normals[0].normalize();
  2901. }
  2902. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2903. if (!this._raw) {
  2904. this._binormals[0].normalize();
  2905. }
  2906. this._distances[0] = 0;
  2907. // normals and binormals : next points
  2908. var prev; // previous vector (segment)
  2909. var cur; // current vector (segment)
  2910. var curTang; // current tangent
  2911. // previous normal
  2912. var prevBinor; // previous binormal
  2913. for (var i = 1; i < l; i++) {
  2914. // tangents
  2915. prev = this._getLastNonNullVector(i);
  2916. if (i < l - 1) {
  2917. cur = this._getFirstNonNullVector(i);
  2918. this._tangents[i] = prev.add(cur);
  2919. this._tangents[i].normalize();
  2920. }
  2921. this._distances[i] = this._distances[i - 1] + prev.length();
  2922. // normals and binormals
  2923. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2924. curTang = this._tangents[i];
  2925. prevBinor = this._binormals[i - 1];
  2926. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2927. if (!this._raw) {
  2928. this._normals[i].normalize();
  2929. }
  2930. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2931. if (!this._raw) {
  2932. this._binormals[i].normalize();
  2933. }
  2934. }
  2935. };
  2936. // private function getFirstNonNullVector(index)
  2937. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2938. Path3D.prototype._getFirstNonNullVector = function (index) {
  2939. var i = 1;
  2940. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2941. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2942. i++;
  2943. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2944. }
  2945. return nNVector;
  2946. };
  2947. // private function getLastNonNullVector(index)
  2948. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2949. Path3D.prototype._getLastNonNullVector = function (index) {
  2950. var i = 1;
  2951. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2952. while (nLVector.length() === 0 && index > i + 1) {
  2953. i++;
  2954. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2955. }
  2956. return nLVector;
  2957. };
  2958. // private function normalVector(v0, vt, va) :
  2959. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2960. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2961. Path3D.prototype._normalVector = function (v0, vt, va) {
  2962. var normal0;
  2963. if (va === undefined || va === null) {
  2964. var point;
  2965. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2966. point = new Vector3(0, -1, 0);
  2967. }
  2968. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2969. point = new Vector3(1, 0, 0);
  2970. }
  2971. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2972. point = new Vector3(0, 0, 1);
  2973. }
  2974. normal0 = Vector3.Cross(vt, point);
  2975. }
  2976. else {
  2977. normal0 = Vector3.Cross(vt, va);
  2978. Vector3.CrossToRef(normal0, vt, normal0);
  2979. }
  2980. normal0.normalize();
  2981. return normal0;
  2982. };
  2983. return Path3D;
  2984. })();
  2985. BABYLON.Path3D = Path3D;
  2986. var Curve3 = (function () {
  2987. function Curve3(points) {
  2988. this._length = 0;
  2989. this._points = points;
  2990. this._length = this._computeLength(points);
  2991. }
  2992. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2993. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2994. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2995. var bez = new Array();
  2996. var equation = function (t, val0, val1, val2) {
  2997. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2998. return res;
  2999. };
  3000. for (var i = 0; i <= nbPoints; i++) {
  3001. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3002. }
  3003. return new Curve3(bez);
  3004. };
  3005. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  3006. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3007. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3008. var bez = new Array();
  3009. var equation = function (t, val0, val1, val2, val3) {
  3010. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  3011. return res;
  3012. };
  3013. for (var i = 0; i <= nbPoints; i++) {
  3014. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3015. }
  3016. return new Curve3(bez);
  3017. };
  3018. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  3019. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3020. var hermite = new Array();
  3021. var step = 1 / nbPoints;
  3022. for (var i = 0; i <= nbPoints; i++) {
  3023. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3024. }
  3025. return new Curve3(hermite);
  3026. };
  3027. Curve3.prototype.getPoints = function () {
  3028. return this._points;
  3029. };
  3030. Curve3.prototype.length = function () {
  3031. return this._length;
  3032. };
  3033. Curve3.prototype.continue = function (curve) {
  3034. var lastPoint = this._points[this._points.length - 1];
  3035. var continuedPoints = this._points.slice();
  3036. var curvePoints = curve.getPoints();
  3037. for (var i = 1; i < curvePoints.length; i++) {
  3038. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3039. }
  3040. var continuedCurve = new Curve3(continuedPoints);
  3041. return continuedCurve;
  3042. };
  3043. Curve3.prototype._computeLength = function (path) {
  3044. var l = 0;
  3045. for (var i = 1; i < path.length; i++) {
  3046. l += (path[i].subtract(path[i - 1])).length();
  3047. }
  3048. return l;
  3049. };
  3050. return Curve3;
  3051. })();
  3052. BABYLON.Curve3 = Curve3;
  3053. // Vertex formats
  3054. var PositionNormalVertex = (function () {
  3055. function PositionNormalVertex(position, normal) {
  3056. if (position === void 0) { position = Vector3.Zero(); }
  3057. if (normal === void 0) { normal = Vector3.Up(); }
  3058. this.position = position;
  3059. this.normal = normal;
  3060. }
  3061. PositionNormalVertex.prototype.clone = function () {
  3062. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3063. };
  3064. return PositionNormalVertex;
  3065. })();
  3066. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3067. var PositionNormalTextureVertex = (function () {
  3068. function PositionNormalTextureVertex(position, normal, uv) {
  3069. if (position === void 0) { position = Vector3.Zero(); }
  3070. if (normal === void 0) { normal = Vector3.Up(); }
  3071. if (uv === void 0) { uv = Vector2.Zero(); }
  3072. this.position = position;
  3073. this.normal = normal;
  3074. this.uv = uv;
  3075. }
  3076. PositionNormalTextureVertex.prototype.clone = function () {
  3077. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3078. };
  3079. return PositionNormalTextureVertex;
  3080. })();
  3081. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3082. // SIMD
  3083. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3084. var previousInvertToRef = Matrix.prototype.invertToRef;
  3085. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3086. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3087. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3088. var SIMDHelper = (function () {
  3089. function SIMDHelper() {
  3090. }
  3091. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3092. get: function () {
  3093. return SIMDHelper._isEnabled;
  3094. },
  3095. enumerable: true,
  3096. configurable: true
  3097. });
  3098. SIMDHelper.DisableSIMD = function () {
  3099. // Replace functions
  3100. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3101. Matrix.prototype.invertToRef = previousInvertToRef;
  3102. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3103. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3104. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3105. SIMDHelper._isEnabled = false;
  3106. };
  3107. SIMDHelper.EnableSIMD = function () {
  3108. if (window.SIMD === undefined) {
  3109. return;
  3110. }
  3111. // Replace functions
  3112. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3113. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3114. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3115. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3116. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3117. Object.defineProperty(Vector3.prototype, "x", {
  3118. get: function () { return this._data[0]; },
  3119. set: function (value) {
  3120. if (!this._data) {
  3121. this._data = new Float32Array(3);
  3122. }
  3123. this._data[0] = value;
  3124. }
  3125. });
  3126. Object.defineProperty(Vector3.prototype, "y", {
  3127. get: function () { return this._data[1]; },
  3128. set: function (value) {
  3129. this._data[1] = value;
  3130. }
  3131. });
  3132. Object.defineProperty(Vector3.prototype, "z", {
  3133. get: function () { return this._data[2]; },
  3134. set: function (value) {
  3135. this._data[2] = value;
  3136. }
  3137. });
  3138. SIMDHelper._isEnabled = true;
  3139. };
  3140. SIMDHelper._isEnabled = false;
  3141. return SIMDHelper;
  3142. })();
  3143. BABYLON.SIMDHelper = SIMDHelper;
  3144. })(BABYLON || (BABYLON = {}));
  3145. var BABYLON;
  3146. (function (BABYLON) {
  3147. var Database = (function () {
  3148. function Database(urlToScene, callbackManifestChecked) {
  3149. // Handling various flavors of prefixed version of IndexedDB
  3150. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3151. this.callbackManifestChecked = callbackManifestChecked;
  3152. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3153. this.db = null;
  3154. this.enableSceneOffline = false;
  3155. this.enableTexturesOffline = false;
  3156. this.manifestVersionFound = 0;
  3157. this.mustUpdateRessources = false;
  3158. this.hasReachedQuota = false;
  3159. if (!Database.IDBStorageEnabled) {
  3160. this.callbackManifestChecked(true);
  3161. }
  3162. else {
  3163. this.checkManifestFile();
  3164. }
  3165. }
  3166. Database.prototype.checkManifestFile = function () {
  3167. var _this = this;
  3168. function noManifestFile() {
  3169. that.enableSceneOffline = false;
  3170. that.enableTexturesOffline = false;
  3171. that.callbackManifestChecked(false);
  3172. }
  3173. var that = this;
  3174. var manifestURL = this.currentSceneUrl + ".manifest";
  3175. var xhr = new XMLHttpRequest();
  3176. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3177. xhr.open("GET", manifestURLTimeStamped, true);
  3178. xhr.addEventListener("load", function () {
  3179. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3180. try {
  3181. var manifestFile = JSON.parse(xhr.response);
  3182. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3183. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3184. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3185. _this.manifestVersionFound = manifestFile.version;
  3186. }
  3187. if (_this.callbackManifestChecked) {
  3188. _this.callbackManifestChecked(true);
  3189. }
  3190. }
  3191. catch (ex) {
  3192. noManifestFile();
  3193. }
  3194. }
  3195. else {
  3196. noManifestFile();
  3197. }
  3198. }, false);
  3199. xhr.addEventListener("error", function (event) {
  3200. noManifestFile();
  3201. }, false);
  3202. try {
  3203. xhr.send();
  3204. }
  3205. catch (ex) {
  3206. BABYLON.Tools.Error("Error on XHR send request.");
  3207. that.callbackManifestChecked(false);
  3208. }
  3209. };
  3210. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3211. var _this = this;
  3212. function handleError() {
  3213. that.isSupported = false;
  3214. if (errorCallback)
  3215. errorCallback();
  3216. }
  3217. var that = this;
  3218. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3219. // Your browser doesn't support IndexedDB
  3220. this.isSupported = false;
  3221. if (errorCallback)
  3222. errorCallback();
  3223. }
  3224. else {
  3225. // If the DB hasn't been opened or created yet
  3226. if (!this.db) {
  3227. this.hasReachedQuota = false;
  3228. this.isSupported = true;
  3229. var request = this.idbFactory.open("babylonjs", 1);
  3230. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3231. request.onerror = function (event) {
  3232. handleError();
  3233. };
  3234. // executes when a version change transaction cannot complete due to other active transactions
  3235. request.onblocked = function (event) {
  3236. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3237. handleError();
  3238. };
  3239. // DB has been opened successfully
  3240. request.onsuccess = function (event) {
  3241. _this.db = request.result;
  3242. successCallback();
  3243. };
  3244. // Initialization of the DB. Creating Scenes & Textures stores
  3245. request.onupgradeneeded = function (event) {
  3246. _this.db = (event.target).result;
  3247. try {
  3248. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3249. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3250. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3251. }
  3252. catch (ex) {
  3253. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3254. handleError();
  3255. }
  3256. };
  3257. }
  3258. else {
  3259. if (successCallback)
  3260. successCallback();
  3261. }
  3262. }
  3263. };
  3264. Database.prototype.loadImageFromDB = function (url, image) {
  3265. var _this = this;
  3266. var completeURL = Database.ReturnFullUrlLocation(url);
  3267. var saveAndLoadImage = function () {
  3268. if (!_this.hasReachedQuota && _this.db !== null) {
  3269. // the texture is not yet in the DB, let's try to save it
  3270. _this._saveImageIntoDBAsync(completeURL, image);
  3271. }
  3272. else {
  3273. image.src = url;
  3274. }
  3275. };
  3276. if (!this.mustUpdateRessources) {
  3277. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3278. }
  3279. else {
  3280. saveAndLoadImage();
  3281. }
  3282. };
  3283. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3284. if (this.isSupported && this.db !== null) {
  3285. var texture;
  3286. var transaction = this.db.transaction(["textures"]);
  3287. transaction.onabort = function (event) {
  3288. image.src = url;
  3289. };
  3290. transaction.oncomplete = function (event) {
  3291. var blobTextureURL;
  3292. if (texture) {
  3293. var URL = window.URL || window.webkitURL;
  3294. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3295. image.onerror = function () {
  3296. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3297. image.src = url;
  3298. };
  3299. image.src = blobTextureURL;
  3300. }
  3301. else {
  3302. notInDBCallback();
  3303. }
  3304. };
  3305. var getRequest = transaction.objectStore("textures").get(url);
  3306. getRequest.onsuccess = function (event) {
  3307. texture = (event.target).result;
  3308. };
  3309. getRequest.onerror = function (event) {
  3310. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3311. image.src = url;
  3312. };
  3313. }
  3314. else {
  3315. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3316. image.src = url;
  3317. }
  3318. };
  3319. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3320. var _this = this;
  3321. if (this.isSupported) {
  3322. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3323. var generateBlobUrl = function () {
  3324. var blobTextureURL;
  3325. if (blob) {
  3326. var URL = window.URL || window.webkitURL;
  3327. try {
  3328. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3329. }
  3330. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3331. catch (ex) {
  3332. blobTextureURL = URL.createObjectURL(blob);
  3333. }
  3334. }
  3335. image.src = blobTextureURL;
  3336. };
  3337. if (Database.IsUASupportingBlobStorage) {
  3338. var xhr = new XMLHttpRequest(), blob;
  3339. xhr.open("GET", url, true);
  3340. xhr.responseType = "blob";
  3341. xhr.addEventListener("load", function () {
  3342. if (xhr.status === 200) {
  3343. // Blob as response (XHR2)
  3344. blob = xhr.response;
  3345. var transaction = _this.db.transaction(["textures"], "readwrite");
  3346. // the transaction could abort because of a QuotaExceededError error
  3347. transaction.onabort = function (event) {
  3348. try {
  3349. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3350. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3351. this.hasReachedQuota = true;
  3352. }
  3353. }
  3354. catch (ex) { }
  3355. generateBlobUrl();
  3356. };
  3357. transaction.oncomplete = function (event) {
  3358. generateBlobUrl();
  3359. };
  3360. var newTexture = { textureUrl: url, data: blob };
  3361. try {
  3362. // Put the blob into the dabase
  3363. var addRequest = transaction.objectStore("textures").put(newTexture);
  3364. addRequest.onsuccess = function (event) {
  3365. };
  3366. addRequest.onerror = function (event) {
  3367. generateBlobUrl();
  3368. };
  3369. }
  3370. catch (ex) {
  3371. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3372. if (ex.code === 25) {
  3373. Database.IsUASupportingBlobStorage = false;
  3374. }
  3375. image.src = url;
  3376. }
  3377. }
  3378. else {
  3379. image.src = url;
  3380. }
  3381. }, false);
  3382. xhr.addEventListener("error", function (event) {
  3383. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3384. image.src = url;
  3385. }, false);
  3386. xhr.send();
  3387. }
  3388. else {
  3389. image.src = url;
  3390. }
  3391. }
  3392. else {
  3393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3394. image.src = url;
  3395. }
  3396. };
  3397. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3398. var _this = this;
  3399. var updateVersion = function (event) {
  3400. // the version is not yet in the DB or we need to update it
  3401. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3402. };
  3403. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3404. };
  3405. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3406. var _this = this;
  3407. if (this.isSupported) {
  3408. var version;
  3409. try {
  3410. var transaction = this.db.transaction(["versions"]);
  3411. transaction.oncomplete = function (event) {
  3412. if (version) {
  3413. // If the version in the JSON file is > than the version in DB
  3414. if (_this.manifestVersionFound > version.data) {
  3415. _this.mustUpdateRessources = true;
  3416. updateInDBCallback();
  3417. }
  3418. else {
  3419. callback(version.data);
  3420. }
  3421. }
  3422. else {
  3423. _this.mustUpdateRessources = true;
  3424. updateInDBCallback();
  3425. }
  3426. };
  3427. transaction.onabort = function (event) {
  3428. callback(-1);
  3429. };
  3430. var getRequest = transaction.objectStore("versions").get(url);
  3431. getRequest.onsuccess = function (event) {
  3432. version = (event.target).result;
  3433. };
  3434. getRequest.onerror = function (event) {
  3435. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3436. callback(-1);
  3437. };
  3438. }
  3439. catch (ex) {
  3440. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3441. callback(-1);
  3442. }
  3443. }
  3444. else {
  3445. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3446. callback(-1);
  3447. }
  3448. };
  3449. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3450. var _this = this;
  3451. if (this.isSupported && !this.hasReachedQuota) {
  3452. try {
  3453. // Open a transaction to the database
  3454. var transaction = this.db.transaction(["versions"], "readwrite");
  3455. // the transaction could abort because of a QuotaExceededError error
  3456. transaction.onabort = function (event) {
  3457. try {
  3458. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3459. _this.hasReachedQuota = true;
  3460. }
  3461. }
  3462. catch (ex) { }
  3463. callback(-1);
  3464. };
  3465. transaction.oncomplete = function (event) {
  3466. callback(_this.manifestVersionFound);
  3467. };
  3468. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3469. // Put the scene into the database
  3470. var addRequest = transaction.objectStore("versions").put(newVersion);
  3471. addRequest.onsuccess = function (event) {
  3472. };
  3473. addRequest.onerror = function (event) {
  3474. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3475. };
  3476. }
  3477. catch (ex) {
  3478. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3479. callback(-1);
  3480. }
  3481. }
  3482. else {
  3483. callback(-1);
  3484. }
  3485. };
  3486. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3487. var _this = this;
  3488. var completeUrl = Database.ReturnFullUrlLocation(url);
  3489. var saveAndLoadFile = function (event) {
  3490. // the scene is not yet in the DB, let's try to save it
  3491. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3492. };
  3493. this._checkVersionFromDB(completeUrl, function (version) {
  3494. if (version !== -1) {
  3495. if (!_this.mustUpdateRessources) {
  3496. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3497. }
  3498. else {
  3499. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3500. }
  3501. }
  3502. else {
  3503. errorCallback();
  3504. }
  3505. });
  3506. };
  3507. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3508. if (this.isSupported) {
  3509. var targetStore;
  3510. if (url.indexOf(".babylon") !== -1) {
  3511. targetStore = "scenes";
  3512. }
  3513. else {
  3514. targetStore = "textures";
  3515. }
  3516. var file;
  3517. var transaction = this.db.transaction([targetStore]);
  3518. transaction.oncomplete = function (event) {
  3519. if (file) {
  3520. callback(file.data);
  3521. }
  3522. else {
  3523. notInDBCallback();
  3524. }
  3525. };
  3526. transaction.onabort = function (event) {
  3527. notInDBCallback();
  3528. };
  3529. var getRequest = transaction.objectStore(targetStore).get(url);
  3530. getRequest.onsuccess = function (event) {
  3531. file = (event.target).result;
  3532. };
  3533. getRequest.onerror = function (event) {
  3534. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3535. notInDBCallback();
  3536. };
  3537. }
  3538. else {
  3539. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3540. callback();
  3541. }
  3542. };
  3543. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3544. var _this = this;
  3545. if (this.isSupported) {
  3546. var targetStore;
  3547. if (url.indexOf(".babylon") !== -1) {
  3548. targetStore = "scenes";
  3549. }
  3550. else {
  3551. targetStore = "textures";
  3552. }
  3553. // Create XHR
  3554. var xhr = new XMLHttpRequest(), fileData;
  3555. xhr.open("GET", url, true);
  3556. if (useArrayBuffer) {
  3557. xhr.responseType = "arraybuffer";
  3558. }
  3559. xhr.onprogress = progressCallback;
  3560. xhr.addEventListener("load", function () {
  3561. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3562. // Blob as response (XHR2)
  3563. //fileData = xhr.responseText;
  3564. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3565. if (!_this.hasReachedQuota) {
  3566. // Open a transaction to the database
  3567. var transaction = _this.db.transaction([targetStore], "readwrite");
  3568. // the transaction could abort because of a QuotaExceededError error
  3569. transaction.onabort = function (event) {
  3570. try {
  3571. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3572. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3573. this.hasReachedQuota = true;
  3574. }
  3575. }
  3576. catch (ex) { }
  3577. callback(fileData);
  3578. };
  3579. transaction.oncomplete = function (event) {
  3580. callback(fileData);
  3581. };
  3582. var newFile;
  3583. if (targetStore === "scenes") {
  3584. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3585. }
  3586. else {
  3587. newFile = { textureUrl: url, data: fileData };
  3588. }
  3589. try {
  3590. // Put the scene into the database
  3591. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3592. addRequest.onsuccess = function (event) {
  3593. };
  3594. addRequest.onerror = function (event) {
  3595. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3596. };
  3597. }
  3598. catch (ex) {
  3599. callback(fileData);
  3600. }
  3601. }
  3602. else {
  3603. callback(fileData);
  3604. }
  3605. }
  3606. else {
  3607. callback();
  3608. }
  3609. }, false);
  3610. xhr.addEventListener("error", function (event) {
  3611. BABYLON.Tools.Error("error on XHR request.");
  3612. callback();
  3613. }, false);
  3614. xhr.send();
  3615. }
  3616. else {
  3617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3618. callback();
  3619. }
  3620. };
  3621. Database.IsUASupportingBlobStorage = true;
  3622. Database.IDBStorageEnabled = true;
  3623. Database.parseURL = function (url) {
  3624. var a = document.createElement('a');
  3625. a.href = url;
  3626. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3627. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3628. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3629. return absLocation;
  3630. };
  3631. Database.ReturnFullUrlLocation = function (url) {
  3632. if (url.indexOf("http:/") === -1) {
  3633. return (Database.parseURL(window.location.href) + url);
  3634. }
  3635. else {
  3636. return url;
  3637. }
  3638. };
  3639. return Database;
  3640. })();
  3641. BABYLON.Database = Database;
  3642. })(BABYLON || (BABYLON = {}));
  3643. var BABYLON;
  3644. (function (BABYLON) {
  3645. var Internals;
  3646. (function (Internals) {
  3647. /*
  3648. * Based on jsTGALoader - Javascript loader for TGA file
  3649. * By Vincent Thibault
  3650. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3651. */
  3652. var TGATools = (function () {
  3653. function TGATools() {
  3654. }
  3655. TGATools.GetTGAHeader = function (data) {
  3656. var offset = 0;
  3657. var header = {
  3658. id_length: data[offset++],
  3659. colormap_type: data[offset++],
  3660. image_type: data[offset++],
  3661. colormap_index: data[offset++] | data[offset++] << 8,
  3662. colormap_length: data[offset++] | data[offset++] << 8,
  3663. colormap_size: data[offset++],
  3664. origin: [
  3665. data[offset++] | data[offset++] << 8,
  3666. data[offset++] | data[offset++] << 8
  3667. ],
  3668. width: data[offset++] | data[offset++] << 8,
  3669. height: data[offset++] | data[offset++] << 8,
  3670. pixel_size: data[offset++],
  3671. flags: data[offset++]
  3672. };
  3673. return header;
  3674. };
  3675. TGATools.UploadContent = function (gl, data) {
  3676. // Not enough data to contain header ?
  3677. if (data.length < 19) {
  3678. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3679. return;
  3680. }
  3681. // Read Header
  3682. var offset = 18;
  3683. var header = TGATools.GetTGAHeader(data);
  3684. // Assume it's a valid Targa file.
  3685. if (header.id_length + offset > data.length) {
  3686. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3687. return;
  3688. }
  3689. // Skip not needed data
  3690. offset += header.id_length;
  3691. var use_rle = false;
  3692. var use_pal = false;
  3693. var use_rgb = false;
  3694. var use_grey = false;
  3695. // Get some informations.
  3696. switch (header.image_type) {
  3697. case TGATools._TYPE_RLE_INDEXED:
  3698. use_rle = true;
  3699. case TGATools._TYPE_INDEXED:
  3700. use_pal = true;
  3701. break;
  3702. case TGATools._TYPE_RLE_RGB:
  3703. use_rle = true;
  3704. case TGATools._TYPE_RGB:
  3705. use_rgb = true;
  3706. break;
  3707. case TGATools._TYPE_RLE_GREY:
  3708. use_rle = true;
  3709. case TGATools._TYPE_GREY:
  3710. use_grey = true;
  3711. break;
  3712. }
  3713. var pixel_data;
  3714. var numAlphaBits = header.flags & 0xf;
  3715. var pixel_size = header.pixel_size >> 3;
  3716. var pixel_total = header.width * header.height * pixel_size;
  3717. // Read palettes
  3718. var palettes;
  3719. if (use_pal) {
  3720. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3721. }
  3722. // Read LRE
  3723. if (use_rle) {
  3724. pixel_data = new Uint8Array(pixel_total);
  3725. var c, count, i;
  3726. var localOffset = 0;
  3727. var pixels = new Uint8Array(pixel_size);
  3728. while (offset < pixel_total && localOffset < pixel_total) {
  3729. c = data[offset++];
  3730. count = (c & 0x7f) + 1;
  3731. // RLE pixels
  3732. if (c & 0x80) {
  3733. // Bind pixel tmp array
  3734. for (i = 0; i < pixel_size; ++i) {
  3735. pixels[i] = data[offset++];
  3736. }
  3737. // Copy pixel array
  3738. for (i = 0; i < count; ++i) {
  3739. pixel_data.set(pixels, localOffset + i * pixel_size);
  3740. }
  3741. localOffset += pixel_size * count;
  3742. }
  3743. else {
  3744. count *= pixel_size;
  3745. for (i = 0; i < count; ++i) {
  3746. pixel_data[localOffset + i] = data[offset++];
  3747. }
  3748. localOffset += count;
  3749. }
  3750. }
  3751. }
  3752. else {
  3753. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3754. }
  3755. // Load to texture
  3756. var x_start, y_start, x_step, y_step, y_end, x_end;
  3757. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3758. default:
  3759. case TGATools._ORIGIN_UL:
  3760. x_start = 0;
  3761. x_step = 1;
  3762. x_end = header.width;
  3763. y_start = 0;
  3764. y_step = 1;
  3765. y_end = header.height;
  3766. break;
  3767. case TGATools._ORIGIN_BL:
  3768. x_start = 0;
  3769. x_step = 1;
  3770. x_end = header.width;
  3771. y_start = header.height - 1;
  3772. y_step = -1;
  3773. y_end = -1;
  3774. break;
  3775. case TGATools._ORIGIN_UR:
  3776. x_start = header.width - 1;
  3777. x_step = -1;
  3778. x_end = -1;
  3779. y_start = 0;
  3780. y_step = 1;
  3781. y_end = header.height;
  3782. break;
  3783. case TGATools._ORIGIN_BR:
  3784. x_start = header.width - 1;
  3785. x_step = -1;
  3786. x_end = -1;
  3787. y_start = header.height - 1;
  3788. y_step = -1;
  3789. y_end = -1;
  3790. break;
  3791. }
  3792. // Load the specify method
  3793. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3794. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3795. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3796. };
  3797. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3798. var image = pixel_data, colormap = palettes;
  3799. var width = header.width, height = header.height;
  3800. var color, i = 0, x, y;
  3801. var imageData = new Uint8Array(width * height * 4);
  3802. for (y = y_start; y !== y_end; y += y_step) {
  3803. for (x = x_start; x !== x_end; x += x_step, i++) {
  3804. color = image[i];
  3805. imageData[(x + width * y) * 4 + 3] = 255;
  3806. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3807. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3808. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3809. }
  3810. }
  3811. return imageData;
  3812. };
  3813. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3814. var image = pixel_data;
  3815. var width = header.width, height = header.height;
  3816. var color, i = 0, x, y;
  3817. var imageData = new Uint8Array(width * height * 4);
  3818. for (y = y_start; y !== y_end; y += y_step) {
  3819. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3820. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3821. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3822. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3823. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3824. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3825. }
  3826. }
  3827. return imageData;
  3828. };
  3829. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3830. var image = pixel_data;
  3831. var width = header.width, height = header.height;
  3832. var i = 0, x, y;
  3833. var imageData = new Uint8Array(width * height * 4);
  3834. for (y = y_start; y !== y_end; y += y_step) {
  3835. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3836. imageData[(x + width * y) * 4 + 3] = 255;
  3837. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3838. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3839. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3840. }
  3841. }
  3842. return imageData;
  3843. };
  3844. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3845. var image = pixel_data;
  3846. var width = header.width, height = header.height;
  3847. var i = 0, x, y;
  3848. var imageData = new Uint8Array(width * height * 4);
  3849. for (y = y_start; y !== y_end; y += y_step) {
  3850. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3851. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3852. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3853. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3854. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3855. }
  3856. }
  3857. return imageData;
  3858. };
  3859. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3860. var image = pixel_data;
  3861. var width = header.width, height = header.height;
  3862. var color, i = 0, x, y;
  3863. var imageData = new Uint8Array(width * height * 4);
  3864. for (y = y_start; y !== y_end; y += y_step) {
  3865. for (x = x_start; x !== x_end; x += x_step, i++) {
  3866. color = image[i];
  3867. imageData[(x + width * y) * 4 + 0] = color;
  3868. imageData[(x + width * y) * 4 + 1] = color;
  3869. imageData[(x + width * y) * 4 + 2] = color;
  3870. imageData[(x + width * y) * 4 + 3] = 255;
  3871. }
  3872. }
  3873. return imageData;
  3874. };
  3875. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3876. var image = pixel_data;
  3877. var width = header.width, height = header.height;
  3878. var i = 0, x, y;
  3879. var imageData = new Uint8Array(width * height * 4);
  3880. for (y = y_start; y !== y_end; y += y_step) {
  3881. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3882. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3883. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3884. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3885. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3886. }
  3887. }
  3888. return imageData;
  3889. };
  3890. TGATools._TYPE_NO_DATA = 0;
  3891. TGATools._TYPE_INDEXED = 1;
  3892. TGATools._TYPE_RGB = 2;
  3893. TGATools._TYPE_GREY = 3;
  3894. TGATools._TYPE_RLE_INDEXED = 9;
  3895. TGATools._TYPE_RLE_RGB = 10;
  3896. TGATools._TYPE_RLE_GREY = 11;
  3897. TGATools._ORIGIN_MASK = 0x30;
  3898. TGATools._ORIGIN_SHIFT = 0x04;
  3899. TGATools._ORIGIN_BL = 0x00;
  3900. TGATools._ORIGIN_BR = 0x01;
  3901. TGATools._ORIGIN_UL = 0x02;
  3902. TGATools._ORIGIN_UR = 0x03;
  3903. return TGATools;
  3904. })();
  3905. Internals.TGATools = TGATools;
  3906. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3907. })(BABYLON || (BABYLON = {}));
  3908. var BABYLON;
  3909. (function (BABYLON) {
  3910. var Internals;
  3911. (function (Internals) {
  3912. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3913. // All values and structures referenced from:
  3914. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3915. var DDS_MAGIC = 0x20534444;
  3916. 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;
  3917. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3918. 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;
  3919. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3920. function FourCCToInt32(value) {
  3921. return value.charCodeAt(0) +
  3922. (value.charCodeAt(1) << 8) +
  3923. (value.charCodeAt(2) << 16) +
  3924. (value.charCodeAt(3) << 24);
  3925. }
  3926. function Int32ToFourCC(value) {
  3927. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3928. }
  3929. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3930. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3931. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3932. var headerLengthInt = 31; // The header length in 32 bit ints
  3933. // Offsets into the header array
  3934. var off_magic = 0;
  3935. var off_size = 1;
  3936. var off_flags = 2;
  3937. var off_height = 3;
  3938. var off_width = 4;
  3939. var off_mipmapCount = 7;
  3940. var off_pfFlags = 20;
  3941. var off_pfFourCC = 21;
  3942. var off_RGBbpp = 22;
  3943. var off_RMask = 23;
  3944. var off_GMask = 24;
  3945. var off_BMask = 25;
  3946. var off_AMask = 26;
  3947. var off_caps1 = 27;
  3948. var off_caps2 = 28;
  3949. ;
  3950. var DDSTools = (function () {
  3951. function DDSTools() {
  3952. }
  3953. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3954. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3955. var mipmapCount = 1;
  3956. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3957. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3958. }
  3959. return {
  3960. width: header[off_width],
  3961. height: header[off_height],
  3962. mipmapCount: mipmapCount,
  3963. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3964. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3965. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3966. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3967. };
  3968. };
  3969. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3970. var byteArray = new Uint8Array(dataLength);
  3971. var srcData = new Uint8Array(arrayBuffer);
  3972. var index = 0;
  3973. for (var y = height - 1; y >= 0; y--) {
  3974. for (var x = 0; x < width; x++) {
  3975. var srcPos = dataOffset + (x + y * width) * 4;
  3976. byteArray[index + 2] = srcData[srcPos];
  3977. byteArray[index + 1] = srcData[srcPos + 1];
  3978. byteArray[index] = srcData[srcPos + 2];
  3979. byteArray[index + 3] = srcData[srcPos + 3];
  3980. index += 4;
  3981. }
  3982. }
  3983. return byteArray;
  3984. };
  3985. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3986. var byteArray = new Uint8Array(dataLength);
  3987. var srcData = new Uint8Array(arrayBuffer);
  3988. var index = 0;
  3989. for (var y = height - 1; y >= 0; y--) {
  3990. for (var x = 0; x < width; x++) {
  3991. var srcPos = dataOffset + (x + y * width) * 3;
  3992. byteArray[index + 2] = srcData[srcPos];
  3993. byteArray[index + 1] = srcData[srcPos + 1];
  3994. byteArray[index] = srcData[srcPos + 2];
  3995. index += 3;
  3996. }
  3997. }
  3998. return byteArray;
  3999. };
  4000. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  4001. var byteArray = new Uint8Array(dataLength);
  4002. var srcData = new Uint8Array(arrayBuffer);
  4003. var index = 0;
  4004. for (var y = height - 1; y >= 0; y--) {
  4005. for (var x = 0; x < width; x++) {
  4006. var srcPos = dataOffset + (x + y * width);
  4007. byteArray[index] = srcData[srcPos];
  4008. index++;
  4009. }
  4010. }
  4011. return byteArray;
  4012. };
  4013. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  4014. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  4015. if (header[off_magic] != DDS_MAGIC) {
  4016. BABYLON.Tools.Error("Invalid magic number in DDS header");
  4017. return;
  4018. }
  4019. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  4020. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  4021. return;
  4022. }
  4023. if (info.isFourCC) {
  4024. fourCC = header[off_pfFourCC];
  4025. switch (fourCC) {
  4026. case FOURCC_DXT1:
  4027. blockBytes = 8;
  4028. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  4029. break;
  4030. case FOURCC_DXT3:
  4031. blockBytes = 16;
  4032. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  4033. break;
  4034. case FOURCC_DXT5:
  4035. blockBytes = 16;
  4036. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4037. break;
  4038. default:
  4039. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4040. return;
  4041. }
  4042. }
  4043. mipmapCount = 1;
  4044. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4045. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4046. }
  4047. var bpp = header[off_RGBbpp];
  4048. for (var face = 0; face < faces; face++) {
  4049. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4050. width = header[off_width];
  4051. height = header[off_height];
  4052. dataOffset = header[off_size] + 4;
  4053. for (i = 0; i < mipmapCount; ++i) {
  4054. if (info.isRGB) {
  4055. if (bpp == 24) {
  4056. dataLength = width * height * 3;
  4057. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4058. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4059. }
  4060. else {
  4061. dataLength = width * height * 4;
  4062. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4063. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4064. }
  4065. }
  4066. else if (info.isLuminance) {
  4067. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4068. var unpaddedRowSize = width;
  4069. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4070. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4071. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4072. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4073. }
  4074. else {
  4075. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4076. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4077. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4078. }
  4079. dataOffset += dataLength;
  4080. width *= 0.5;
  4081. height *= 0.5;
  4082. width = Math.max(1.0, width);
  4083. height = Math.max(1.0, height);
  4084. }
  4085. }
  4086. };
  4087. return DDSTools;
  4088. })();
  4089. Internals.DDSTools = DDSTools;
  4090. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4091. })(BABYLON || (BABYLON = {}));
  4092. var BABYLON;
  4093. (function (BABYLON) {
  4094. var SmartArray = (function () {
  4095. function SmartArray(capacity) {
  4096. this.length = 0;
  4097. this._duplicateId = 0;
  4098. this.data = new Array(capacity);
  4099. this._id = SmartArray._GlobalId++;
  4100. }
  4101. SmartArray.prototype.push = function (value) {
  4102. this.data[this.length++] = value;
  4103. if (this.length > this.data.length) {
  4104. this.data.length *= 2;
  4105. }
  4106. if (!value.__smartArrayFlags) {
  4107. value.__smartArrayFlags = {};
  4108. }
  4109. value.__smartArrayFlags[this._id] = this._duplicateId;
  4110. };
  4111. SmartArray.prototype.pushNoDuplicate = function (value) {
  4112. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4113. return;
  4114. }
  4115. this.push(value);
  4116. };
  4117. SmartArray.prototype.sort = function (compareFn) {
  4118. this.data.sort(compareFn);
  4119. };
  4120. SmartArray.prototype.reset = function () {
  4121. this.length = 0;
  4122. this._duplicateId++;
  4123. };
  4124. SmartArray.prototype.concat = function (array) {
  4125. if (array.length === 0) {
  4126. return;
  4127. }
  4128. if (this.length + array.length > this.data.length) {
  4129. this.data.length = (this.length + array.length) * 2;
  4130. }
  4131. for (var index = 0; index < array.length; index++) {
  4132. this.data[this.length++] = (array.data || array)[index];
  4133. }
  4134. };
  4135. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4136. if (array.length === 0) {
  4137. return;
  4138. }
  4139. if (this.length + array.length > this.data.length) {
  4140. this.data.length = (this.length + array.length) * 2;
  4141. }
  4142. for (var index = 0; index < array.length; index++) {
  4143. var item = (array.data || array)[index];
  4144. this.pushNoDuplicate(item);
  4145. }
  4146. };
  4147. SmartArray.prototype.indexOf = function (value) {
  4148. var position = this.data.indexOf(value);
  4149. if (position >= this.length) {
  4150. return -1;
  4151. }
  4152. return position;
  4153. };
  4154. // Statics
  4155. SmartArray._GlobalId = 0;
  4156. return SmartArray;
  4157. })();
  4158. BABYLON.SmartArray = SmartArray;
  4159. })(BABYLON || (BABYLON = {}));
  4160. var BABYLON;
  4161. (function (BABYLON) {
  4162. var SmartCollection = (function () {
  4163. function SmartCollection(capacity) {
  4164. if (capacity === void 0) { capacity = 10; }
  4165. this.count = 0;
  4166. this._initialCapacity = capacity;
  4167. this.items = {};
  4168. this._keys = new Array(this._initialCapacity);
  4169. }
  4170. SmartCollection.prototype.add = function (key, item) {
  4171. if (this.items[key] != undefined) {
  4172. return -1;
  4173. }
  4174. this.items[key] = item;
  4175. //literal keys are always strings, but we keep source type of key in _keys array
  4176. this._keys[this.count++] = key;
  4177. if (this.count > this._keys.length) {
  4178. this._keys.length *= 2;
  4179. }
  4180. return this.count;
  4181. };
  4182. SmartCollection.prototype.remove = function (key) {
  4183. if (this.items[key] == undefined) {
  4184. return -1;
  4185. }
  4186. return this.removeItemOfIndex(this.indexOf(key));
  4187. };
  4188. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4189. if (index < this.count && index > -1) {
  4190. delete this.items[this._keys[index]];
  4191. //here, shifting by hand is better optimised than .splice
  4192. while (index < this.count) {
  4193. this._keys[index] = this._keys[index + 1];
  4194. index++;
  4195. }
  4196. }
  4197. else {
  4198. return -1;
  4199. }
  4200. return --this.count;
  4201. };
  4202. SmartCollection.prototype.indexOf = function (key) {
  4203. for (var i = 0; i !== this.count; i++) {
  4204. if (this._keys[i] === key) {
  4205. return i;
  4206. }
  4207. }
  4208. return -1;
  4209. };
  4210. SmartCollection.prototype.item = function (key) {
  4211. return this.items[key];
  4212. };
  4213. SmartCollection.prototype.getAllKeys = function () {
  4214. if (this.count > 0) {
  4215. var keys = new Array(this.count);
  4216. for (var i = 0; i < this.count; i++) {
  4217. keys[i] = this._keys[i];
  4218. }
  4219. return keys;
  4220. }
  4221. else {
  4222. return undefined;
  4223. }
  4224. };
  4225. SmartCollection.prototype.getKeyByIndex = function (index) {
  4226. if (index < this.count && index > -1) {
  4227. return this._keys[index];
  4228. }
  4229. else {
  4230. return undefined;
  4231. }
  4232. };
  4233. SmartCollection.prototype.getItemByIndex = function (index) {
  4234. if (index < this.count && index > -1) {
  4235. return this.items[this._keys[index]];
  4236. }
  4237. else {
  4238. return undefined;
  4239. }
  4240. };
  4241. SmartCollection.prototype.empty = function () {
  4242. if (this.count > 0) {
  4243. this.count = 0;
  4244. this.items = {};
  4245. this._keys = new Array(this._initialCapacity);
  4246. }
  4247. };
  4248. SmartCollection.prototype.forEach = function (block) {
  4249. var key;
  4250. for (key in this.items) {
  4251. if (this.items.hasOwnProperty(key)) {
  4252. block(this.items[key]);
  4253. }
  4254. }
  4255. };
  4256. return SmartCollection;
  4257. })();
  4258. BABYLON.SmartCollection = SmartCollection;
  4259. })(BABYLON || (BABYLON = {}));
  4260. var BABYLON;
  4261. (function (BABYLON) {
  4262. // Screenshots
  4263. var screenshotCanvas;
  4264. var cloneValue = function (source, destinationObject) {
  4265. if (!source)
  4266. return null;
  4267. if (source instanceof BABYLON.Mesh) {
  4268. return null;
  4269. }
  4270. if (source instanceof BABYLON.SubMesh) {
  4271. return source.clone(destinationObject);
  4272. }
  4273. else if (source.clone) {
  4274. return source.clone();
  4275. }
  4276. return null;
  4277. };
  4278. var Tools = (function () {
  4279. function Tools() {
  4280. }
  4281. Tools.ToHex = function (i) {
  4282. var str = i.toString(16);
  4283. if (i <= 15) {
  4284. return ("0" + str).toUpperCase();
  4285. }
  4286. return str.toUpperCase();
  4287. };
  4288. Tools.SetImmediate = function (action) {
  4289. if (window.setImmediate) {
  4290. window.setImmediate(action);
  4291. }
  4292. else {
  4293. setTimeout(action, 1);
  4294. }
  4295. };
  4296. Tools.IsExponantOfTwo = function (value) {
  4297. var count = 1;
  4298. do {
  4299. count *= 2;
  4300. } while (count < value);
  4301. return count === value;
  4302. };
  4303. Tools.GetExponantOfTwo = function (value, max) {
  4304. var count = 1;
  4305. do {
  4306. count *= 2;
  4307. } while (count < value);
  4308. if (count > max)
  4309. count = max;
  4310. return count;
  4311. };
  4312. Tools.GetFilename = function (path) {
  4313. var index = path.lastIndexOf("/");
  4314. if (index < 0)
  4315. return path;
  4316. return path.substring(index + 1);
  4317. };
  4318. Tools.GetDOMTextContent = function (element) {
  4319. var result = "";
  4320. var child = element.firstChild;
  4321. while (child) {
  4322. if (child.nodeType === 3) {
  4323. result += child.textContent;
  4324. }
  4325. child = child.nextSibling;
  4326. }
  4327. return result;
  4328. };
  4329. Tools.ToDegrees = function (angle) {
  4330. return angle * 180 / Math.PI;
  4331. };
  4332. Tools.ToRadians = function (angle) {
  4333. return angle * Math.PI / 180;
  4334. };
  4335. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4336. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4337. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4338. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4339. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4340. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4341. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4342. }
  4343. return {
  4344. minimum: minimum,
  4345. maximum: maximum
  4346. };
  4347. };
  4348. Tools.ExtractMinAndMax = function (positions, start, count) {
  4349. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4350. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4351. for (var index = start; index < start + count; index++) {
  4352. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4353. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4354. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4355. }
  4356. return {
  4357. minimum: minimum,
  4358. maximum: maximum
  4359. };
  4360. };
  4361. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4362. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4363. return undefined;
  4364. return Array.isArray(obj) ? obj : [obj];
  4365. };
  4366. // Misc.
  4367. Tools.GetPointerPrefix = function () {
  4368. var eventPrefix = "pointer";
  4369. // Check if hand.js is referenced or if the browser natively supports pointer events
  4370. if (!navigator.pointerEnabled) {
  4371. eventPrefix = "mouse";
  4372. }
  4373. return eventPrefix;
  4374. };
  4375. Tools.QueueNewFrame = function (func) {
  4376. if (window.requestAnimationFrame)
  4377. window.requestAnimationFrame(func);
  4378. else if (window.msRequestAnimationFrame)
  4379. window.msRequestAnimationFrame(func);
  4380. else if (window.webkitRequestAnimationFrame)
  4381. window.webkitRequestAnimationFrame(func);
  4382. else if (window.mozRequestAnimationFrame)
  4383. window.mozRequestAnimationFrame(func);
  4384. else if (window.oRequestAnimationFrame)
  4385. window.oRequestAnimationFrame(func);
  4386. else {
  4387. window.setTimeout(func, 16);
  4388. }
  4389. };
  4390. Tools.RequestFullscreen = function (element) {
  4391. if (element.requestFullscreen)
  4392. element.requestFullscreen();
  4393. else if (element.msRequestFullscreen)
  4394. element.msRequestFullscreen();
  4395. else if (element.webkitRequestFullscreen)
  4396. element.webkitRequestFullscreen();
  4397. else if (element.mozRequestFullScreen)
  4398. element.mozRequestFullScreen();
  4399. };
  4400. Tools.ExitFullscreen = function () {
  4401. if (document.exitFullscreen) {
  4402. document.exitFullscreen();
  4403. }
  4404. else if (document.mozCancelFullScreen) {
  4405. document.mozCancelFullScreen();
  4406. }
  4407. else if (document.webkitCancelFullScreen) {
  4408. document.webkitCancelFullScreen();
  4409. }
  4410. else if (document.msCancelFullScreen) {
  4411. document.msCancelFullScreen();
  4412. }
  4413. };
  4414. // External files
  4415. Tools.CleanUrl = function (url) {
  4416. url = url.replace(/#/mg, "%23");
  4417. return url;
  4418. };
  4419. Tools.LoadImage = function (url, onload, onerror, database) {
  4420. url = Tools.CleanUrl(url);
  4421. var img = new Image();
  4422. if (url.substr(0, 5) !== "data:")
  4423. img.crossOrigin = 'anonymous';
  4424. img.onload = function () {
  4425. onload(img);
  4426. };
  4427. img.onerror = function (err) {
  4428. Tools.Error("Error while trying to load texture: " + url);
  4429. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4430. onload(img);
  4431. };
  4432. var noIndexedDB = function () {
  4433. img.src = url;
  4434. };
  4435. var loadFromIndexedDB = function () {
  4436. database.loadImageFromDB(url, img);
  4437. };
  4438. //ANY database to do!
  4439. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4440. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4441. }
  4442. else {
  4443. if (url.indexOf("file:") === -1) {
  4444. noIndexedDB();
  4445. }
  4446. else {
  4447. try {
  4448. var textureName = url.substring(5);
  4449. var blobURL;
  4450. try {
  4451. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4452. }
  4453. catch (ex) {
  4454. // Chrome doesn't support oneTimeOnly parameter
  4455. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4456. }
  4457. img.src = blobURL;
  4458. }
  4459. catch (e) {
  4460. img.src = null;
  4461. }
  4462. }
  4463. }
  4464. return img;
  4465. };
  4466. //ANY
  4467. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4468. url = Tools.CleanUrl(url);
  4469. var noIndexedDB = function () {
  4470. var request = new XMLHttpRequest();
  4471. var loadUrl = Tools.BaseUrl + url;
  4472. request.open('GET', loadUrl, true);
  4473. if (useArrayBuffer) {
  4474. request.responseType = "arraybuffer";
  4475. }
  4476. request.onprogress = progressCallBack;
  4477. request.onreadystatechange = function () {
  4478. if (request.readyState === 4) {
  4479. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4480. callback(!useArrayBuffer ? request.responseText : request.response);
  4481. }
  4482. else {
  4483. if (onError) {
  4484. onError();
  4485. }
  4486. else {
  4487. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4488. }
  4489. }
  4490. }
  4491. };
  4492. request.send(null);
  4493. };
  4494. var loadFromIndexedDB = function () {
  4495. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4496. };
  4497. if (url.indexOf("file:") !== -1) {
  4498. var fileName = url.substring(5);
  4499. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4500. }
  4501. else {
  4502. // Caching all files
  4503. if (database && database.enableSceneOffline) {
  4504. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4505. }
  4506. else {
  4507. noIndexedDB();
  4508. }
  4509. }
  4510. };
  4511. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4512. var reader = new FileReader();
  4513. reader.onload = function (e) {
  4514. //target doesn't have result from ts 1.3
  4515. callback(e.target['result']);
  4516. };
  4517. reader.onprogress = progressCallback;
  4518. reader.readAsDataURL(fileToLoad);
  4519. };
  4520. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4521. var reader = new FileReader();
  4522. reader.onerror = function (e) {
  4523. Tools.Log("Error while reading file: " + fileToLoad.name);
  4524. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4525. };
  4526. reader.onload = function (e) {
  4527. //target doesn't have result from ts 1.3
  4528. callback(e.target['result']);
  4529. };
  4530. reader.onprogress = progressCallBack;
  4531. if (!useArrayBuffer) {
  4532. // Asynchronous read
  4533. reader.readAsText(fileToLoad);
  4534. }
  4535. else {
  4536. reader.readAsArrayBuffer(fileToLoad);
  4537. }
  4538. };
  4539. // Misc.
  4540. Tools.Clamp = function (value, min, max) {
  4541. if (min === void 0) { min = 0; }
  4542. if (max === void 0) { max = 1; }
  4543. return Math.min(max, Math.max(min, value));
  4544. };
  4545. // Returns -1 when value is a negative number and
  4546. // +1 when value is a positive number.
  4547. Tools.Sign = function (value) {
  4548. value = +value; // convert to a number
  4549. if (value === 0 || isNaN(value))
  4550. return value;
  4551. return value > 0 ? 1 : -1;
  4552. };
  4553. Tools.Format = function (value, decimals) {
  4554. if (decimals === void 0) { decimals = 2; }
  4555. return value.toFixed(decimals);
  4556. };
  4557. Tools.CheckExtends = function (v, min, max) {
  4558. if (v.x < min.x)
  4559. min.x = v.x;
  4560. if (v.y < min.y)
  4561. min.y = v.y;
  4562. if (v.z < min.z)
  4563. min.z = v.z;
  4564. if (v.x > max.x)
  4565. max.x = v.x;
  4566. if (v.y > max.y)
  4567. max.y = v.y;
  4568. if (v.z > max.z)
  4569. max.z = v.z;
  4570. };
  4571. Tools.WithinEpsilon = function (a, b, epsilon) {
  4572. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4573. var num = a - b;
  4574. return -epsilon <= num && num <= epsilon;
  4575. };
  4576. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4577. for (var prop in source) {
  4578. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4579. continue;
  4580. }
  4581. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4582. continue;
  4583. }
  4584. var sourceValue = source[prop];
  4585. var typeOfSourceValue = typeof sourceValue;
  4586. if (typeOfSourceValue === "function") {
  4587. continue;
  4588. }
  4589. if (typeOfSourceValue === "object") {
  4590. if (sourceValue instanceof Array) {
  4591. destination[prop] = [];
  4592. if (sourceValue.length > 0) {
  4593. if (typeof sourceValue[0] == "object") {
  4594. for (var index = 0; index < sourceValue.length; index++) {
  4595. var clonedValue = cloneValue(sourceValue[index], destination);
  4596. if (destination[prop].indexOf(clonedValue) === -1) {
  4597. destination[prop].push(clonedValue);
  4598. }
  4599. }
  4600. }
  4601. else {
  4602. destination[prop] = sourceValue.slice(0);
  4603. }
  4604. }
  4605. }
  4606. else {
  4607. destination[prop] = cloneValue(sourceValue, destination);
  4608. }
  4609. }
  4610. else {
  4611. destination[prop] = sourceValue;
  4612. }
  4613. }
  4614. };
  4615. Tools.IsEmpty = function (obj) {
  4616. for (var i in obj) {
  4617. return false;
  4618. }
  4619. return true;
  4620. };
  4621. Tools.RegisterTopRootEvents = function (events) {
  4622. for (var index = 0; index < events.length; index++) {
  4623. var event = events[index];
  4624. window.addEventListener(event.name, event.handler, false);
  4625. try {
  4626. if (window.parent) {
  4627. window.parent.addEventListener(event.name, event.handler, false);
  4628. }
  4629. }
  4630. catch (e) {
  4631. }
  4632. }
  4633. };
  4634. Tools.UnregisterTopRootEvents = function (events) {
  4635. for (var index = 0; index < events.length; index++) {
  4636. var event = events[index];
  4637. window.removeEventListener(event.name, event.handler);
  4638. try {
  4639. if (window.parent) {
  4640. window.parent.removeEventListener(event.name, event.handler);
  4641. }
  4642. }
  4643. catch (e) {
  4644. }
  4645. }
  4646. };
  4647. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4648. // Read the contents of the framebuffer
  4649. var numberOfChannelsByLine = width * 4;
  4650. var halfHeight = height / 2;
  4651. //Reading datas from WebGL
  4652. var data = engine.readPixels(0, 0, width, height);
  4653. //To flip image on Y axis.
  4654. for (var i = 0; i < halfHeight; i++) {
  4655. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4656. var currentCell = j + i * numberOfChannelsByLine;
  4657. var targetLine = height - i - 1;
  4658. var targetCell = j + targetLine * numberOfChannelsByLine;
  4659. var temp = data[currentCell];
  4660. data[currentCell] = data[targetCell];
  4661. data[targetCell] = temp;
  4662. }
  4663. }
  4664. // Create a 2D canvas to store the result
  4665. if (!screenshotCanvas) {
  4666. screenshotCanvas = document.createElement('canvas');
  4667. }
  4668. screenshotCanvas.width = width;
  4669. screenshotCanvas.height = height;
  4670. var context = screenshotCanvas.getContext('2d');
  4671. // Copy the pixels to a 2D canvas
  4672. var imageData = context.createImageData(width, height);
  4673. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4674. var castData = imageData.data;
  4675. castData.set(data);
  4676. context.putImageData(imageData, 0, 0);
  4677. var base64Image = screenshotCanvas.toDataURL();
  4678. if (successCallback) {
  4679. successCallback(base64Image);
  4680. }
  4681. else {
  4682. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4683. if (("download" in document.createElement("a"))) {
  4684. var a = window.document.createElement("a");
  4685. a.href = base64Image;
  4686. var date = new Date();
  4687. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4688. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4689. window.document.body.appendChild(a);
  4690. a.addEventListener("click", function () {
  4691. a.parentElement.removeChild(a);
  4692. });
  4693. a.click();
  4694. }
  4695. else {
  4696. var newWindow = window.open("");
  4697. var img = newWindow.document.createElement("img");
  4698. img.src = base64Image;
  4699. newWindow.document.body.appendChild(img);
  4700. }
  4701. }
  4702. };
  4703. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4704. var width;
  4705. var height;
  4706. //If a precision value is specified
  4707. if (size.precision) {
  4708. width = Math.round(engine.getRenderWidth() * size.precision);
  4709. height = Math.round(width / engine.getAspectRatio(camera));
  4710. size = { width: width, height: height };
  4711. }
  4712. else if (size.width && size.height) {
  4713. width = size.width;
  4714. height = size.height;
  4715. }
  4716. else if (size.width && !size.height) {
  4717. width = size.width;
  4718. height = Math.round(width / engine.getAspectRatio(camera));
  4719. size = { width: width, height: height };
  4720. }
  4721. else if (size.height && !size.width) {
  4722. height = size.height;
  4723. width = Math.round(height * engine.getAspectRatio(camera));
  4724. size = { width: width, height: height };
  4725. }
  4726. else if (!isNaN(size)) {
  4727. height = size;
  4728. width = size;
  4729. }
  4730. else {
  4731. Tools.Error("Invalid 'size' parameter !");
  4732. return;
  4733. }
  4734. var scene = camera.getScene();
  4735. var previousCamera = null;
  4736. if (scene.activeCamera !== camera) {
  4737. previousCamera = scene.activeCamera;
  4738. scene.activeCamera = camera;
  4739. }
  4740. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4741. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4742. texture.renderList = scene.meshes;
  4743. texture.onAfterRender = function () {
  4744. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4745. };
  4746. scene.incrementRenderId();
  4747. texture.render(true);
  4748. texture.dispose();
  4749. if (previousCamera) {
  4750. scene.activeCamera = previousCamera;
  4751. }
  4752. };
  4753. // XHR response validator for local file scenario
  4754. Tools.ValidateXHRData = function (xhr, dataType) {
  4755. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4756. if (dataType === void 0) { dataType = 7; }
  4757. try {
  4758. if (dataType & 1) {
  4759. if (xhr.responseText && xhr.responseText.length > 0) {
  4760. return true;
  4761. }
  4762. else if (dataType === 1) {
  4763. return false;
  4764. }
  4765. }
  4766. if (dataType & 2) {
  4767. // Check header width and height since there is no "TGA" magic number
  4768. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4769. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4770. return true;
  4771. }
  4772. else if (dataType === 2) {
  4773. return false;
  4774. }
  4775. }
  4776. if (dataType & 4) {
  4777. // Check for the "DDS" magic number
  4778. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4779. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4780. return true;
  4781. }
  4782. else {
  4783. return false;
  4784. }
  4785. }
  4786. }
  4787. catch (e) {
  4788. }
  4789. return false;
  4790. };
  4791. Object.defineProperty(Tools, "NoneLogLevel", {
  4792. get: function () {
  4793. return Tools._NoneLogLevel;
  4794. },
  4795. enumerable: true,
  4796. configurable: true
  4797. });
  4798. Object.defineProperty(Tools, "MessageLogLevel", {
  4799. get: function () {
  4800. return Tools._MessageLogLevel;
  4801. },
  4802. enumerable: true,
  4803. configurable: true
  4804. });
  4805. Object.defineProperty(Tools, "WarningLogLevel", {
  4806. get: function () {
  4807. return Tools._WarningLogLevel;
  4808. },
  4809. enumerable: true,
  4810. configurable: true
  4811. });
  4812. Object.defineProperty(Tools, "ErrorLogLevel", {
  4813. get: function () {
  4814. return Tools._ErrorLogLevel;
  4815. },
  4816. enumerable: true,
  4817. configurable: true
  4818. });
  4819. Object.defineProperty(Tools, "AllLogLevel", {
  4820. get: function () {
  4821. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4822. },
  4823. enumerable: true,
  4824. configurable: true
  4825. });
  4826. Tools._AddLogEntry = function (entry) {
  4827. Tools._LogCache = entry + Tools._LogCache;
  4828. if (Tools.OnNewCacheEntry) {
  4829. Tools.OnNewCacheEntry(entry);
  4830. }
  4831. };
  4832. Tools._FormatMessage = function (message) {
  4833. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4834. var date = new Date();
  4835. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4836. };
  4837. Tools._LogDisabled = function (message) {
  4838. // nothing to do
  4839. };
  4840. Tools._LogEnabled = function (message) {
  4841. var formattedMessage = Tools._FormatMessage(message);
  4842. console.log("BJS - " + formattedMessage);
  4843. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4844. Tools._AddLogEntry(entry);
  4845. };
  4846. Tools._WarnDisabled = function (message) {
  4847. // nothing to do
  4848. };
  4849. Tools._WarnEnabled = function (message) {
  4850. var formattedMessage = Tools._FormatMessage(message);
  4851. console.warn("BJS - " + formattedMessage);
  4852. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4853. Tools._AddLogEntry(entry);
  4854. };
  4855. Tools._ErrorDisabled = function (message) {
  4856. // nothing to do
  4857. };
  4858. Tools._ErrorEnabled = function (message) {
  4859. Tools.errorsCount++;
  4860. var formattedMessage = Tools._FormatMessage(message);
  4861. console.error("BJS - " + formattedMessage);
  4862. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4863. Tools._AddLogEntry(entry);
  4864. };
  4865. Object.defineProperty(Tools, "LogCache", {
  4866. get: function () {
  4867. return Tools._LogCache;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Tools.ClearLogCache = function () {
  4873. Tools._LogCache = "";
  4874. Tools.errorsCount = 0;
  4875. };
  4876. Object.defineProperty(Tools, "LogLevels", {
  4877. set: function (level) {
  4878. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4879. Tools.Log = Tools._LogEnabled;
  4880. }
  4881. else {
  4882. Tools.Log = Tools._LogDisabled;
  4883. }
  4884. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4885. Tools.Warn = Tools._WarnEnabled;
  4886. }
  4887. else {
  4888. Tools.Warn = Tools._WarnDisabled;
  4889. }
  4890. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4891. Tools.Error = Tools._ErrorEnabled;
  4892. }
  4893. else {
  4894. Tools.Error = Tools._ErrorDisabled;
  4895. }
  4896. },
  4897. enumerable: true,
  4898. configurable: true
  4899. });
  4900. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4901. get: function () {
  4902. return Tools._PerformanceNoneLogLevel;
  4903. },
  4904. enumerable: true,
  4905. configurable: true
  4906. });
  4907. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4908. get: function () {
  4909. return Tools._PerformanceUserMarkLogLevel;
  4910. },
  4911. enumerable: true,
  4912. configurable: true
  4913. });
  4914. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4915. get: function () {
  4916. return Tools._PerformanceConsoleLogLevel;
  4917. },
  4918. enumerable: true,
  4919. configurable: true
  4920. });
  4921. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4922. set: function (level) {
  4923. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4924. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4925. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4926. return;
  4927. }
  4928. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4929. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4930. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4931. return;
  4932. }
  4933. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4934. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4935. },
  4936. enumerable: true,
  4937. configurable: true
  4938. });
  4939. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4940. };
  4941. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4942. };
  4943. Tools._StartUserMark = function (counterName, condition) {
  4944. if (condition === void 0) { condition = true; }
  4945. if (!condition || !Tools._performance.mark) {
  4946. return;
  4947. }
  4948. Tools._performance.mark(counterName + "-Begin");
  4949. };
  4950. Tools._EndUserMark = function (counterName, condition) {
  4951. if (condition === void 0) { condition = true; }
  4952. if (!condition || !Tools._performance.mark) {
  4953. return;
  4954. }
  4955. Tools._performance.mark(counterName + "-End");
  4956. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4957. };
  4958. Tools._StartPerformanceConsole = function (counterName, condition) {
  4959. if (condition === void 0) { condition = true; }
  4960. if (!condition) {
  4961. return;
  4962. }
  4963. Tools._StartUserMark(counterName, condition);
  4964. if (console.time) {
  4965. console.time(counterName);
  4966. }
  4967. };
  4968. Tools._EndPerformanceConsole = function (counterName, condition) {
  4969. if (condition === void 0) { condition = true; }
  4970. if (!condition) {
  4971. return;
  4972. }
  4973. Tools._EndUserMark(counterName, condition);
  4974. if (console.time) {
  4975. console.timeEnd(counterName);
  4976. }
  4977. };
  4978. Object.defineProperty(Tools, "Now", {
  4979. get: function () {
  4980. if (window.performance && window.performance.now) {
  4981. return window.performance.now();
  4982. }
  4983. return new Date().getTime();
  4984. },
  4985. enumerable: true,
  4986. configurable: true
  4987. });
  4988. // Deprecated
  4989. Tools.GetFps = function () {
  4990. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4991. return 0;
  4992. };
  4993. Tools.BaseUrl = "";
  4994. // Logs
  4995. Tools._NoneLogLevel = 0;
  4996. Tools._MessageLogLevel = 1;
  4997. Tools._WarningLogLevel = 2;
  4998. Tools._ErrorLogLevel = 4;
  4999. Tools._LogCache = "";
  5000. Tools.errorsCount = 0;
  5001. Tools.Log = Tools._LogEnabled;
  5002. Tools.Warn = Tools._WarnEnabled;
  5003. Tools.Error = Tools._ErrorEnabled;
  5004. // Performances
  5005. Tools._PerformanceNoneLogLevel = 0;
  5006. Tools._PerformanceUserMarkLogLevel = 1;
  5007. Tools._PerformanceConsoleLogLevel = 2;
  5008. Tools._performance = window.performance;
  5009. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5010. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5011. return Tools;
  5012. })();
  5013. BABYLON.Tools = Tools;
  5014. /**
  5015. * An implementation of a loop for asynchronous functions.
  5016. */
  5017. var AsyncLoop = (function () {
  5018. /**
  5019. * Constroctor.
  5020. * @param iterations the number of iterations.
  5021. * @param _fn the function to run each iteration
  5022. * @param _successCallback the callback that will be called upon succesful execution
  5023. * @param offset starting offset.
  5024. */
  5025. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5026. if (offset === void 0) { offset = 0; }
  5027. this.iterations = iterations;
  5028. this._fn = _fn;
  5029. this._successCallback = _successCallback;
  5030. this.index = offset - 1;
  5031. this._done = false;
  5032. }
  5033. /**
  5034. * Execute the next iteration. Must be called after the last iteration was finished.
  5035. */
  5036. AsyncLoop.prototype.executeNext = function () {
  5037. if (!this._done) {
  5038. if (this.index + 1 < this.iterations) {
  5039. ++this.index;
  5040. this._fn(this);
  5041. }
  5042. else {
  5043. this.breakLoop();
  5044. }
  5045. }
  5046. };
  5047. /**
  5048. * Break the loop and run the success callback.
  5049. */
  5050. AsyncLoop.prototype.breakLoop = function () {
  5051. this._done = true;
  5052. this._successCallback();
  5053. };
  5054. /**
  5055. * Helper function
  5056. */
  5057. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5058. if (offset === void 0) { offset = 0; }
  5059. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5060. loop.executeNext();
  5061. return loop;
  5062. };
  5063. /**
  5064. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5065. * @param iterations total number of iterations
  5066. * @param syncedIterations number of synchronous iterations in each async iteration.
  5067. * @param fn the function to call each iteration.
  5068. * @param callback a success call back that will be called when iterating stops.
  5069. * @param breakFunction a break condition (optional)
  5070. * @param timeout timeout settings for the setTimeout function. default - 0.
  5071. * @constructor
  5072. */
  5073. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5074. if (timeout === void 0) { timeout = 0; }
  5075. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5076. if (breakFunction && breakFunction())
  5077. loop.breakLoop();
  5078. else {
  5079. setTimeout(function () {
  5080. for (var i = 0; i < syncedIterations; ++i) {
  5081. var iteration = (loop.index * syncedIterations) + i;
  5082. if (iteration >= iterations)
  5083. break;
  5084. fn(iteration);
  5085. if (breakFunction && breakFunction()) {
  5086. loop.breakLoop();
  5087. break;
  5088. }
  5089. }
  5090. loop.executeNext();
  5091. }, timeout);
  5092. }
  5093. }, callback);
  5094. };
  5095. return AsyncLoop;
  5096. })();
  5097. BABYLON.AsyncLoop = AsyncLoop;
  5098. })(BABYLON || (BABYLON = {}));
  5099. var BABYLON;
  5100. (function (BABYLON) {
  5101. var _DepthCullingState = (function () {
  5102. function _DepthCullingState() {
  5103. this._isDepthTestDirty = false;
  5104. this._isDepthMaskDirty = false;
  5105. this._isDepthFuncDirty = false;
  5106. this._isCullFaceDirty = false;
  5107. this._isCullDirty = false;
  5108. this._isZOffsetDirty = false;
  5109. }
  5110. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5111. get: function () {
  5112. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5113. },
  5114. enumerable: true,
  5115. configurable: true
  5116. });
  5117. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5118. get: function () {
  5119. return this._zOffset;
  5120. },
  5121. set: function (value) {
  5122. if (this._zOffset === value) {
  5123. return;
  5124. }
  5125. this._zOffset = value;
  5126. this._isZOffsetDirty = true;
  5127. },
  5128. enumerable: true,
  5129. configurable: true
  5130. });
  5131. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5132. get: function () {
  5133. return this._cullFace;
  5134. },
  5135. set: function (value) {
  5136. if (this._cullFace === value) {
  5137. return;
  5138. }
  5139. this._cullFace = value;
  5140. this._isCullFaceDirty = true;
  5141. },
  5142. enumerable: true,
  5143. configurable: true
  5144. });
  5145. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5146. get: function () {
  5147. return this._cull;
  5148. },
  5149. set: function (value) {
  5150. if (this._cull === value) {
  5151. return;
  5152. }
  5153. this._cull = value;
  5154. this._isCullDirty = true;
  5155. },
  5156. enumerable: true,
  5157. configurable: true
  5158. });
  5159. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5160. get: function () {
  5161. return this._depthFunc;
  5162. },
  5163. set: function (value) {
  5164. if (this._depthFunc === value) {
  5165. return;
  5166. }
  5167. this._depthFunc = value;
  5168. this._isDepthFuncDirty = true;
  5169. },
  5170. enumerable: true,
  5171. configurable: true
  5172. });
  5173. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5174. get: function () {
  5175. return this._depthMask;
  5176. },
  5177. set: function (value) {
  5178. if (this._depthMask === value) {
  5179. return;
  5180. }
  5181. this._depthMask = value;
  5182. this._isDepthMaskDirty = true;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5188. get: function () {
  5189. return this._depthTest;
  5190. },
  5191. set: function (value) {
  5192. if (this._depthTest === value) {
  5193. return;
  5194. }
  5195. this._depthTest = value;
  5196. this._isDepthTestDirty = true;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. _DepthCullingState.prototype.reset = function () {
  5202. this._depthMask = true;
  5203. this._depthTest = true;
  5204. this._depthFunc = null;
  5205. this._cull = null;
  5206. this._cullFace = null;
  5207. this._zOffset = 0;
  5208. this._isDepthTestDirty = true;
  5209. this._isDepthMaskDirty = true;
  5210. this._isDepthFuncDirty = false;
  5211. this._isCullFaceDirty = false;
  5212. this._isCullDirty = false;
  5213. this._isZOffsetDirty = false;
  5214. };
  5215. _DepthCullingState.prototype.apply = function (gl) {
  5216. if (!this.isDirty) {
  5217. return;
  5218. }
  5219. // Cull
  5220. if (this._isCullDirty) {
  5221. if (this.cull) {
  5222. gl.enable(gl.CULL_FACE);
  5223. }
  5224. else {
  5225. gl.disable(gl.CULL_FACE);
  5226. }
  5227. this._isCullDirty = false;
  5228. }
  5229. // Cull face
  5230. if (this._isCullFaceDirty) {
  5231. gl.cullFace(this.cullFace);
  5232. this._isCullFaceDirty = false;
  5233. }
  5234. // Depth mask
  5235. if (this._isDepthMaskDirty) {
  5236. gl.depthMask(this.depthMask);
  5237. this._isDepthMaskDirty = false;
  5238. }
  5239. // Depth test
  5240. if (this._isDepthTestDirty) {
  5241. if (this.depthTest) {
  5242. gl.enable(gl.DEPTH_TEST);
  5243. }
  5244. else {
  5245. gl.disable(gl.DEPTH_TEST);
  5246. }
  5247. this._isDepthTestDirty = false;
  5248. }
  5249. // Depth func
  5250. if (this._isDepthFuncDirty) {
  5251. gl.depthFunc(this.depthFunc);
  5252. this._isDepthFuncDirty = false;
  5253. }
  5254. // zOffset
  5255. if (this._isZOffsetDirty) {
  5256. if (this.zOffset) {
  5257. gl.enable(gl.POLYGON_OFFSET_FILL);
  5258. gl.polygonOffset(this.zOffset, 0);
  5259. }
  5260. else {
  5261. gl.disable(gl.POLYGON_OFFSET_FILL);
  5262. }
  5263. this._isZOffsetDirty = false;
  5264. }
  5265. };
  5266. return _DepthCullingState;
  5267. })();
  5268. BABYLON._DepthCullingState = _DepthCullingState;
  5269. var _AlphaState = (function () {
  5270. function _AlphaState() {
  5271. this._isAlphaBlendDirty = false;
  5272. this._isBlendFunctionParametersDirty = false;
  5273. this._alphaBlend = false;
  5274. this._blendFunctionParameters = new Array(4);
  5275. }
  5276. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5277. get: function () {
  5278. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5279. },
  5280. enumerable: true,
  5281. configurable: true
  5282. });
  5283. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5284. get: function () {
  5285. return this._alphaBlend;
  5286. },
  5287. set: function (value) {
  5288. if (this._alphaBlend === value) {
  5289. return;
  5290. }
  5291. this._alphaBlend = value;
  5292. this._isAlphaBlendDirty = true;
  5293. },
  5294. enumerable: true,
  5295. configurable: true
  5296. });
  5297. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5298. if (this._blendFunctionParameters[0] === value0 &&
  5299. this._blendFunctionParameters[1] === value1 &&
  5300. this._blendFunctionParameters[2] === value2 &&
  5301. this._blendFunctionParameters[3] === value3) {
  5302. return;
  5303. }
  5304. this._blendFunctionParameters[0] = value0;
  5305. this._blendFunctionParameters[1] = value1;
  5306. this._blendFunctionParameters[2] = value2;
  5307. this._blendFunctionParameters[3] = value3;
  5308. this._isBlendFunctionParametersDirty = true;
  5309. };
  5310. _AlphaState.prototype.reset = function () {
  5311. this._alphaBlend = false;
  5312. this._blendFunctionParameters[0] = null;
  5313. this._blendFunctionParameters[1] = null;
  5314. this._blendFunctionParameters[2] = null;
  5315. this._blendFunctionParameters[3] = null;
  5316. this._isAlphaBlendDirty = true;
  5317. this._isBlendFunctionParametersDirty = false;
  5318. };
  5319. _AlphaState.prototype.apply = function (gl) {
  5320. if (!this.isDirty) {
  5321. return;
  5322. }
  5323. // Alpha blend
  5324. if (this._isAlphaBlendDirty) {
  5325. if (this._alphaBlend) {
  5326. gl.enable(gl.BLEND);
  5327. }
  5328. else {
  5329. gl.disable(gl.BLEND);
  5330. }
  5331. this._isAlphaBlendDirty = false;
  5332. }
  5333. // Alpha function
  5334. if (this._isBlendFunctionParametersDirty) {
  5335. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5336. this._isBlendFunctionParametersDirty = false;
  5337. }
  5338. };
  5339. return _AlphaState;
  5340. })();
  5341. BABYLON._AlphaState = _AlphaState;
  5342. var compileShader = function (gl, source, type, defines) {
  5343. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5344. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5345. gl.compileShader(shader);
  5346. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5347. throw new Error(gl.getShaderInfoLog(shader));
  5348. }
  5349. return shader;
  5350. };
  5351. var getWebGLTextureType = function (gl, type) {
  5352. var textureType = gl.UNSIGNED_BYTE;
  5353. if (type === Engine.TEXTURETYPE_FLOAT)
  5354. textureType = gl.FLOAT;
  5355. return textureType;
  5356. };
  5357. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5358. var magFilter = gl.NEAREST;
  5359. var minFilter = gl.NEAREST;
  5360. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5361. magFilter = gl.LINEAR;
  5362. if (generateMipMaps) {
  5363. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5364. }
  5365. else {
  5366. minFilter = gl.LINEAR;
  5367. }
  5368. }
  5369. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5370. magFilter = gl.LINEAR;
  5371. if (generateMipMaps) {
  5372. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5373. }
  5374. else {
  5375. minFilter = gl.LINEAR;
  5376. }
  5377. }
  5378. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5379. magFilter = gl.NEAREST;
  5380. if (generateMipMaps) {
  5381. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5382. }
  5383. else {
  5384. minFilter = gl.NEAREST;
  5385. }
  5386. }
  5387. return {
  5388. min: minFilter,
  5389. mag: magFilter
  5390. };
  5391. };
  5392. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5394. var engine = scene.getEngine();
  5395. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5396. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5397. gl.bindTexture(gl.TEXTURE_2D, texture);
  5398. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5399. texture._baseWidth = width;
  5400. texture._baseHeight = height;
  5401. texture._width = potWidth;
  5402. texture._height = potHeight;
  5403. texture.isReady = true;
  5404. processFunction(potWidth, potHeight);
  5405. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5407. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5408. if (!noMipmap && !isCompressed) {
  5409. gl.generateMipmap(gl.TEXTURE_2D);
  5410. }
  5411. gl.bindTexture(gl.TEXTURE_2D, null);
  5412. engine._activeTexturesCache = [];
  5413. scene._removePendingData(texture);
  5414. };
  5415. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5416. var onload = function () {
  5417. loadedImages[index] = img;
  5418. loadedImages._internalCount++;
  5419. scene._removePendingData(img);
  5420. if (loadedImages._internalCount === 6) {
  5421. onfinish(loadedImages);
  5422. }
  5423. };
  5424. var onerror = function () {
  5425. scene._removePendingData(img);
  5426. };
  5427. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5428. scene._addPendingData(img);
  5429. };
  5430. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5431. var loadedImages = [];
  5432. loadedImages._internalCount = 0;
  5433. for (var index = 0; index < 6; index++) {
  5434. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5435. }
  5436. };
  5437. var EngineCapabilities = (function () {
  5438. function EngineCapabilities() {
  5439. }
  5440. return EngineCapabilities;
  5441. })();
  5442. BABYLON.EngineCapabilities = EngineCapabilities;
  5443. /**
  5444. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5445. */
  5446. var Engine = (function () {
  5447. /**
  5448. * @constructor
  5449. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5450. * @param {boolean} [antialias] - enable antialias
  5451. * @param options - further options to be sent to the getContext function
  5452. */
  5453. function Engine(canvas, antialias, options) {
  5454. var _this = this;
  5455. // Public members
  5456. this.isFullscreen = false;
  5457. this.isPointerLock = false;
  5458. this.cullBackFaces = true;
  5459. this.renderEvenInBackground = true;
  5460. // To enable/disable IDB support and avoid XHR on .manifest
  5461. this.enableOfflineSupport = true;
  5462. this.scenes = new Array();
  5463. this._windowIsBackground = false;
  5464. this._drawCalls = 0;
  5465. this._renderingQueueLaunched = false;
  5466. this._activeRenderLoops = [];
  5467. // FPS
  5468. this.fpsRange = 60;
  5469. this.previousFramesDuration = [];
  5470. this.fps = 60;
  5471. this.deltaTime = 0;
  5472. // States
  5473. this._depthCullingState = new _DepthCullingState();
  5474. this._alphaState = new _AlphaState();
  5475. this._alphaMode = Engine.ALPHA_DISABLE;
  5476. // Cache
  5477. this._loadedTexturesCache = new Array();
  5478. this._activeTexturesCache = new Array();
  5479. this._compiledEffects = {};
  5480. this._uintIndicesCurrentlySet = false;
  5481. this._renderingCanvas = canvas;
  5482. options = options || {};
  5483. options.antialias = antialias;
  5484. if (options.preserveDrawingBuffer === undefined) {
  5485. options.preserveDrawingBuffer = false;
  5486. }
  5487. // GL
  5488. try {
  5489. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5490. }
  5491. catch (e) {
  5492. throw new Error("WebGL not supported");
  5493. }
  5494. if (!this._gl) {
  5495. throw new Error("WebGL not supported");
  5496. }
  5497. this._onBlur = function () {
  5498. _this._windowIsBackground = true;
  5499. };
  5500. this._onFocus = function () {
  5501. _this._windowIsBackground = false;
  5502. };
  5503. window.addEventListener("blur", this._onBlur);
  5504. window.addEventListener("focus", this._onFocus);
  5505. // Viewport
  5506. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5507. this.resize();
  5508. // Caps
  5509. this._caps = new EngineCapabilities();
  5510. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5511. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5512. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5513. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5514. // Infos
  5515. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5516. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5517. if (rendererInfo != null) {
  5518. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5519. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5520. }
  5521. if (!this._glVendor) {
  5522. this._glVendor = "Unknown vendor";
  5523. }
  5524. if (!this._glRenderer) {
  5525. this._glRenderer = "Unknown renderer";
  5526. }
  5527. // Extensions
  5528. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5529. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5530. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5531. 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');
  5532. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5533. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5534. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5535. this._caps.highPrecisionShaderSupported = true;
  5536. if (this._gl.getShaderPrecisionFormat) {
  5537. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5538. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5539. }
  5540. // Depth buffer
  5541. this.setDepthBuffer(true);
  5542. this.setDepthFunctionToLessOrEqual();
  5543. this.setDepthWrite(true);
  5544. // Fullscreen
  5545. this._onFullscreenChange = function () {
  5546. if (document.fullscreen !== undefined) {
  5547. _this.isFullscreen = document.fullscreen;
  5548. }
  5549. else if (document.mozFullScreen !== undefined) {
  5550. _this.isFullscreen = document.mozFullScreen;
  5551. }
  5552. else if (document.webkitIsFullScreen !== undefined) {
  5553. _this.isFullscreen = document.webkitIsFullScreen;
  5554. }
  5555. else if (document.msIsFullScreen !== undefined) {
  5556. _this.isFullscreen = document.msIsFullScreen;
  5557. }
  5558. // Pointer lock
  5559. if (_this.isFullscreen && _this._pointerLockRequested) {
  5560. canvas.requestPointerLock = canvas.requestPointerLock ||
  5561. canvas.msRequestPointerLock ||
  5562. canvas.mozRequestPointerLock ||
  5563. canvas.webkitRequestPointerLock;
  5564. if (canvas.requestPointerLock) {
  5565. canvas.requestPointerLock();
  5566. }
  5567. }
  5568. };
  5569. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5570. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5571. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5572. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5573. // Pointer lock
  5574. this._onPointerLockChange = function () {
  5575. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5576. document.webkitPointerLockElement === canvas ||
  5577. document.msPointerLockElement === canvas ||
  5578. document.pointerLockElement === canvas);
  5579. };
  5580. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5581. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5582. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5583. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5584. if (!Engine.audioEngine) {
  5585. Engine.audioEngine = new BABYLON.AudioEngine();
  5586. }
  5587. //default loading screen
  5588. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5589. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5590. }
  5591. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5592. get: function () {
  5593. return Engine._ALPHA_DISABLE;
  5594. },
  5595. enumerable: true,
  5596. configurable: true
  5597. });
  5598. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5599. get: function () {
  5600. return Engine._ALPHA_ONEONE;
  5601. },
  5602. enumerable: true,
  5603. configurable: true
  5604. });
  5605. Object.defineProperty(Engine, "ALPHA_ADD", {
  5606. get: function () {
  5607. return Engine._ALPHA_ADD;
  5608. },
  5609. enumerable: true,
  5610. configurable: true
  5611. });
  5612. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5613. get: function () {
  5614. return Engine._ALPHA_COMBINE;
  5615. },
  5616. enumerable: true,
  5617. configurable: true
  5618. });
  5619. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5620. get: function () {
  5621. return Engine._ALPHA_SUBTRACT;
  5622. },
  5623. enumerable: true,
  5624. configurable: true
  5625. });
  5626. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5627. get: function () {
  5628. return Engine._ALPHA_MULTIPLY;
  5629. },
  5630. enumerable: true,
  5631. configurable: true
  5632. });
  5633. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5634. get: function () {
  5635. return Engine._ALPHA_MAXIMIZED;
  5636. },
  5637. enumerable: true,
  5638. configurable: true
  5639. });
  5640. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5641. get: function () {
  5642. return Engine._DELAYLOADSTATE_NONE;
  5643. },
  5644. enumerable: true,
  5645. configurable: true
  5646. });
  5647. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5648. get: function () {
  5649. return Engine._DELAYLOADSTATE_LOADED;
  5650. },
  5651. enumerable: true,
  5652. configurable: true
  5653. });
  5654. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5655. get: function () {
  5656. return Engine._DELAYLOADSTATE_LOADING;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5662. get: function () {
  5663. return Engine._DELAYLOADSTATE_NOTLOADED;
  5664. },
  5665. enumerable: true,
  5666. configurable: true
  5667. });
  5668. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5669. get: function () {
  5670. return Engine._TEXTUREFORMAT_ALPHA;
  5671. },
  5672. enumerable: true,
  5673. configurable: true
  5674. });
  5675. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5676. get: function () {
  5677. return Engine._TEXTUREFORMAT_LUMINANCE;
  5678. },
  5679. enumerable: true,
  5680. configurable: true
  5681. });
  5682. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5683. get: function () {
  5684. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5685. },
  5686. enumerable: true,
  5687. configurable: true
  5688. });
  5689. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5690. get: function () {
  5691. return Engine._TEXTUREFORMAT_RGB;
  5692. },
  5693. enumerable: true,
  5694. configurable: true
  5695. });
  5696. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5697. get: function () {
  5698. return Engine._TEXTUREFORMAT_RGBA;
  5699. },
  5700. enumerable: true,
  5701. configurable: true
  5702. });
  5703. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5704. get: function () {
  5705. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5706. },
  5707. enumerable: true,
  5708. configurable: true
  5709. });
  5710. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5711. get: function () {
  5712. return Engine._TEXTURETYPE_FLOAT;
  5713. },
  5714. enumerable: true,
  5715. configurable: true
  5716. });
  5717. Object.defineProperty(Engine, "Version", {
  5718. get: function () {
  5719. return "2.3.0-alpha";
  5720. },
  5721. enumerable: true,
  5722. configurable: true
  5723. });
  5724. Engine.prototype._prepareWorkingCanvas = function () {
  5725. if (this._workingCanvas) {
  5726. return;
  5727. }
  5728. this._workingCanvas = document.createElement("canvas");
  5729. this._workingContext = this._workingCanvas.getContext("2d");
  5730. };
  5731. Engine.prototype.getGlInfo = function () {
  5732. return {
  5733. vendor: this._glVendor,
  5734. renderer: this._glRenderer,
  5735. version: this._glVersion
  5736. };
  5737. };
  5738. Engine.prototype.getAspectRatio = function (camera) {
  5739. var viewport = camera.viewport;
  5740. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5741. };
  5742. Engine.prototype.getRenderWidth = function () {
  5743. if (this._currentRenderTarget) {
  5744. return this._currentRenderTarget._width;
  5745. }
  5746. return this._renderingCanvas.width;
  5747. };
  5748. Engine.prototype.getRenderHeight = function () {
  5749. if (this._currentRenderTarget) {
  5750. return this._currentRenderTarget._height;
  5751. }
  5752. return this._renderingCanvas.height;
  5753. };
  5754. Engine.prototype.getRenderingCanvas = function () {
  5755. return this._renderingCanvas;
  5756. };
  5757. Engine.prototype.getRenderingCanvasClientRect = function () {
  5758. return this._renderingCanvas.getBoundingClientRect();
  5759. };
  5760. Engine.prototype.setHardwareScalingLevel = function (level) {
  5761. this._hardwareScalingLevel = level;
  5762. this.resize();
  5763. };
  5764. Engine.prototype.getHardwareScalingLevel = function () {
  5765. return this._hardwareScalingLevel;
  5766. };
  5767. Engine.prototype.getLoadedTexturesCache = function () {
  5768. return this._loadedTexturesCache;
  5769. };
  5770. Engine.prototype.getCaps = function () {
  5771. return this._caps;
  5772. };
  5773. Object.defineProperty(Engine.prototype, "drawCalls", {
  5774. get: function () {
  5775. return this._drawCalls;
  5776. },
  5777. enumerable: true,
  5778. configurable: true
  5779. });
  5780. // Methods
  5781. Engine.prototype.resetDrawCalls = function () {
  5782. this._drawCalls = 0;
  5783. };
  5784. Engine.prototype.setDepthFunctionToGreater = function () {
  5785. this._depthCullingState.depthFunc = this._gl.GREATER;
  5786. };
  5787. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5788. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5789. };
  5790. Engine.prototype.setDepthFunctionToLess = function () {
  5791. this._depthCullingState.depthFunc = this._gl.LESS;
  5792. };
  5793. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5794. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5795. };
  5796. /**
  5797. * stop executing a render loop function and remove it from the execution array
  5798. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5799. */
  5800. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5801. if (!renderFunction) {
  5802. this._activeRenderLoops = [];
  5803. return;
  5804. }
  5805. var index = this._activeRenderLoops.indexOf(renderFunction);
  5806. if (index >= 0) {
  5807. this._activeRenderLoops.splice(index, 1);
  5808. }
  5809. };
  5810. Engine.prototype._renderLoop = function () {
  5811. var _this = this;
  5812. var shouldRender = true;
  5813. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5814. shouldRender = false;
  5815. }
  5816. if (shouldRender) {
  5817. // Start new frame
  5818. this.beginFrame();
  5819. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5820. var renderFunction = this._activeRenderLoops[index];
  5821. renderFunction();
  5822. }
  5823. // Present
  5824. this.endFrame();
  5825. }
  5826. if (this._activeRenderLoops.length > 0) {
  5827. // Register new frame
  5828. BABYLON.Tools.QueueNewFrame(function () {
  5829. _this._renderLoop();
  5830. });
  5831. }
  5832. else {
  5833. this._renderingQueueLaunched = false;
  5834. }
  5835. };
  5836. /**
  5837. * Register and execute a render loop. The engine can have more than one render function.
  5838. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5839. * @example
  5840. * engine.runRenderLoop(function () {
  5841. * scene.render()
  5842. * })
  5843. */
  5844. Engine.prototype.runRenderLoop = function (renderFunction) {
  5845. var _this = this;
  5846. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5847. return;
  5848. }
  5849. this._activeRenderLoops.push(renderFunction);
  5850. if (!this._renderingQueueLaunched) {
  5851. this._renderingQueueLaunched = true;
  5852. BABYLON.Tools.QueueNewFrame(function () {
  5853. _this._renderLoop();
  5854. });
  5855. }
  5856. };
  5857. /**
  5858. * Toggle full screen mode.
  5859. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5860. */
  5861. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5862. if (this.isFullscreen) {
  5863. BABYLON.Tools.ExitFullscreen();
  5864. }
  5865. else {
  5866. this._pointerLockRequested = requestPointerLock;
  5867. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5868. }
  5869. };
  5870. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5871. this.applyStates();
  5872. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5873. if (this._depthCullingState.depthMask) {
  5874. this._gl.clearDepth(1.0);
  5875. }
  5876. var mode = 0;
  5877. if (backBuffer)
  5878. mode |= this._gl.COLOR_BUFFER_BIT;
  5879. if (depthStencil && this._depthCullingState.depthMask)
  5880. mode |= this._gl.DEPTH_BUFFER_BIT;
  5881. this._gl.clear(mode);
  5882. };
  5883. /**
  5884. * Set the WebGL's viewport
  5885. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5886. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5887. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5888. */
  5889. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5890. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5891. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5892. var x = viewport.x || 0;
  5893. var y = viewport.y || 0;
  5894. this._cachedViewport = viewport;
  5895. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5896. };
  5897. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5898. this._cachedViewport = null;
  5899. this._gl.viewport(x, y, width, height);
  5900. };
  5901. Engine.prototype.beginFrame = function () {
  5902. this._measureFps();
  5903. };
  5904. Engine.prototype.endFrame = function () {
  5905. //this.flushFramebuffer();
  5906. };
  5907. /**
  5908. * resize the view according to the canvas' size.
  5909. * @example
  5910. * window.addEventListener("resize", function () {
  5911. * engine.resize();
  5912. * });
  5913. */
  5914. Engine.prototype.resize = function () {
  5915. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5916. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5917. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5918. };
  5919. /**
  5920. * force a specific size of the canvas
  5921. * @param {number} width - the new canvas' width
  5922. * @param {number} height - the new canvas' height
  5923. */
  5924. Engine.prototype.setSize = function (width, height) {
  5925. this._renderingCanvas.width = width;
  5926. this._renderingCanvas.height = height;
  5927. for (var index = 0; index < this.scenes.length; index++) {
  5928. var scene = this.scenes[index];
  5929. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5930. var cam = scene.cameras[camIndex];
  5931. cam._currentRenderId = 0;
  5932. }
  5933. }
  5934. };
  5935. Engine.prototype.bindFramebuffer = function (texture) {
  5936. this._currentRenderTarget = texture;
  5937. var gl = this._gl;
  5938. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5939. this._gl.viewport(0, 0, texture._width, texture._height);
  5940. this.wipeCaches();
  5941. };
  5942. Engine.prototype.unBindFramebuffer = function (texture) {
  5943. this._currentRenderTarget = null;
  5944. if (texture.generateMipMaps) {
  5945. var gl = this._gl;
  5946. gl.bindTexture(gl.TEXTURE_2D, texture);
  5947. gl.generateMipmap(gl.TEXTURE_2D);
  5948. gl.bindTexture(gl.TEXTURE_2D, null);
  5949. }
  5950. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5951. };
  5952. Engine.prototype.flushFramebuffer = function () {
  5953. this._gl.flush();
  5954. };
  5955. Engine.prototype.restoreDefaultFramebuffer = function () {
  5956. this._currentRenderTarget = null;
  5957. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5958. this.setViewport(this._cachedViewport);
  5959. this.wipeCaches();
  5960. };
  5961. // VBOs
  5962. Engine.prototype._resetVertexBufferBinding = function () {
  5963. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5964. this._cachedVertexBuffers = null;
  5965. };
  5966. Engine.prototype.createVertexBuffer = function (vertices) {
  5967. var vbo = this._gl.createBuffer();
  5968. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5969. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5970. this._resetVertexBufferBinding();
  5971. vbo.references = 1;
  5972. return vbo;
  5973. };
  5974. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5975. var vbo = this._gl.createBuffer();
  5976. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5977. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5978. this._resetVertexBufferBinding();
  5979. vbo.references = 1;
  5980. return vbo;
  5981. };
  5982. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5983. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5984. if (offset === undefined) {
  5985. offset = 0;
  5986. }
  5987. if (vertices instanceof Float32Array) {
  5988. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5989. }
  5990. else {
  5991. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5992. }
  5993. this._resetVertexBufferBinding();
  5994. };
  5995. Engine.prototype._resetIndexBufferBinding = function () {
  5996. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5997. this._cachedIndexBuffer = null;
  5998. };
  5999. Engine.prototype.createIndexBuffer = function (indices) {
  6000. var vbo = this._gl.createBuffer();
  6001. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6002. // Check for 32 bits indices
  6003. var arrayBuffer;
  6004. var need32Bits = false;
  6005. if (this._caps.uintIndices) {
  6006. for (var index = 0; index < indices.length; index++) {
  6007. if (indices[index] > 65535) {
  6008. need32Bits = true;
  6009. break;
  6010. }
  6011. }
  6012. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6013. }
  6014. else {
  6015. arrayBuffer = new Uint16Array(indices);
  6016. }
  6017. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6018. this._resetIndexBufferBinding();
  6019. vbo.references = 1;
  6020. vbo.is32Bits = need32Bits;
  6021. return vbo;
  6022. };
  6023. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6024. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6025. this._cachedVertexBuffers = vertexBuffer;
  6026. this._cachedEffectForVertexBuffers = effect;
  6027. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6028. var offset = 0;
  6029. for (var index = 0; index < vertexDeclaration.length; index++) {
  6030. var order = effect.getAttributeLocation(index);
  6031. if (order >= 0) {
  6032. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6033. }
  6034. offset += vertexDeclaration[index] * 4;
  6035. }
  6036. }
  6037. if (this._cachedIndexBuffer !== indexBuffer) {
  6038. this._cachedIndexBuffer = indexBuffer;
  6039. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6040. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6041. }
  6042. };
  6043. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6044. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6045. this._cachedVertexBuffers = vertexBuffers;
  6046. this._cachedEffectForVertexBuffers = effect;
  6047. var attributes = effect.getAttributesNames();
  6048. for (var index = 0; index < attributes.length; index++) {
  6049. var order = effect.getAttributeLocation(index);
  6050. if (order >= 0) {
  6051. var vertexBuffer = vertexBuffers[attributes[index]];
  6052. if (!vertexBuffer) {
  6053. continue;
  6054. }
  6055. var stride = vertexBuffer.getStrideSize();
  6056. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6057. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6058. }
  6059. }
  6060. }
  6061. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6062. this._cachedIndexBuffer = indexBuffer;
  6063. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6064. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6065. }
  6066. };
  6067. Engine.prototype._releaseBuffer = function (buffer) {
  6068. buffer.references--;
  6069. if (buffer.references === 0) {
  6070. this._gl.deleteBuffer(buffer);
  6071. return true;
  6072. }
  6073. return false;
  6074. };
  6075. Engine.prototype.createInstancesBuffer = function (capacity) {
  6076. var buffer = this._gl.createBuffer();
  6077. buffer.capacity = capacity;
  6078. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6079. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6080. return buffer;
  6081. };
  6082. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6083. this._gl.deleteBuffer(buffer);
  6084. };
  6085. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6086. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6087. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6088. for (var index = 0; index < 4; index++) {
  6089. var offsetLocation = offsetLocations[index];
  6090. this._gl.enableVertexAttribArray(offsetLocation);
  6091. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6092. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6093. }
  6094. };
  6095. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6096. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6097. for (var index = 0; index < 4; index++) {
  6098. var offsetLocation = offsetLocations[index];
  6099. this._gl.disableVertexAttribArray(offsetLocation);
  6100. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6101. }
  6102. };
  6103. Engine.prototype.applyStates = function () {
  6104. this._depthCullingState.apply(this._gl);
  6105. this._alphaState.apply(this._gl);
  6106. };
  6107. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6108. // Apply states
  6109. this.applyStates();
  6110. this._drawCalls++;
  6111. // Render
  6112. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6113. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6114. if (instancesCount) {
  6115. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6116. return;
  6117. }
  6118. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6119. };
  6120. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6121. // Apply states
  6122. this.applyStates();
  6123. this._drawCalls++;
  6124. if (instancesCount) {
  6125. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6126. return;
  6127. }
  6128. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6129. };
  6130. // Shaders
  6131. Engine.prototype._releaseEffect = function (effect) {
  6132. if (this._compiledEffects[effect._key]) {
  6133. delete this._compiledEffects[effect._key];
  6134. if (effect.getProgram()) {
  6135. this._gl.deleteProgram(effect.getProgram());
  6136. }
  6137. }
  6138. };
  6139. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6140. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6141. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6142. var name = vertex + "+" + fragment + "@" + defines;
  6143. if (this._compiledEffects[name]) {
  6144. return this._compiledEffects[name];
  6145. }
  6146. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6147. effect._key = name;
  6148. this._compiledEffects[name] = effect;
  6149. return effect;
  6150. };
  6151. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6152. if (uniformsNames === void 0) { uniformsNames = []; }
  6153. if (samplers === void 0) { samplers = []; }
  6154. if (defines === void 0) { defines = ""; }
  6155. return this.createEffect({
  6156. vertex: "particles",
  6157. fragmentElement: fragmentName
  6158. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6159. };
  6160. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6161. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6162. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6163. var shaderProgram = this._gl.createProgram();
  6164. this._gl.attachShader(shaderProgram, vertexShader);
  6165. this._gl.attachShader(shaderProgram, fragmentShader);
  6166. this._gl.linkProgram(shaderProgram);
  6167. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6168. if (!linked) {
  6169. var error = this._gl.getProgramInfoLog(shaderProgram);
  6170. if (error) {
  6171. throw new Error(error);
  6172. }
  6173. }
  6174. this._gl.deleteShader(vertexShader);
  6175. this._gl.deleteShader(fragmentShader);
  6176. return shaderProgram;
  6177. };
  6178. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6179. var results = [];
  6180. for (var index = 0; index < uniformsNames.length; index++) {
  6181. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6182. }
  6183. return results;
  6184. };
  6185. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6186. var results = [];
  6187. for (var index = 0; index < attributesNames.length; index++) {
  6188. try {
  6189. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6190. }
  6191. catch (e) {
  6192. results.push(-1);
  6193. }
  6194. }
  6195. return results;
  6196. };
  6197. Engine.prototype.enableEffect = function (effect) {
  6198. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6199. if (effect && effect.onBind) {
  6200. effect.onBind(effect);
  6201. }
  6202. return;
  6203. }
  6204. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6205. // Use program
  6206. this._gl.useProgram(effect.getProgram());
  6207. for (var i in this._vertexAttribArrays) {
  6208. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6209. continue;
  6210. }
  6211. this._vertexAttribArrays[i] = false;
  6212. this._gl.disableVertexAttribArray(i);
  6213. }
  6214. var attributesCount = effect.getAttributesCount();
  6215. for (var index = 0; index < attributesCount; index++) {
  6216. // Attributes
  6217. var order = effect.getAttributeLocation(index);
  6218. if (order >= 0) {
  6219. this._vertexAttribArrays[order] = true;
  6220. this._gl.enableVertexAttribArray(order);
  6221. }
  6222. }
  6223. this._currentEffect = effect;
  6224. if (effect.onBind) {
  6225. effect.onBind(effect);
  6226. }
  6227. };
  6228. Engine.prototype.setArray = function (uniform, array) {
  6229. if (!uniform)
  6230. return;
  6231. this._gl.uniform1fv(uniform, array);
  6232. };
  6233. Engine.prototype.setArray2 = function (uniform, array) {
  6234. if (!uniform || array.length % 2 !== 0)
  6235. return;
  6236. this._gl.uniform2fv(uniform, array);
  6237. };
  6238. Engine.prototype.setArray3 = function (uniform, array) {
  6239. if (!uniform || array.length % 3 !== 0)
  6240. return;
  6241. this._gl.uniform3fv(uniform, array);
  6242. };
  6243. Engine.prototype.setArray4 = function (uniform, array) {
  6244. if (!uniform || array.length % 4 !== 0)
  6245. return;
  6246. this._gl.uniform4fv(uniform, array);
  6247. };
  6248. Engine.prototype.setMatrices = function (uniform, matrices) {
  6249. if (!uniform)
  6250. return;
  6251. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6252. };
  6253. Engine.prototype.setMatrix = function (uniform, matrix) {
  6254. if (!uniform)
  6255. return;
  6256. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6257. };
  6258. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6259. if (!uniform)
  6260. return;
  6261. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6262. };
  6263. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6264. if (!uniform)
  6265. return;
  6266. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6267. };
  6268. Engine.prototype.setFloat = function (uniform, value) {
  6269. if (!uniform)
  6270. return;
  6271. this._gl.uniform1f(uniform, value);
  6272. };
  6273. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6274. if (!uniform)
  6275. return;
  6276. this._gl.uniform2f(uniform, x, y);
  6277. };
  6278. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6279. if (!uniform)
  6280. return;
  6281. this._gl.uniform3f(uniform, x, y, z);
  6282. };
  6283. Engine.prototype.setBool = function (uniform, bool) {
  6284. if (!uniform)
  6285. return;
  6286. this._gl.uniform1i(uniform, bool);
  6287. };
  6288. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6289. if (!uniform)
  6290. return;
  6291. this._gl.uniform4f(uniform, x, y, z, w);
  6292. };
  6293. Engine.prototype.setColor3 = function (uniform, color3) {
  6294. if (!uniform)
  6295. return;
  6296. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6297. };
  6298. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6299. if (!uniform)
  6300. return;
  6301. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6302. };
  6303. // States
  6304. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6305. if (zOffset === void 0) { zOffset = 0; }
  6306. if (reverseSide === void 0) { reverseSide = false; }
  6307. // Culling
  6308. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6309. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6310. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6311. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace != cullFace) {
  6312. if (culling) {
  6313. this._depthCullingState.cullFace = cullFace;
  6314. this._depthCullingState.cull = true;
  6315. }
  6316. else {
  6317. this._depthCullingState.cull = false;
  6318. }
  6319. }
  6320. // Z offset
  6321. this._depthCullingState.zOffset = zOffset;
  6322. };
  6323. Engine.prototype.setDepthBuffer = function (enable) {
  6324. this._depthCullingState.depthTest = enable;
  6325. };
  6326. Engine.prototype.getDepthWrite = function () {
  6327. return this._depthCullingState.depthMask;
  6328. };
  6329. Engine.prototype.setDepthWrite = function (enable) {
  6330. this._depthCullingState.depthMask = enable;
  6331. };
  6332. Engine.prototype.setColorWrite = function (enable) {
  6333. this._gl.colorMask(enable, enable, enable, enable);
  6334. };
  6335. Engine.prototype.setAlphaMode = function (mode) {
  6336. if (this._alphaMode == mode) {
  6337. return;
  6338. }
  6339. switch (mode) {
  6340. case Engine.ALPHA_DISABLE:
  6341. this.setDepthWrite(true);
  6342. this._alphaState.alphaBlend = false;
  6343. break;
  6344. case Engine.ALPHA_COMBINE:
  6345. this.setDepthWrite(false);
  6346. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6347. this._alphaState.alphaBlend = true;
  6348. break;
  6349. case Engine.ALPHA_ONEONE:
  6350. this.setDepthWrite(false);
  6351. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6352. this._alphaState.alphaBlend = true;
  6353. break;
  6354. case Engine.ALPHA_ADD:
  6355. this.setDepthWrite(false);
  6356. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6357. this._alphaState.alphaBlend = true;
  6358. break;
  6359. case Engine.ALPHA_SUBTRACT:
  6360. this.setDepthWrite(false);
  6361. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6362. this._alphaState.alphaBlend = true;
  6363. break;
  6364. case Engine.ALPHA_MULTIPLY:
  6365. this.setDepthWrite(false);
  6366. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6367. this._alphaState.alphaBlend = true;
  6368. break;
  6369. case Engine.ALPHA_MAXIMIZED:
  6370. this.setDepthWrite(false);
  6371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6372. this._alphaState.alphaBlend = true;
  6373. break;
  6374. }
  6375. this._alphaMode = mode;
  6376. };
  6377. Engine.prototype.getAlphaMode = function () {
  6378. return this._alphaMode;
  6379. };
  6380. Engine.prototype.setAlphaTesting = function (enable) {
  6381. this._alphaTest = enable;
  6382. };
  6383. Engine.prototype.getAlphaTesting = function () {
  6384. return this._alphaTest;
  6385. };
  6386. // Textures
  6387. Engine.prototype.wipeCaches = function () {
  6388. this._activeTexturesCache = [];
  6389. this._currentEffect = null;
  6390. this._depthCullingState.reset();
  6391. this._alphaState.reset();
  6392. this._cachedVertexBuffers = null;
  6393. this._cachedIndexBuffer = null;
  6394. this._cachedEffectForVertexBuffers = null;
  6395. };
  6396. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6397. var gl = this._gl;
  6398. gl.bindTexture(gl.TEXTURE_2D, texture);
  6399. var magFilter = gl.NEAREST;
  6400. var minFilter = gl.NEAREST;
  6401. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6402. magFilter = gl.LINEAR;
  6403. minFilter = gl.LINEAR;
  6404. }
  6405. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6406. magFilter = gl.LINEAR;
  6407. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6408. }
  6409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6411. gl.bindTexture(gl.TEXTURE_2D, null);
  6412. texture.samplingMode = samplingMode;
  6413. };
  6414. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6415. var _this = this;
  6416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6417. if (onLoad === void 0) { onLoad = null; }
  6418. if (onError === void 0) { onError = null; }
  6419. if (buffer === void 0) { buffer = null; }
  6420. var texture = this._gl.createTexture();
  6421. var extension;
  6422. var fromData = false;
  6423. if (url.substr(0, 5) === "data:") {
  6424. fromData = true;
  6425. }
  6426. if (!fromData)
  6427. extension = url.substr(url.length - 4, 4).toLowerCase();
  6428. else {
  6429. var oldUrl = url;
  6430. fromData = oldUrl.split(':');
  6431. url = oldUrl;
  6432. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6433. }
  6434. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6435. var isTGA = (extension === ".tga");
  6436. scene._addPendingData(texture);
  6437. texture.url = url;
  6438. texture.noMipmap = noMipmap;
  6439. texture.references = 1;
  6440. texture.samplingMode = samplingMode;
  6441. this._loadedTexturesCache.push(texture);
  6442. var onerror = function () {
  6443. scene._removePendingData(texture);
  6444. if (onError) {
  6445. onError();
  6446. }
  6447. };
  6448. if (isTGA) {
  6449. var callback = function (arrayBuffer) {
  6450. var data = new Uint8Array(arrayBuffer);
  6451. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6452. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6453. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6454. if (onLoad) {
  6455. onLoad();
  6456. }
  6457. }, samplingMode);
  6458. };
  6459. if (!(fromData instanceof Array))
  6460. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6461. callback(arrayBuffer);
  6462. }, onerror, scene.database, true);
  6463. else
  6464. callback(buffer);
  6465. }
  6466. else if (isDDS) {
  6467. callback = function (data) {
  6468. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6469. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6470. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6471. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6472. if (onLoad) {
  6473. onLoad();
  6474. }
  6475. }, samplingMode);
  6476. };
  6477. if (!(fromData instanceof Array))
  6478. BABYLON.Tools.LoadFile(url, function (data) {
  6479. callback(data);
  6480. }, onerror, scene.database, true);
  6481. else
  6482. callback(buffer);
  6483. }
  6484. else {
  6485. var onload = function (img) {
  6486. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6487. var isPot = (img.width === potWidth && img.height === potHeight);
  6488. if (!isPot) {
  6489. _this._prepareWorkingCanvas();
  6490. _this._workingCanvas.width = potWidth;
  6491. _this._workingCanvas.height = potHeight;
  6492. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6493. _this._workingContext.imageSmoothingEnabled = false;
  6494. _this._workingContext.mozImageSmoothingEnabled = false;
  6495. _this._workingContext.oImageSmoothingEnabled = false;
  6496. _this._workingContext.webkitImageSmoothingEnabled = false;
  6497. _this._workingContext.msImageSmoothingEnabled = false;
  6498. }
  6499. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6500. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6501. _this._workingContext.imageSmoothingEnabled = true;
  6502. _this._workingContext.mozImageSmoothingEnabled = true;
  6503. _this._workingContext.oImageSmoothingEnabled = true;
  6504. _this._workingContext.webkitImageSmoothingEnabled = true;
  6505. _this._workingContext.msImageSmoothingEnabled = true;
  6506. }
  6507. }
  6508. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6509. if (onLoad) {
  6510. onLoad();
  6511. }
  6512. }, samplingMode);
  6513. };
  6514. if (!(fromData instanceof Array))
  6515. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6516. else
  6517. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6518. }
  6519. return texture;
  6520. };
  6521. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6522. if (compression === void 0) { compression = null; }
  6523. var internalFormat = this._gl.RGBA;
  6524. switch (format) {
  6525. case Engine.TEXTUREFORMAT_ALPHA:
  6526. internalFormat = this._gl.ALPHA;
  6527. break;
  6528. case Engine.TEXTUREFORMAT_LUMINANCE:
  6529. internalFormat = this._gl.LUMINANCE;
  6530. break;
  6531. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6532. internalFormat = this._gl.LUMINANCE_ALPHA;
  6533. break;
  6534. case Engine.TEXTUREFORMAT_RGB:
  6535. internalFormat = this._gl.RGB;
  6536. break;
  6537. case Engine.TEXTUREFORMAT_RGBA:
  6538. internalFormat = this._gl.RGBA;
  6539. break;
  6540. }
  6541. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6542. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6543. if (compression) {
  6544. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6545. }
  6546. else {
  6547. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6548. }
  6549. if (texture.generateMipMaps) {
  6550. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6551. }
  6552. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6553. this._activeTexturesCache = [];
  6554. texture.isReady = true;
  6555. };
  6556. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6557. if (compression === void 0) { compression = null; }
  6558. var texture = this._gl.createTexture();
  6559. texture._baseWidth = width;
  6560. texture._baseHeight = height;
  6561. texture._width = width;
  6562. texture._height = height;
  6563. texture.references = 1;
  6564. this.updateRawTexture(texture, data, format, invertY, compression);
  6565. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6566. // Filters
  6567. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6569. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6570. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6571. texture.samplingMode = samplingMode;
  6572. this._loadedTexturesCache.push(texture);
  6573. return texture;
  6574. };
  6575. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6576. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6577. var texture = this._gl.createTexture();
  6578. texture._baseWidth = width;
  6579. texture._baseHeight = height;
  6580. if (forceExponantOfTwo) {
  6581. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6582. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6583. }
  6584. this._activeTexturesCache = [];
  6585. texture._width = width;
  6586. texture._height = height;
  6587. texture.isReady = false;
  6588. texture.generateMipMaps = generateMipMaps;
  6589. texture.references = 1;
  6590. texture.samplingMode = samplingMode;
  6591. this.updateTextureSamplingMode(samplingMode, texture);
  6592. this._loadedTexturesCache.push(texture);
  6593. return texture;
  6594. };
  6595. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6596. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6597. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6600. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6601. };
  6602. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6603. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6604. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6605. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6606. if (texture.generateMipMaps) {
  6607. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6608. }
  6609. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6610. this._activeTexturesCache = [];
  6611. texture.isReady = true;
  6612. };
  6613. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6614. if (texture._isDisabled) {
  6615. return;
  6616. }
  6617. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6618. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6619. try {
  6620. // Testing video texture support
  6621. if (this._videoTextureSupported === undefined) {
  6622. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6623. if (this._gl.getError() !== 0) {
  6624. this._videoTextureSupported = false;
  6625. }
  6626. else {
  6627. this._videoTextureSupported = true;
  6628. }
  6629. }
  6630. // Copy video through the current working canvas if video texture is not supported
  6631. if (!this._videoTextureSupported) {
  6632. if (!texture._workingCanvas) {
  6633. texture._workingCanvas = document.createElement("canvas");
  6634. texture._workingContext = texture._workingCanvas.getContext("2d");
  6635. texture._workingCanvas.width = texture._width;
  6636. texture._workingCanvas.height = texture._height;
  6637. }
  6638. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6639. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6640. }
  6641. else {
  6642. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6643. }
  6644. if (texture.generateMipMaps) {
  6645. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6646. }
  6647. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6648. this._activeTexturesCache = [];
  6649. texture.isReady = true;
  6650. }
  6651. catch (ex) {
  6652. // Something unexpected
  6653. // Let's disable the texture
  6654. texture._isDisabled = true;
  6655. }
  6656. };
  6657. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6658. // old version had a "generateMipMaps" arg instead of options.
  6659. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6660. // in the same way, generateDepthBuffer is defaulted to true
  6661. var generateMipMaps = false;
  6662. var generateDepthBuffer = true;
  6663. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6664. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6665. if (options !== undefined) {
  6666. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6667. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6668. type = options.type === undefined ? type : options.type;
  6669. if (options.samplingMode !== undefined) {
  6670. samplingMode = options.samplingMode;
  6671. }
  6672. if (type === Engine.TEXTURETYPE_FLOAT) {
  6673. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6674. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6675. }
  6676. }
  6677. var gl = this._gl;
  6678. var texture = gl.createTexture();
  6679. gl.bindTexture(gl.TEXTURE_2D, texture);
  6680. var width = size.width || size;
  6681. var height = size.height || size;
  6682. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6683. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6684. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6685. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6686. }
  6687. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6688. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6691. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6692. var depthBuffer;
  6693. // Create the depth buffer
  6694. if (generateDepthBuffer) {
  6695. depthBuffer = gl.createRenderbuffer();
  6696. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6697. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6698. }
  6699. // Create the framebuffer
  6700. var framebuffer = gl.createFramebuffer();
  6701. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6702. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6703. if (generateDepthBuffer) {
  6704. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6705. }
  6706. if (generateMipMaps) {
  6707. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6708. }
  6709. // Unbind
  6710. gl.bindTexture(gl.TEXTURE_2D, null);
  6711. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6712. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6713. texture._framebuffer = framebuffer;
  6714. if (generateDepthBuffer) {
  6715. texture._depthBuffer = depthBuffer;
  6716. }
  6717. texture._width = width;
  6718. texture._height = height;
  6719. texture.isReady = true;
  6720. texture.generateMipMaps = generateMipMaps;
  6721. texture.references = 1;
  6722. texture.samplingMode = samplingMode;
  6723. this._activeTexturesCache = [];
  6724. this._loadedTexturesCache.push(texture);
  6725. return texture;
  6726. };
  6727. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6728. var _this = this;
  6729. var gl = this._gl;
  6730. var texture = gl.createTexture();
  6731. texture.isCube = true;
  6732. texture.url = rootUrl;
  6733. texture.references = 1;
  6734. this._loadedTexturesCache.push(texture);
  6735. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6736. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6737. if (isDDS) {
  6738. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6739. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6740. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6741. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6742. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6743. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6744. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6745. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6746. }
  6747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6751. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6752. _this._activeTexturesCache = [];
  6753. texture._width = info.width;
  6754. texture._height = info.height;
  6755. texture.isReady = true;
  6756. }, null, null, true);
  6757. }
  6758. else {
  6759. cascadeLoad(rootUrl, scene, function (imgs) {
  6760. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6761. var height = width;
  6762. _this._prepareWorkingCanvas();
  6763. _this._workingCanvas.width = width;
  6764. _this._workingCanvas.height = height;
  6765. var faces = [
  6766. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6767. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6768. ];
  6769. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6770. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6771. for (var index = 0; index < faces.length; index++) {
  6772. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6773. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6774. }
  6775. if (!noMipmap) {
  6776. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6777. }
  6778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6782. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6783. _this._activeTexturesCache = [];
  6784. texture._width = width;
  6785. texture._height = height;
  6786. texture.isReady = true;
  6787. }, extensions);
  6788. }
  6789. return texture;
  6790. };
  6791. Engine.prototype._releaseTexture = function (texture) {
  6792. var gl = this._gl;
  6793. if (texture._framebuffer) {
  6794. gl.deleteFramebuffer(texture._framebuffer);
  6795. }
  6796. if (texture._depthBuffer) {
  6797. gl.deleteRenderbuffer(texture._depthBuffer);
  6798. }
  6799. gl.deleteTexture(texture);
  6800. // Unbind channels
  6801. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6802. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6803. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6804. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6805. this._activeTexturesCache[channel] = null;
  6806. }
  6807. var index = this._loadedTexturesCache.indexOf(texture);
  6808. if (index !== -1) {
  6809. this._loadedTexturesCache.splice(index, 1);
  6810. }
  6811. };
  6812. Engine.prototype.bindSamplers = function (effect) {
  6813. this._gl.useProgram(effect.getProgram());
  6814. var samplers = effect.getSamplers();
  6815. for (var index = 0; index < samplers.length; index++) {
  6816. var uniform = effect.getUniform(samplers[index]);
  6817. this._gl.uniform1i(uniform, index);
  6818. }
  6819. this._currentEffect = null;
  6820. };
  6821. Engine.prototype._bindTexture = function (channel, texture) {
  6822. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6823. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6824. this._activeTexturesCache[channel] = null;
  6825. };
  6826. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6827. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6828. };
  6829. Engine.prototype.setTexture = function (channel, texture) {
  6830. if (channel < 0) {
  6831. return;
  6832. }
  6833. // Not ready?
  6834. if (!texture || !texture.isReady()) {
  6835. if (this._activeTexturesCache[channel] != null) {
  6836. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6837. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6838. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6839. this._activeTexturesCache[channel] = null;
  6840. }
  6841. return;
  6842. }
  6843. // Video
  6844. if (texture instanceof BABYLON.VideoTexture) {
  6845. if (texture.update()) {
  6846. this._activeTexturesCache[channel] = null;
  6847. }
  6848. }
  6849. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6850. texture.delayLoad();
  6851. return;
  6852. }
  6853. if (this._activeTexturesCache[channel] === texture) {
  6854. return;
  6855. }
  6856. this._activeTexturesCache[channel] = texture;
  6857. var internalTexture = texture.getInternalTexture();
  6858. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6859. if (internalTexture.isCube) {
  6860. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6861. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6862. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6863. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6864. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6865. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6866. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6867. }
  6868. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6869. }
  6870. else {
  6871. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6872. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6873. internalTexture._cachedWrapU = texture.wrapU;
  6874. switch (texture.wrapU) {
  6875. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6876. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6877. break;
  6878. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6879. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6880. break;
  6881. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6882. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6883. break;
  6884. }
  6885. }
  6886. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6887. internalTexture._cachedWrapV = texture.wrapV;
  6888. switch (texture.wrapV) {
  6889. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6890. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6891. break;
  6892. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6893. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6894. break;
  6895. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6897. break;
  6898. }
  6899. }
  6900. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6901. }
  6902. };
  6903. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6904. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6905. var value = texture.anisotropicFilteringLevel;
  6906. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6907. value = 1;
  6908. }
  6909. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6910. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6911. texture._cachedAnisotropicFilteringLevel = value;
  6912. }
  6913. };
  6914. Engine.prototype.readPixels = function (x, y, width, height) {
  6915. var data = new Uint8Array(height * width * 4);
  6916. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6917. return data;
  6918. };
  6919. // Dispose
  6920. Engine.prototype.dispose = function () {
  6921. this.hideLoadingUI();
  6922. this.stopRenderLoop();
  6923. // Release scenes
  6924. while (this.scenes.length) {
  6925. this.scenes[0].dispose();
  6926. }
  6927. // Release audio engine
  6928. Engine.audioEngine.dispose();
  6929. // Release effects
  6930. for (var name in this._compiledEffects) {
  6931. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6932. }
  6933. // Unbind
  6934. for (var i in this._vertexAttribArrays) {
  6935. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6936. continue;
  6937. }
  6938. this._gl.disableVertexAttribArray(i);
  6939. }
  6940. this._gl = null;
  6941. // Events
  6942. window.removeEventListener("blur", this._onBlur);
  6943. window.removeEventListener("focus", this._onFocus);
  6944. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6945. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6946. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6947. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6948. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6949. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6950. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6951. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6952. };
  6953. // Loading screen
  6954. Engine.prototype.displayLoadingUI = function () {
  6955. this._loadingScreen.displayLoadingUI();
  6956. };
  6957. Engine.prototype.hideLoadingUI = function () {
  6958. this._loadingScreen.hideLoadingUI();
  6959. };
  6960. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6961. get: function () {
  6962. return this._loadingScreen;
  6963. },
  6964. set: function (loadingScreen) {
  6965. this._loadingScreen = loadingScreen;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6971. set: function (text) {
  6972. this._loadingScreen.loadingUIText = text;
  6973. },
  6974. enumerable: true,
  6975. configurable: true
  6976. });
  6977. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6978. set: function (color) {
  6979. this._loadingScreen.loadingUIBackgroundColor = color;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. // FPS
  6985. Engine.prototype.getFps = function () {
  6986. return this.fps;
  6987. };
  6988. Engine.prototype.getDeltaTime = function () {
  6989. return this.deltaTime;
  6990. };
  6991. Engine.prototype._measureFps = function () {
  6992. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6993. var length = this.previousFramesDuration.length;
  6994. if (length >= 2) {
  6995. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6996. }
  6997. if (length >= this.fpsRange) {
  6998. if (length > this.fpsRange) {
  6999. this.previousFramesDuration.splice(0, 1);
  7000. length = this.previousFramesDuration.length;
  7001. }
  7002. var sum = 0;
  7003. for (var id = 0; id < length - 1; id++) {
  7004. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7005. }
  7006. this.fps = 1000.0 / (sum / (length - 1));
  7007. }
  7008. };
  7009. // Statics
  7010. Engine.isSupported = function () {
  7011. try {
  7012. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7013. if (navigator.isCocoonJS) {
  7014. return true;
  7015. }
  7016. var tempcanvas = document.createElement("canvas");
  7017. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7018. return gl != null && !!window.WebGLRenderingContext;
  7019. }
  7020. catch (e) {
  7021. return false;
  7022. }
  7023. };
  7024. // Const statics
  7025. Engine._ALPHA_DISABLE = 0;
  7026. Engine._ALPHA_ADD = 1;
  7027. Engine._ALPHA_COMBINE = 2;
  7028. Engine._ALPHA_SUBTRACT = 3;
  7029. Engine._ALPHA_MULTIPLY = 4;
  7030. Engine._ALPHA_MAXIMIZED = 5;
  7031. Engine._ALPHA_ONEONE = 6;
  7032. Engine._DELAYLOADSTATE_NONE = 0;
  7033. Engine._DELAYLOADSTATE_LOADED = 1;
  7034. Engine._DELAYLOADSTATE_LOADING = 2;
  7035. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7036. Engine._TEXTUREFORMAT_ALPHA = 0;
  7037. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7038. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7039. Engine._TEXTUREFORMAT_RGB = 4;
  7040. Engine._TEXTUREFORMAT_RGBA = 5;
  7041. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7042. Engine._TEXTURETYPE_FLOAT = 1;
  7043. // Updatable statics so stick with vars here
  7044. Engine.Epsilon = 0.001;
  7045. Engine.CollisionsEpsilon = 0.001;
  7046. Engine.CodeRepository = "src/";
  7047. Engine.ShadersRepository = "src/Shaders/";
  7048. return Engine;
  7049. })();
  7050. BABYLON.Engine = Engine;
  7051. })(BABYLON || (BABYLON = {}));
  7052. var BABYLON;
  7053. (function (BABYLON) {
  7054. /**
  7055. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7056. */
  7057. var Node = (function () {
  7058. /**
  7059. * @constructor
  7060. * @param {string} name - the name and id to be given to this node
  7061. * @param {BABYLON.Scene} the scene this node will be added to
  7062. */
  7063. function Node(name, scene) {
  7064. this.state = "";
  7065. this.animations = new Array();
  7066. this._childrenFlag = -1;
  7067. this._isEnabled = true;
  7068. this._isReady = true;
  7069. this._currentRenderId = -1;
  7070. this._parentRenderId = -1;
  7071. this.name = name;
  7072. this.id = name;
  7073. this._scene = scene;
  7074. this._initCache();
  7075. }
  7076. Node.prototype.getScene = function () {
  7077. return this._scene;
  7078. };
  7079. Node.prototype.getEngine = function () {
  7080. return this._scene.getEngine();
  7081. };
  7082. // override it in derived class
  7083. Node.prototype.getWorldMatrix = function () {
  7084. return BABYLON.Matrix.Identity();
  7085. };
  7086. // override it in derived class if you add new variables to the cache
  7087. // and call the parent class method
  7088. Node.prototype._initCache = function () {
  7089. this._cache = {};
  7090. this._cache.parent = undefined;
  7091. };
  7092. Node.prototype.updateCache = function (force) {
  7093. if (!force && this.isSynchronized())
  7094. return;
  7095. this._cache.parent = this.parent;
  7096. this._updateCache();
  7097. };
  7098. // override it in derived class if you add new variables to the cache
  7099. // and call the parent class method if !ignoreParentClass
  7100. Node.prototype._updateCache = function (ignoreParentClass) {
  7101. };
  7102. // override it in derived class if you add new variables to the cache
  7103. Node.prototype._isSynchronized = function () {
  7104. return true;
  7105. };
  7106. Node.prototype._markSyncedWithParent = function () {
  7107. this._parentRenderId = this.parent._currentRenderId;
  7108. };
  7109. Node.prototype.isSynchronizedWithParent = function () {
  7110. if (!this.parent) {
  7111. return true;
  7112. }
  7113. if (this._parentRenderId !== this.parent._currentRenderId) {
  7114. return false;
  7115. }
  7116. return this.parent.isSynchronized();
  7117. };
  7118. Node.prototype.isSynchronized = function (updateCache) {
  7119. var check = this.hasNewParent();
  7120. check = check || !this.isSynchronizedWithParent();
  7121. check = check || !this._isSynchronized();
  7122. if (updateCache)
  7123. this.updateCache(true);
  7124. return !check;
  7125. };
  7126. Node.prototype.hasNewParent = function (update) {
  7127. if (this._cache.parent === this.parent)
  7128. return false;
  7129. if (update)
  7130. this._cache.parent = this.parent;
  7131. return true;
  7132. };
  7133. /**
  7134. * Is this node ready to be used/rendered
  7135. * @return {boolean} is it ready
  7136. */
  7137. Node.prototype.isReady = function () {
  7138. return this._isReady;
  7139. };
  7140. /**
  7141. * Is this node enabled.
  7142. * If the node has a parent and is enabled, the parent will be inspected as well.
  7143. * @return {boolean} whether this node (and its parent) is enabled.
  7144. * @see setEnabled
  7145. */
  7146. Node.prototype.isEnabled = function () {
  7147. if (!this._isEnabled) {
  7148. return false;
  7149. }
  7150. if (this.parent) {
  7151. return this.parent.isEnabled();
  7152. }
  7153. return true;
  7154. };
  7155. /**
  7156. * Set the enabled state of this node.
  7157. * @param {boolean} value - the new enabled state
  7158. * @see isEnabled
  7159. */
  7160. Node.prototype.setEnabled = function (value) {
  7161. this._isEnabled = value;
  7162. };
  7163. /**
  7164. * Is this node a descendant of the given node.
  7165. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7166. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7167. * @see parent
  7168. */
  7169. Node.prototype.isDescendantOf = function (ancestor) {
  7170. if (this.parent) {
  7171. if (this.parent === ancestor) {
  7172. return true;
  7173. }
  7174. return this.parent.isDescendantOf(ancestor);
  7175. }
  7176. return false;
  7177. };
  7178. Node.prototype._getDescendants = function (list, results) {
  7179. for (var index = 0; index < list.length; index++) {
  7180. var item = list[index];
  7181. if (item.isDescendantOf(this)) {
  7182. results.push(item);
  7183. }
  7184. }
  7185. };
  7186. /**
  7187. * Will return all nodes that have this node as parent.
  7188. * @return {BABYLON.Node[]} all children nodes of all types.
  7189. */
  7190. Node.prototype.getDescendants = function () {
  7191. var results = [];
  7192. this._getDescendants(this._scene.meshes, results);
  7193. this._getDescendants(this._scene.lights, results);
  7194. this._getDescendants(this._scene.cameras, results);
  7195. return results;
  7196. };
  7197. Node.prototype._setReady = function (state) {
  7198. if (state == this._isReady) {
  7199. return;
  7200. }
  7201. if (!state) {
  7202. this._isReady = false;
  7203. return;
  7204. }
  7205. this._isReady = true;
  7206. if (this.onReady) {
  7207. this.onReady(this);
  7208. }
  7209. };
  7210. return Node;
  7211. })();
  7212. BABYLON.Node = Node;
  7213. })(BABYLON || (BABYLON = {}));
  7214. var BABYLON;
  7215. (function (BABYLON) {
  7216. var FilesInput = (function () {
  7217. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7218. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7219. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7220. this._engine = p_engine;
  7221. this._canvas = p_canvas;
  7222. this._currentScene = p_scene;
  7223. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7224. this._progressCallback = p_progressCallback;
  7225. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7226. this._textureLoadingCallback = p_textureLoadingCallback;
  7227. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7228. }
  7229. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7230. var _this = this;
  7231. if (p_elementToMonitor) {
  7232. this._elementToMonitor = p_elementToMonitor;
  7233. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7234. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7235. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7236. }
  7237. };
  7238. FilesInput.prototype.renderFunction = function () {
  7239. if (this._additionnalRenderLoopLogicCallback) {
  7240. this._additionnalRenderLoopLogicCallback();
  7241. }
  7242. if (this._currentScene) {
  7243. if (this._textureLoadingCallback) {
  7244. var remaining = this._currentScene.getWaitingItemsCount();
  7245. if (remaining > 0) {
  7246. this._textureLoadingCallback(remaining);
  7247. }
  7248. }
  7249. this._currentScene.render();
  7250. }
  7251. };
  7252. FilesInput.prototype.drag = function (e) {
  7253. e.stopPropagation();
  7254. e.preventDefault();
  7255. };
  7256. FilesInput.prototype.drop = function (eventDrop) {
  7257. eventDrop.stopPropagation();
  7258. eventDrop.preventDefault();
  7259. this.loadFiles(eventDrop);
  7260. };
  7261. FilesInput.prototype.loadFiles = function (event) {
  7262. if (this._startingProcessingFilesCallback)
  7263. this._startingProcessingFilesCallback();
  7264. // Handling data transfer via drag'n'drop
  7265. if (event && event.dataTransfer && event.dataTransfer.files) {
  7266. this._filesToLoad = event.dataTransfer.files;
  7267. }
  7268. // Handling files from input files
  7269. if (event && event.target && event.target.files) {
  7270. this._filesToLoad = event.target.files;
  7271. }
  7272. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7273. for (var i = 0; i < this._filesToLoad.length; i++) {
  7274. switch (this._filesToLoad[i].type) {
  7275. case "image/jpeg":
  7276. case "image/png":
  7277. case "image/bmp":
  7278. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7279. break;
  7280. case "image/targa":
  7281. case "image/vnd.ms-dds":
  7282. case "audio/wav":
  7283. case "audio/x-wav":
  7284. case "audio/mp3":
  7285. case "audio/mpeg":
  7286. case "audio/mpeg3":
  7287. case "audio/x-mpeg-3":
  7288. case "audio/ogg":
  7289. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7290. break;
  7291. default:
  7292. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7293. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7294. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7295. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7296. this._sceneFileToLoad = this._filesToLoad[i];
  7297. }
  7298. break;
  7299. }
  7300. }
  7301. this.reload();
  7302. }
  7303. };
  7304. FilesInput.prototype.reload = function () {
  7305. var _this = this;
  7306. var that = this;
  7307. // If a ".babylon" file has been provided
  7308. if (this._sceneFileToLoad) {
  7309. if (this._currentScene) {
  7310. if (BABYLON.Tools.errorsCount > 0) {
  7311. BABYLON.Tools.ClearLogCache();
  7312. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7313. }
  7314. this._engine.stopRenderLoop();
  7315. this._currentScene.dispose();
  7316. }
  7317. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7318. that._currentScene = newScene;
  7319. // Wait for textures and shaders to be ready
  7320. that._currentScene.executeWhenReady(function () {
  7321. // Attach camera to canvas inputs
  7322. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7323. that._currentScene.createDefaultCameraOrLight();
  7324. }
  7325. that._currentScene.activeCamera.attachControl(that._canvas);
  7326. if (that._sceneLoadedCallback) {
  7327. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7328. }
  7329. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7330. });
  7331. }, function (progress) {
  7332. if (_this._progressCallback) {
  7333. _this._progressCallback(progress);
  7334. }
  7335. });
  7336. }
  7337. else {
  7338. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7339. }
  7340. };
  7341. FilesInput.FilesTextures = new Array();
  7342. FilesInput.FilesToLoad = new Array();
  7343. return FilesInput;
  7344. })();
  7345. BABYLON.FilesInput = FilesInput;
  7346. })(BABYLON || (BABYLON = {}));
  7347. var BABYLON;
  7348. (function (BABYLON) {
  7349. var IntersectionInfo = (function () {
  7350. function IntersectionInfo(bu, bv, distance) {
  7351. this.bu = bu;
  7352. this.bv = bv;
  7353. this.distance = distance;
  7354. this.faceId = 0;
  7355. this.subMeshId = 0;
  7356. }
  7357. return IntersectionInfo;
  7358. })();
  7359. BABYLON.IntersectionInfo = IntersectionInfo;
  7360. var PickingInfo = (function () {
  7361. function PickingInfo() {
  7362. this.hit = false;
  7363. this.distance = 0;
  7364. this.pickedPoint = null;
  7365. this.pickedMesh = null;
  7366. this.bu = 0;
  7367. this.bv = 0;
  7368. this.faceId = -1;
  7369. this.subMeshId = 0;
  7370. }
  7371. // Methods
  7372. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7373. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7374. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7375. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7376. return null;
  7377. }
  7378. var indices = this.pickedMesh.getIndices();
  7379. var result;
  7380. if (useVerticesNormals) {
  7381. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7382. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7383. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7384. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7385. normal0 = normal0.scale(this.bu);
  7386. normal1 = normal1.scale(this.bv);
  7387. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7388. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7389. }
  7390. else {
  7391. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7392. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7393. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7394. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7395. var p1p2 = vertex1.subtract(vertex2);
  7396. var p3p2 = vertex3.subtract(vertex2);
  7397. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7398. }
  7399. if (useWorldCoordinates) {
  7400. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7401. }
  7402. return BABYLON.Vector3.Normalize(result);
  7403. };
  7404. PickingInfo.prototype.getTextureCoordinates = function () {
  7405. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7406. return null;
  7407. }
  7408. var indices = this.pickedMesh.getIndices();
  7409. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7410. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7411. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7412. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7413. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7414. uv1 = uv1.scale(this.bu);
  7415. uv2 = uv2.scale(this.bv);
  7416. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7417. };
  7418. return PickingInfo;
  7419. })();
  7420. BABYLON.PickingInfo = PickingInfo;
  7421. })(BABYLON || (BABYLON = {}));
  7422. var BABYLON;
  7423. (function (BABYLON) {
  7424. var BoundingSphere = (function () {
  7425. function BoundingSphere(minimum, maximum) {
  7426. this.minimum = minimum;
  7427. this.maximum = maximum;
  7428. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7429. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7430. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7431. this.radius = distance * 0.5;
  7432. this.centerWorld = BABYLON.Vector3.Zero();
  7433. this._update(BABYLON.Matrix.Identity());
  7434. }
  7435. // Methods
  7436. BoundingSphere.prototype._update = function (world) {
  7437. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7438. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7439. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7440. };
  7441. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7442. for (var i = 0; i < 6; i++) {
  7443. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7444. return false;
  7445. }
  7446. return true;
  7447. };
  7448. BoundingSphere.prototype.intersectsPoint = function (point) {
  7449. var x = this.centerWorld.x - point.x;
  7450. var y = this.centerWorld.y - point.y;
  7451. var z = this.centerWorld.z - point.z;
  7452. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7453. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7454. return false;
  7455. return true;
  7456. };
  7457. // Statics
  7458. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7459. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7460. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7461. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7462. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7463. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7464. return false;
  7465. return true;
  7466. };
  7467. return BoundingSphere;
  7468. })();
  7469. BABYLON.BoundingSphere = BoundingSphere;
  7470. })(BABYLON || (BABYLON = {}));
  7471. var BABYLON;
  7472. (function (BABYLON) {
  7473. var BoundingBox = (function () {
  7474. function BoundingBox(minimum, maximum) {
  7475. this.minimum = minimum;
  7476. this.maximum = maximum;
  7477. this.vectors = new Array();
  7478. this.vectorsWorld = new Array();
  7479. // Bounding vectors
  7480. this.vectors.push(this.minimum.clone());
  7481. this.vectors.push(this.maximum.clone());
  7482. this.vectors.push(this.minimum.clone());
  7483. this.vectors[2].x = this.maximum.x;
  7484. this.vectors.push(this.minimum.clone());
  7485. this.vectors[3].y = this.maximum.y;
  7486. this.vectors.push(this.minimum.clone());
  7487. this.vectors[4].z = this.maximum.z;
  7488. this.vectors.push(this.maximum.clone());
  7489. this.vectors[5].z = this.minimum.z;
  7490. this.vectors.push(this.maximum.clone());
  7491. this.vectors[6].x = this.minimum.x;
  7492. this.vectors.push(this.maximum.clone());
  7493. this.vectors[7].y = this.minimum.y;
  7494. // OBB
  7495. this.center = this.maximum.add(this.minimum).scale(0.5);
  7496. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7497. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7498. // World
  7499. for (var index = 0; index < this.vectors.length; index++) {
  7500. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7501. }
  7502. this.minimumWorld = BABYLON.Vector3.Zero();
  7503. this.maximumWorld = BABYLON.Vector3.Zero();
  7504. this._update(BABYLON.Matrix.Identity());
  7505. }
  7506. // Methods
  7507. BoundingBox.prototype.getWorldMatrix = function () {
  7508. return this._worldMatrix;
  7509. };
  7510. BoundingBox.prototype._update = function (world) {
  7511. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7512. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7513. for (var index = 0; index < this.vectors.length; index++) {
  7514. var v = this.vectorsWorld[index];
  7515. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7516. if (v.x < this.minimumWorld.x)
  7517. this.minimumWorld.x = v.x;
  7518. if (v.y < this.minimumWorld.y)
  7519. this.minimumWorld.y = v.y;
  7520. if (v.z < this.minimumWorld.z)
  7521. this.minimumWorld.z = v.z;
  7522. if (v.x > this.maximumWorld.x)
  7523. this.maximumWorld.x = v.x;
  7524. if (v.y > this.maximumWorld.y)
  7525. this.maximumWorld.y = v.y;
  7526. if (v.z > this.maximumWorld.z)
  7527. this.maximumWorld.z = v.z;
  7528. }
  7529. // OBB
  7530. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7531. this.center.scaleInPlace(0.5);
  7532. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7533. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7534. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7535. this._worldMatrix = world;
  7536. };
  7537. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7538. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7539. };
  7540. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7541. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7542. };
  7543. BoundingBox.prototype.intersectsPoint = function (point) {
  7544. var delta = -BABYLON.Engine.Epsilon;
  7545. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7546. return false;
  7547. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7548. return false;
  7549. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7550. return false;
  7551. return true;
  7552. };
  7553. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7554. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7555. };
  7556. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7557. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7558. return false;
  7559. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7560. return false;
  7561. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7562. return false;
  7563. return true;
  7564. };
  7565. // Statics
  7566. BoundingBox.Intersects = function (box0, box1) {
  7567. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7568. return false;
  7569. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7570. return false;
  7571. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7572. return false;
  7573. return true;
  7574. };
  7575. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7576. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7577. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7578. return (num <= (sphereRadius * sphereRadius));
  7579. };
  7580. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7581. for (var p = 0; p < 6; p++) {
  7582. for (var i = 0; i < 8; i++) {
  7583. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7584. return false;
  7585. }
  7586. }
  7587. }
  7588. return true;
  7589. };
  7590. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7591. for (var p = 0; p < 6; p++) {
  7592. var inCount = 8;
  7593. for (var i = 0; i < 8; i++) {
  7594. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7595. --inCount;
  7596. }
  7597. else {
  7598. break;
  7599. }
  7600. }
  7601. if (inCount === 0)
  7602. return false;
  7603. }
  7604. return true;
  7605. };
  7606. return BoundingBox;
  7607. })();
  7608. BABYLON.BoundingBox = BoundingBox;
  7609. })(BABYLON || (BABYLON = {}));
  7610. var BABYLON;
  7611. (function (BABYLON) {
  7612. var computeBoxExtents = function (axis, box) {
  7613. var p = BABYLON.Vector3.Dot(box.center, axis);
  7614. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7615. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7616. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7617. var r = r0 + r1 + r2;
  7618. return {
  7619. min: p - r,
  7620. max: p + r
  7621. };
  7622. };
  7623. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7624. var axisOverlap = function (axis, box0, box1) {
  7625. var result0 = computeBoxExtents(axis, box0);
  7626. var result1 = computeBoxExtents(axis, box1);
  7627. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7628. };
  7629. var BoundingInfo = (function () {
  7630. function BoundingInfo(minimum, maximum) {
  7631. this.minimum = minimum;
  7632. this.maximum = maximum;
  7633. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7634. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7635. }
  7636. // Methods
  7637. BoundingInfo.prototype._update = function (world) {
  7638. this.boundingBox._update(world);
  7639. this.boundingSphere._update(world);
  7640. };
  7641. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7642. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7643. return false;
  7644. return this.boundingBox.isInFrustum(frustumPlanes);
  7645. };
  7646. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7647. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7648. };
  7649. BoundingInfo.prototype._checkCollision = function (collider) {
  7650. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7651. };
  7652. BoundingInfo.prototype.intersectsPoint = function (point) {
  7653. if (!this.boundingSphere.centerWorld) {
  7654. return false;
  7655. }
  7656. if (!this.boundingSphere.intersectsPoint(point)) {
  7657. return false;
  7658. }
  7659. if (!this.boundingBox.intersectsPoint(point)) {
  7660. return false;
  7661. }
  7662. return true;
  7663. };
  7664. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7665. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7666. return false;
  7667. }
  7668. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7669. return false;
  7670. }
  7671. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7672. return false;
  7673. }
  7674. if (!precise) {
  7675. return true;
  7676. }
  7677. var box0 = this.boundingBox;
  7678. var box1 = boundingInfo.boundingBox;
  7679. if (!axisOverlap(box0.directions[0], box0, box1))
  7680. return false;
  7681. if (!axisOverlap(box0.directions[1], box0, box1))
  7682. return false;
  7683. if (!axisOverlap(box0.directions[2], box0, box1))
  7684. return false;
  7685. if (!axisOverlap(box1.directions[0], box0, box1))
  7686. return false;
  7687. if (!axisOverlap(box1.directions[1], box0, box1))
  7688. return false;
  7689. if (!axisOverlap(box1.directions[2], box0, box1))
  7690. return false;
  7691. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7692. return false;
  7693. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7694. return false;
  7695. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7696. return false;
  7697. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7698. return false;
  7699. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7700. return false;
  7701. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7702. return false;
  7703. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7704. return false;
  7705. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7706. return false;
  7707. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7708. return false;
  7709. return true;
  7710. };
  7711. return BoundingInfo;
  7712. })();
  7713. BABYLON.BoundingInfo = BoundingInfo;
  7714. })(BABYLON || (BABYLON = {}));
  7715. var BABYLON;
  7716. (function (BABYLON) {
  7717. var AbstractMesh = (function (_super) {
  7718. __extends(AbstractMesh, _super);
  7719. function AbstractMesh(name, scene) {
  7720. var _this = this;
  7721. _super.call(this, name, scene);
  7722. // Properties
  7723. this.definedFacingForward = true; // orientation for POV movement & rotation
  7724. this.position = new BABYLON.Vector3(0, 0, 0);
  7725. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7726. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7727. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7728. this.visibility = 1.0;
  7729. this.alphaIndex = Number.MAX_VALUE;
  7730. this.infiniteDistance = false;
  7731. this.isVisible = true;
  7732. this.isPickable = true;
  7733. this.showBoundingBox = false;
  7734. this.showSubMeshesBoundingBox = false;
  7735. this.onDispose = null;
  7736. this.isBlocker = false;
  7737. this.renderingGroupId = 0;
  7738. this.receiveShadows = false;
  7739. this.renderOutline = false;
  7740. this.outlineColor = BABYLON.Color3.Red();
  7741. this.outlineWidth = 0.02;
  7742. this.renderOverlay = false;
  7743. this.overlayColor = BABYLON.Color3.Red();
  7744. this.overlayAlpha = 0.5;
  7745. this.hasVertexAlpha = false;
  7746. this.useVertexColors = true;
  7747. this.applyFog = true;
  7748. this.computeBonesUsingShaders = true;
  7749. this.scalingDeterminant = 1;
  7750. this.useOctreeForRenderingSelection = true;
  7751. this.useOctreeForPicking = true;
  7752. this.useOctreeForCollisions = true;
  7753. this.layerMask = 0x0FFFFFFF;
  7754. this.alwaysSelectAsActiveMesh = false;
  7755. // Physics
  7756. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7757. // Collisions
  7758. this._checkCollisions = false;
  7759. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7760. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7761. this._collider = new BABYLON.Collider();
  7762. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7763. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7764. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7765. // Edges
  7766. this.edgesWidth = 1;
  7767. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7768. // Cache
  7769. this._localScaling = BABYLON.Matrix.Zero();
  7770. this._localRotation = BABYLON.Matrix.Zero();
  7771. this._localTranslation = BABYLON.Matrix.Zero();
  7772. this._localBillboard = BABYLON.Matrix.Zero();
  7773. this._localPivotScaling = BABYLON.Matrix.Zero();
  7774. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7775. this._localWorld = BABYLON.Matrix.Zero();
  7776. this._worldMatrix = BABYLON.Matrix.Zero();
  7777. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7778. this._absolutePosition = BABYLON.Vector3.Zero();
  7779. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7780. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7781. this._isDirty = false;
  7782. this._pivotMatrix = BABYLON.Matrix.Identity();
  7783. this._isDisposed = false;
  7784. this._renderId = 0;
  7785. this._intersectionsInProgress = new Array();
  7786. this._onAfterWorldMatrixUpdate = new Array();
  7787. this._isWorldMatrixFrozen = false;
  7788. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7789. if (collidedMesh === void 0) { collidedMesh = null; }
  7790. //TODO move this to the collision coordinator!
  7791. if (_this.getScene().workerCollisions)
  7792. newPosition.multiplyInPlace(_this._collider.radius);
  7793. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7794. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7795. _this.position.addInPlace(_this._diffPositionForCollisions);
  7796. }
  7797. if (_this.onCollide && collidedMesh) {
  7798. _this.onCollide(collidedMesh);
  7799. }
  7800. };
  7801. scene.addMesh(this);
  7802. }
  7803. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7804. get: function () {
  7805. return AbstractMesh._BILLBOARDMODE_NONE;
  7806. },
  7807. enumerable: true,
  7808. configurable: true
  7809. });
  7810. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7811. get: function () {
  7812. return AbstractMesh._BILLBOARDMODE_X;
  7813. },
  7814. enumerable: true,
  7815. configurable: true
  7816. });
  7817. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7818. get: function () {
  7819. return AbstractMesh._BILLBOARDMODE_Y;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7825. get: function () {
  7826. return AbstractMesh._BILLBOARDMODE_Z;
  7827. },
  7828. enumerable: true,
  7829. configurable: true
  7830. });
  7831. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7832. get: function () {
  7833. return AbstractMesh._BILLBOARDMODE_ALL;
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. // Methods
  7839. AbstractMesh.prototype.disableEdgesRendering = function () {
  7840. if (this._edgesRenderer !== undefined) {
  7841. this._edgesRenderer.dispose();
  7842. this._edgesRenderer = undefined;
  7843. }
  7844. };
  7845. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7846. if (epsilon === void 0) { epsilon = 0.95; }
  7847. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7848. this.disableEdgesRendering();
  7849. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7850. };
  7851. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7852. get: function () {
  7853. return false;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. AbstractMesh.prototype.getLOD = function (camera) {
  7859. return this;
  7860. };
  7861. AbstractMesh.prototype.getTotalVertices = function () {
  7862. return 0;
  7863. };
  7864. AbstractMesh.prototype.getIndices = function () {
  7865. return null;
  7866. };
  7867. AbstractMesh.prototype.getVerticesData = function (kind) {
  7868. return null;
  7869. };
  7870. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7871. return false;
  7872. };
  7873. AbstractMesh.prototype.getBoundingInfo = function () {
  7874. if (this._masterMesh) {
  7875. return this._masterMesh.getBoundingInfo();
  7876. }
  7877. if (!this._boundingInfo) {
  7878. this._updateBoundingInfo();
  7879. }
  7880. return this._boundingInfo;
  7881. };
  7882. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7883. get: function () {
  7884. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7885. },
  7886. enumerable: true,
  7887. configurable: true
  7888. });
  7889. AbstractMesh.prototype._preActivate = function () {
  7890. };
  7891. AbstractMesh.prototype._activate = function (renderId) {
  7892. this._renderId = renderId;
  7893. };
  7894. AbstractMesh.prototype.getWorldMatrix = function () {
  7895. if (this._masterMesh) {
  7896. return this._masterMesh.getWorldMatrix();
  7897. }
  7898. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7899. this.computeWorldMatrix();
  7900. }
  7901. return this._worldMatrix;
  7902. };
  7903. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7904. get: function () {
  7905. return this._worldMatrix;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7911. get: function () {
  7912. return this._absolutePosition;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7918. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7919. this.computeWorldMatrix(true);
  7920. this._isWorldMatrixFrozen = true;
  7921. };
  7922. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7923. this._isWorldMatrixFrozen = false;
  7924. this.computeWorldMatrix(true);
  7925. };
  7926. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7927. get: function () {
  7928. return this._isWorldMatrixFrozen;
  7929. },
  7930. enumerable: true,
  7931. configurable: true
  7932. });
  7933. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7934. axis.normalize();
  7935. if (!this.rotationQuaternion) {
  7936. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7937. this.rotation = BABYLON.Vector3.Zero();
  7938. }
  7939. var rotationQuaternion;
  7940. if (!space || space === BABYLON.Space.LOCAL) {
  7941. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7942. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7943. }
  7944. else {
  7945. if (this.parent) {
  7946. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7947. invertParentWorldMatrix.invert();
  7948. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7949. }
  7950. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7951. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7952. }
  7953. };
  7954. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7955. var displacementVector = axis.scale(distance);
  7956. if (!space || space === BABYLON.Space.LOCAL) {
  7957. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7958. this.setPositionWithLocalVector(tempV3);
  7959. }
  7960. else {
  7961. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7962. }
  7963. };
  7964. AbstractMesh.prototype.getAbsolutePosition = function () {
  7965. this.computeWorldMatrix();
  7966. return this._absolutePosition;
  7967. };
  7968. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7969. if (!absolutePosition) {
  7970. return;
  7971. }
  7972. var absolutePositionX;
  7973. var absolutePositionY;
  7974. var absolutePositionZ;
  7975. if (absolutePosition.x === undefined) {
  7976. if (arguments.length < 3) {
  7977. return;
  7978. }
  7979. absolutePositionX = arguments[0];
  7980. absolutePositionY = arguments[1];
  7981. absolutePositionZ = arguments[2];
  7982. }
  7983. else {
  7984. absolutePositionX = absolutePosition.x;
  7985. absolutePositionY = absolutePosition.y;
  7986. absolutePositionZ = absolutePosition.z;
  7987. }
  7988. if (this.parent) {
  7989. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7990. invertParentWorldMatrix.invert();
  7991. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7992. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7993. }
  7994. else {
  7995. this.position.x = absolutePositionX;
  7996. this.position.y = absolutePositionY;
  7997. this.position.z = absolutePositionZ;
  7998. }
  7999. };
  8000. // ================================== Point of View Movement =================================
  8001. /**
  8002. * Perform relative position change from the point of view of behind the front of the mesh.
  8003. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8004. * Supports definition of mesh facing forward or backward.
  8005. * @param {number} amountRight
  8006. * @param {number} amountUp
  8007. * @param {number} amountForward
  8008. */
  8009. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8010. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8011. };
  8012. /**
  8013. * Calculate relative position change from the point of view of behind the front of the mesh.
  8014. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8015. * Supports definition of mesh facing forward or backward.
  8016. * @param {number} amountRight
  8017. * @param {number} amountUp
  8018. * @param {number} amountForward
  8019. */
  8020. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8021. var rotMatrix = new BABYLON.Matrix();
  8022. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8023. rotQuaternion.toRotationMatrix(rotMatrix);
  8024. var translationDelta = BABYLON.Vector3.Zero();
  8025. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8027. return translationDelta;
  8028. };
  8029. // ================================== Point of View Rotation =================================
  8030. /**
  8031. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8032. * Supports definition of mesh facing forward or backward.
  8033. * @param {number} flipBack
  8034. * @param {number} twirlClockwise
  8035. * @param {number} tiltRight
  8036. */
  8037. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8038. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8039. };
  8040. /**
  8041. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8042. * Supports definition of mesh facing forward or backward.
  8043. * @param {number} flipBack
  8044. * @param {number} twirlClockwise
  8045. * @param {number} tiltRight
  8046. */
  8047. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8048. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8049. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8050. };
  8051. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8052. this._pivotMatrix = matrix;
  8053. this._cache.pivotMatrixUpdated = true;
  8054. };
  8055. AbstractMesh.prototype.getPivotMatrix = function () {
  8056. return this._pivotMatrix;
  8057. };
  8058. AbstractMesh.prototype._isSynchronized = function () {
  8059. if (this._isDirty) {
  8060. return false;
  8061. }
  8062. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8063. return false;
  8064. if (this._cache.pivotMatrixUpdated) {
  8065. return false;
  8066. }
  8067. if (this.infiniteDistance) {
  8068. return false;
  8069. }
  8070. if (!this._cache.position.equals(this.position))
  8071. return false;
  8072. if (this.rotationQuaternion) {
  8073. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8074. return false;
  8075. }
  8076. else {
  8077. if (!this._cache.rotation.equals(this.rotation))
  8078. return false;
  8079. }
  8080. if (!this._cache.scaling.equals(this.scaling))
  8081. return false;
  8082. return true;
  8083. };
  8084. AbstractMesh.prototype._initCache = function () {
  8085. _super.prototype._initCache.call(this);
  8086. this._cache.localMatrixUpdated = false;
  8087. this._cache.position = BABYLON.Vector3.Zero();
  8088. this._cache.scaling = BABYLON.Vector3.Zero();
  8089. this._cache.rotation = BABYLON.Vector3.Zero();
  8090. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8091. };
  8092. AbstractMesh.prototype.markAsDirty = function (property) {
  8093. if (property === "rotation") {
  8094. this.rotationQuaternion = null;
  8095. }
  8096. this._currentRenderId = Number.MAX_VALUE;
  8097. this._isDirty = true;
  8098. };
  8099. AbstractMesh.prototype._updateBoundingInfo = function () {
  8100. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8101. this._boundingInfo._update(this.worldMatrixFromCache);
  8102. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8103. };
  8104. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8105. if (!this.subMeshes) {
  8106. return;
  8107. }
  8108. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8109. var subMesh = this.subMeshes[subIndex];
  8110. subMesh.updateBoundingInfo(matrix);
  8111. }
  8112. };
  8113. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8114. if (this._isWorldMatrixFrozen) {
  8115. return this._worldMatrix;
  8116. }
  8117. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8118. return this._worldMatrix;
  8119. }
  8120. this._cache.position.copyFrom(this.position);
  8121. this._cache.scaling.copyFrom(this.scaling);
  8122. this._cache.pivotMatrixUpdated = false;
  8123. this._currentRenderId = this.getScene().getRenderId();
  8124. this._isDirty = false;
  8125. // Scaling
  8126. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  8127. // Rotation
  8128. if (this.rotationQuaternion) {
  8129. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8130. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8131. }
  8132. else {
  8133. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8134. this._cache.rotation.copyFrom(this.rotation);
  8135. }
  8136. // Translation
  8137. if (this.infiniteDistance && !this.parent) {
  8138. var camera = this.getScene().activeCamera;
  8139. if (camera) {
  8140. var cameraWorldMatrix = camera.getWorldMatrix();
  8141. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8142. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8143. }
  8144. }
  8145. else {
  8146. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8147. }
  8148. // Composing transformations
  8149. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8150. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8151. // Billboarding
  8152. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8153. var localPosition = this.position.clone();
  8154. var zero = this.getScene().activeCamera.globalPosition.clone();
  8155. if (this.parent && this.parent.position) {
  8156. localPosition.addInPlace(this.parent.position);
  8157. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8158. }
  8159. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8160. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8161. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8162. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8163. zero.y = localPosition.y + 0.001;
  8164. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8165. zero.z = localPosition.z + 0.001;
  8166. }
  8167. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8168. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8169. this._localBillboard.invert();
  8170. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8171. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8172. }
  8173. // Local world
  8174. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8175. // Parent
  8176. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8177. this._markSyncedWithParent();
  8178. if (this._meshToBoneReferal) {
  8179. if (!this._localMeshReferalTransform) {
  8180. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8181. }
  8182. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8183. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8184. }
  8185. else {
  8186. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8187. }
  8188. }
  8189. else {
  8190. this._worldMatrix.copyFrom(this._localWorld);
  8191. }
  8192. // Bounding info
  8193. this._updateBoundingInfo();
  8194. // Absolute position
  8195. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8196. // Callbacks
  8197. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8198. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8199. }
  8200. return this._worldMatrix;
  8201. };
  8202. /**
  8203. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8204. * @param func: callback function to add
  8205. */
  8206. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8207. this._onAfterWorldMatrixUpdate.push(func);
  8208. };
  8209. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8210. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8211. if (index > -1) {
  8212. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8213. }
  8214. };
  8215. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8216. this.computeWorldMatrix();
  8217. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8218. };
  8219. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8220. this.computeWorldMatrix();
  8221. var invLocalWorldMatrix = this._localWorld.clone();
  8222. invLocalWorldMatrix.invert();
  8223. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8224. };
  8225. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8226. this.computeWorldMatrix(true);
  8227. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8228. };
  8229. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8230. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8231. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8232. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8233. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8234. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8235. /// <returns>Mesh oriented towards targetMesh</returns>
  8236. yawCor = yawCor || 0; // default to zero if undefined
  8237. pitchCor = pitchCor || 0;
  8238. rollCor = rollCor || 0;
  8239. var dv = targetPoint.subtract(this.position);
  8240. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8241. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8242. var pitch = Math.atan2(dv.y, len);
  8243. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8244. };
  8245. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8246. this._meshToBoneReferal = affectedMesh;
  8247. this.parent = bone;
  8248. if (bone.getWorldMatrix().determinant() < 0) {
  8249. this.scalingDeterminant *= -1;
  8250. }
  8251. };
  8252. AbstractMesh.prototype.detachFromBone = function () {
  8253. if (this.parent.getWorldMatrix().determinant() < 0) {
  8254. this.scalingDeterminant *= -1;
  8255. }
  8256. this._meshToBoneReferal = null;
  8257. this.parent = null;
  8258. };
  8259. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8260. return this._boundingInfo.isInFrustum(frustumPlanes);
  8261. };
  8262. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8263. if (!camera) {
  8264. camera = this.getScene().activeCamera;
  8265. }
  8266. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8267. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8268. return false;
  8269. }
  8270. return true;
  8271. };
  8272. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8273. if (!this._boundingInfo || !mesh._boundingInfo) {
  8274. return false;
  8275. }
  8276. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8277. };
  8278. AbstractMesh.prototype.intersectsPoint = function (point) {
  8279. if (!this._boundingInfo) {
  8280. return false;
  8281. }
  8282. return this._boundingInfo.intersectsPoint(point);
  8283. };
  8284. // Physics
  8285. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8286. var physicsEngine = this.getScene().getPhysicsEngine();
  8287. if (!physicsEngine) {
  8288. return null;
  8289. }
  8290. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8291. if (impostor.impostor) {
  8292. // Old API
  8293. options = impostor;
  8294. impostor = impostor.impostor;
  8295. }
  8296. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8297. physicsEngine._unregisterMesh(this);
  8298. return null;
  8299. }
  8300. if (!options) {
  8301. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8302. }
  8303. else {
  8304. if (!options.mass && options.mass !== 0)
  8305. options.mass = 0;
  8306. if (!options.friction && options.friction !== 0)
  8307. options.friction = 0.2;
  8308. if (!options.restitution && options.restitution !== 0)
  8309. options.restitution = 0.2;
  8310. }
  8311. this._physicImpostor = impostor;
  8312. this._physicsMass = options.mass;
  8313. this._physicsFriction = options.friction;
  8314. this._physicRestitution = options.restitution;
  8315. return physicsEngine._registerMesh(this, impostor, options);
  8316. };
  8317. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8318. if (!this._physicImpostor) {
  8319. return BABYLON.PhysicsEngine.NoImpostor;
  8320. }
  8321. return this._physicImpostor;
  8322. };
  8323. AbstractMesh.prototype.getPhysicsMass = function () {
  8324. if (!this._physicsMass) {
  8325. return 0;
  8326. }
  8327. return this._physicsMass;
  8328. };
  8329. AbstractMesh.prototype.getPhysicsFriction = function () {
  8330. if (!this._physicsFriction) {
  8331. return 0;
  8332. }
  8333. return this._physicsFriction;
  8334. };
  8335. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8336. if (!this._physicRestitution) {
  8337. return 0;
  8338. }
  8339. return this._physicRestitution;
  8340. };
  8341. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8342. if (!camera) {
  8343. camera = this.getScene().activeCamera;
  8344. }
  8345. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8346. };
  8347. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8348. if (!camera) {
  8349. camera = this.getScene().activeCamera;
  8350. }
  8351. return this.absolutePosition.subtract(camera.position).length();
  8352. };
  8353. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8354. if (!this._physicImpostor) {
  8355. return;
  8356. }
  8357. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8358. };
  8359. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8360. if (!this._physicImpostor) {
  8361. return;
  8362. }
  8363. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8364. };
  8365. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8366. if (!this._physicImpostor) {
  8367. return;
  8368. }
  8369. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8370. };
  8371. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8372. // Collisions
  8373. get: function () {
  8374. return this._checkCollisions;
  8375. },
  8376. set: function (collisionEnabled) {
  8377. this._checkCollisions = collisionEnabled;
  8378. if (this.getScene().workerCollisions) {
  8379. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8380. }
  8381. },
  8382. enumerable: true,
  8383. configurable: true
  8384. });
  8385. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8386. var globalPosition = this.getAbsolutePosition();
  8387. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8388. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8389. this._collider.radius = this.ellipsoid;
  8390. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8391. };
  8392. // Submeshes octree
  8393. /**
  8394. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8395. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8396. */
  8397. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8398. if (maxCapacity === void 0) { maxCapacity = 64; }
  8399. if (maxDepth === void 0) { maxDepth = 2; }
  8400. if (!this._submeshesOctree) {
  8401. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8402. }
  8403. this.computeWorldMatrix(true);
  8404. // Update octree
  8405. var bbox = this.getBoundingInfo().boundingBox;
  8406. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8407. return this._submeshesOctree;
  8408. };
  8409. // Collisions
  8410. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8411. this._generatePointsArray();
  8412. // Transformation
  8413. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8414. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8415. subMesh._lastColliderWorldVertices = [];
  8416. subMesh._trianglePlanes = [];
  8417. var start = subMesh.verticesStart;
  8418. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8419. for (var i = start; i < end; i++) {
  8420. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8421. }
  8422. }
  8423. // Collide
  8424. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8425. if (collider.collisionFound) {
  8426. collider.collidedMesh = this;
  8427. }
  8428. };
  8429. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8430. var subMeshes;
  8431. var len;
  8432. // Octrees
  8433. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8434. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8435. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8436. len = intersections.length;
  8437. subMeshes = intersections.data;
  8438. }
  8439. else {
  8440. subMeshes = this.subMeshes;
  8441. len = subMeshes.length;
  8442. }
  8443. for (var index = 0; index < len; index++) {
  8444. var subMesh = subMeshes[index];
  8445. // Bounding test
  8446. if (len > 1 && !subMesh._checkCollision(collider))
  8447. continue;
  8448. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8449. }
  8450. };
  8451. AbstractMesh.prototype._checkCollision = function (collider) {
  8452. // Bounding box test
  8453. if (!this._boundingInfo._checkCollision(collider))
  8454. return;
  8455. // Transformation matrix
  8456. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8457. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8458. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8459. };
  8460. // Picking
  8461. AbstractMesh.prototype._generatePointsArray = function () {
  8462. return false;
  8463. };
  8464. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8465. var pickingInfo = new BABYLON.PickingInfo();
  8466. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8467. return pickingInfo;
  8468. }
  8469. if (!this._generatePointsArray()) {
  8470. return pickingInfo;
  8471. }
  8472. var intersectInfo = null;
  8473. // Octrees
  8474. var subMeshes;
  8475. var len;
  8476. if (this._submeshesOctree && this.useOctreeForPicking) {
  8477. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8478. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8479. len = intersections.length;
  8480. subMeshes = intersections.data;
  8481. }
  8482. else {
  8483. subMeshes = this.subMeshes;
  8484. len = subMeshes.length;
  8485. }
  8486. for (var index = 0; index < len; index++) {
  8487. var subMesh = subMeshes[index];
  8488. // Bounding test
  8489. if (len > 1 && !subMesh.canIntersects(ray))
  8490. continue;
  8491. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8492. if (currentIntersectInfo) {
  8493. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8494. intersectInfo = currentIntersectInfo;
  8495. intersectInfo.subMeshId = index;
  8496. if (fastCheck) {
  8497. break;
  8498. }
  8499. }
  8500. }
  8501. }
  8502. if (intersectInfo) {
  8503. // Get picked point
  8504. var world = this.getWorldMatrix();
  8505. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8506. var direction = ray.direction.clone();
  8507. direction = direction.scale(intersectInfo.distance);
  8508. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8509. var pickedPoint = worldOrigin.add(worldDirection);
  8510. // Return result
  8511. pickingInfo.hit = true;
  8512. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8513. pickingInfo.pickedPoint = pickedPoint;
  8514. pickingInfo.pickedMesh = this;
  8515. pickingInfo.bu = intersectInfo.bu;
  8516. pickingInfo.bv = intersectInfo.bv;
  8517. pickingInfo.faceId = intersectInfo.faceId;
  8518. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8519. return pickingInfo;
  8520. }
  8521. return pickingInfo;
  8522. };
  8523. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8524. return null;
  8525. };
  8526. AbstractMesh.prototype.releaseSubMeshes = function () {
  8527. if (this.subMeshes) {
  8528. while (this.subMeshes.length) {
  8529. this.subMeshes[0].dispose();
  8530. }
  8531. }
  8532. else {
  8533. this.subMeshes = new Array();
  8534. }
  8535. };
  8536. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8537. var index;
  8538. // Physics
  8539. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8540. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8541. }
  8542. // Intersections in progress
  8543. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8544. var other = this._intersectionsInProgress[index];
  8545. var pos = other._intersectionsInProgress.indexOf(this);
  8546. other._intersectionsInProgress.splice(pos, 1);
  8547. }
  8548. this._intersectionsInProgress = [];
  8549. // Edges
  8550. if (this._edgesRenderer) {
  8551. this._edgesRenderer.dispose();
  8552. this._edgesRenderer = null;
  8553. }
  8554. // SubMeshes
  8555. this.releaseSubMeshes();
  8556. // Remove from scene
  8557. this.getScene().removeMesh(this);
  8558. if (!doNotRecurse) {
  8559. // Particles
  8560. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8561. if (this.getScene().particleSystems[index].emitter === this) {
  8562. this.getScene().particleSystems[index].dispose();
  8563. index--;
  8564. }
  8565. }
  8566. // Children
  8567. var objects = this.getScene().meshes.slice(0);
  8568. for (index = 0; index < objects.length; index++) {
  8569. if (objects[index].parent === this) {
  8570. objects[index].dispose();
  8571. }
  8572. }
  8573. }
  8574. else {
  8575. for (index = 0; index < this.getScene().meshes.length; index++) {
  8576. var obj = this.getScene().meshes[index];
  8577. if (obj.parent === this) {
  8578. obj.parent = null;
  8579. obj.computeWorldMatrix(true);
  8580. }
  8581. }
  8582. }
  8583. this._onAfterWorldMatrixUpdate = [];
  8584. this._isDisposed = true;
  8585. // Callback
  8586. if (this.onDispose) {
  8587. this.onDispose();
  8588. }
  8589. };
  8590. // Statics
  8591. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8592. AbstractMesh._BILLBOARDMODE_X = 1;
  8593. AbstractMesh._BILLBOARDMODE_Y = 2;
  8594. AbstractMesh._BILLBOARDMODE_Z = 4;
  8595. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8596. return AbstractMesh;
  8597. })(BABYLON.Node);
  8598. BABYLON.AbstractMesh = AbstractMesh;
  8599. })(BABYLON || (BABYLON = {}));
  8600. var BABYLON;
  8601. (function (BABYLON) {
  8602. var Light = (function (_super) {
  8603. __extends(Light, _super);
  8604. function Light(name, scene) {
  8605. _super.call(this, name, scene);
  8606. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8607. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8608. this.intensity = 1.0;
  8609. this.range = Number.MAX_VALUE;
  8610. this.includeOnlyWithLayerMask = 0;
  8611. this.includedOnlyMeshes = new Array();
  8612. this.excludedMeshes = new Array();
  8613. this.excludeWithLayerMask = 0;
  8614. this._excludedMeshesIds = new Array();
  8615. this._includedOnlyMeshesIds = new Array();
  8616. scene.addLight(this);
  8617. }
  8618. Light.prototype.getShadowGenerator = function () {
  8619. return this._shadowGenerator;
  8620. };
  8621. Light.prototype.getAbsolutePosition = function () {
  8622. return BABYLON.Vector3.Zero();
  8623. };
  8624. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8625. };
  8626. Light.prototype._getWorldMatrix = function () {
  8627. return BABYLON.Matrix.Identity();
  8628. };
  8629. Light.prototype.canAffectMesh = function (mesh) {
  8630. if (!mesh) {
  8631. return true;
  8632. }
  8633. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8634. return false;
  8635. }
  8636. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8637. return false;
  8638. }
  8639. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8640. return false;
  8641. }
  8642. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8643. return false;
  8644. }
  8645. return true;
  8646. };
  8647. Light.prototype.getWorldMatrix = function () {
  8648. this._currentRenderId = this.getScene().getRenderId();
  8649. var worldMatrix = this._getWorldMatrix();
  8650. if (this.parent && this.parent.getWorldMatrix) {
  8651. if (!this._parentedWorldMatrix) {
  8652. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8653. }
  8654. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8655. this._markSyncedWithParent();
  8656. return this._parentedWorldMatrix;
  8657. }
  8658. return worldMatrix;
  8659. };
  8660. Light.prototype.dispose = function () {
  8661. if (this._shadowGenerator) {
  8662. this._shadowGenerator.dispose();
  8663. this._shadowGenerator = null;
  8664. }
  8665. // Remove from scene
  8666. this.getScene().removeLight(this);
  8667. };
  8668. return Light;
  8669. })(BABYLON.Node);
  8670. BABYLON.Light = Light;
  8671. })(BABYLON || (BABYLON = {}));
  8672. var BABYLON;
  8673. (function (BABYLON) {
  8674. var PointLight = (function (_super) {
  8675. __extends(PointLight, _super);
  8676. function PointLight(name, position, scene) {
  8677. _super.call(this, name, scene);
  8678. this.position = position;
  8679. }
  8680. PointLight.prototype.getAbsolutePosition = function () {
  8681. return this._transformedPosition ? this._transformedPosition : this.position;
  8682. };
  8683. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8684. if (this.parent && this.parent.getWorldMatrix) {
  8685. if (!this._transformedPosition) {
  8686. this._transformedPosition = BABYLON.Vector3.Zero();
  8687. }
  8688. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8689. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8690. return;
  8691. }
  8692. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8693. };
  8694. PointLight.prototype.getShadowGenerator = function () {
  8695. return null;
  8696. };
  8697. PointLight.prototype._getWorldMatrix = function () {
  8698. if (!this._worldMatrix) {
  8699. this._worldMatrix = BABYLON.Matrix.Identity();
  8700. }
  8701. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8702. return this._worldMatrix;
  8703. };
  8704. return PointLight;
  8705. })(BABYLON.Light);
  8706. BABYLON.PointLight = PointLight;
  8707. })(BABYLON || (BABYLON = {}));
  8708. var BABYLON;
  8709. (function (BABYLON) {
  8710. var SpotLight = (function (_super) {
  8711. __extends(SpotLight, _super);
  8712. function SpotLight(name, position, direction, angle, exponent, scene) {
  8713. _super.call(this, name, scene);
  8714. this.position = position;
  8715. this.direction = direction;
  8716. this.angle = angle;
  8717. this.exponent = exponent;
  8718. }
  8719. SpotLight.prototype.getAbsolutePosition = function () {
  8720. return this.transformedPosition ? this.transformedPosition : this.position;
  8721. };
  8722. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8723. var activeCamera = this.getScene().activeCamera;
  8724. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8725. };
  8726. SpotLight.prototype.supportsVSM = function () {
  8727. return true;
  8728. };
  8729. SpotLight.prototype.needRefreshPerFrame = function () {
  8730. return false;
  8731. };
  8732. SpotLight.prototype.setDirectionToTarget = function (target) {
  8733. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8734. return this.direction;
  8735. };
  8736. SpotLight.prototype.computeTransformedPosition = function () {
  8737. if (this.parent && this.parent.getWorldMatrix) {
  8738. if (!this.transformedPosition) {
  8739. this.transformedPosition = BABYLON.Vector3.Zero();
  8740. }
  8741. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8742. return true;
  8743. }
  8744. return false;
  8745. };
  8746. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8747. var normalizeDirection;
  8748. if (this.parent && this.parent.getWorldMatrix) {
  8749. if (!this._transformedDirection) {
  8750. this._transformedDirection = BABYLON.Vector3.Zero();
  8751. }
  8752. this.computeTransformedPosition();
  8753. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8754. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8755. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8756. }
  8757. else {
  8758. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8759. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8760. }
  8761. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8762. };
  8763. SpotLight.prototype._getWorldMatrix = function () {
  8764. if (!this._worldMatrix) {
  8765. this._worldMatrix = BABYLON.Matrix.Identity();
  8766. }
  8767. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8768. return this._worldMatrix;
  8769. };
  8770. return SpotLight;
  8771. })(BABYLON.Light);
  8772. BABYLON.SpotLight = SpotLight;
  8773. })(BABYLON || (BABYLON = {}));
  8774. var BABYLON;
  8775. (function (BABYLON) {
  8776. var HemisphericLight = (function (_super) {
  8777. __extends(HemisphericLight, _super);
  8778. function HemisphericLight(name, direction, scene) {
  8779. _super.call(this, name, scene);
  8780. this.direction = direction;
  8781. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8782. }
  8783. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8784. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8785. return this.direction;
  8786. };
  8787. HemisphericLight.prototype.getShadowGenerator = function () {
  8788. return null;
  8789. };
  8790. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8791. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8792. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8793. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8794. };
  8795. HemisphericLight.prototype._getWorldMatrix = function () {
  8796. if (!this._worldMatrix) {
  8797. this._worldMatrix = BABYLON.Matrix.Identity();
  8798. }
  8799. return this._worldMatrix;
  8800. };
  8801. return HemisphericLight;
  8802. })(BABYLON.Light);
  8803. BABYLON.HemisphericLight = HemisphericLight;
  8804. })(BABYLON || (BABYLON = {}));
  8805. var BABYLON;
  8806. (function (BABYLON) {
  8807. var DirectionalLight = (function (_super) {
  8808. __extends(DirectionalLight, _super);
  8809. function DirectionalLight(name, direction, scene) {
  8810. _super.call(this, name, scene);
  8811. this.direction = direction;
  8812. this.shadowOrthoScale = 0.5;
  8813. this.position = direction.scale(-1);
  8814. }
  8815. DirectionalLight.prototype.getAbsolutePosition = function () {
  8816. return this.transformedPosition ? this.transformedPosition : this.position;
  8817. };
  8818. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8819. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8820. return this.direction;
  8821. };
  8822. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8823. var orthoLeft = Number.MAX_VALUE;
  8824. var orthoRight = Number.MIN_VALUE;
  8825. var orthoTop = Number.MIN_VALUE;
  8826. var orthoBottom = Number.MAX_VALUE;
  8827. var tempVector3 = BABYLON.Vector3.Zero();
  8828. var activeCamera = this.getScene().activeCamera;
  8829. // Check extends
  8830. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8831. var mesh = renderList[meshIndex];
  8832. if (!mesh) {
  8833. continue;
  8834. }
  8835. var boundingInfo = mesh.getBoundingInfo();
  8836. if (!boundingInfo) {
  8837. continue;
  8838. }
  8839. var boundingBox = boundingInfo.boundingBox;
  8840. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8841. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8842. if (tempVector3.x < orthoLeft)
  8843. orthoLeft = tempVector3.x;
  8844. if (tempVector3.y < orthoBottom)
  8845. orthoBottom = tempVector3.y;
  8846. if (tempVector3.x > orthoRight)
  8847. orthoRight = tempVector3.x;
  8848. if (tempVector3.y > orthoTop)
  8849. orthoTop = tempVector3.y;
  8850. }
  8851. }
  8852. var xOffset = orthoRight - orthoLeft;
  8853. var yOffset = orthoTop - orthoBottom;
  8854. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8855. };
  8856. DirectionalLight.prototype.supportsVSM = function () {
  8857. return true;
  8858. };
  8859. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8860. return true;
  8861. };
  8862. DirectionalLight.prototype.computeTransformedPosition = function () {
  8863. if (this.parent && this.parent.getWorldMatrix) {
  8864. if (!this.transformedPosition) {
  8865. this.transformedPosition = BABYLON.Vector3.Zero();
  8866. }
  8867. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8868. return true;
  8869. }
  8870. return false;
  8871. };
  8872. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8873. if (this.parent && this.parent.getWorldMatrix) {
  8874. if (!this._transformedDirection) {
  8875. this._transformedDirection = BABYLON.Vector3.Zero();
  8876. }
  8877. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8878. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8879. return;
  8880. }
  8881. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8882. };
  8883. DirectionalLight.prototype._getWorldMatrix = function () {
  8884. if (!this._worldMatrix) {
  8885. this._worldMatrix = BABYLON.Matrix.Identity();
  8886. }
  8887. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8888. return this._worldMatrix;
  8889. };
  8890. return DirectionalLight;
  8891. })(BABYLON.Light);
  8892. BABYLON.DirectionalLight = DirectionalLight;
  8893. })(BABYLON || (BABYLON = {}));
  8894. var BABYLON;
  8895. (function (BABYLON) {
  8896. var ShadowGenerator = (function () {
  8897. function ShadowGenerator(mapSize, light) {
  8898. var _this = this;
  8899. // Members
  8900. this._filter = ShadowGenerator.FILTER_NONE;
  8901. this.blurScale = 2;
  8902. this._blurBoxOffset = 0;
  8903. this._bias = 0.00005;
  8904. this._lightDirection = BABYLON.Vector3.Zero();
  8905. this._darkness = 0;
  8906. this._transparencyShadow = false;
  8907. this._viewMatrix = BABYLON.Matrix.Zero();
  8908. this._projectionMatrix = BABYLON.Matrix.Zero();
  8909. this._transformMatrix = BABYLON.Matrix.Zero();
  8910. this._worldViewProjection = BABYLON.Matrix.Zero();
  8911. this._light = light;
  8912. this._scene = light.getScene();
  8913. this._mapSize = mapSize;
  8914. light._shadowGenerator = this;
  8915. // Render target
  8916. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8917. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8918. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8919. this._shadowMap.anisotropicFilteringLevel = 1;
  8920. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8921. this._shadowMap.renderParticles = false;
  8922. this._shadowMap.onAfterUnbind = function () {
  8923. if (!_this.useBlurVarianceShadowMap) {
  8924. return;
  8925. }
  8926. if (!_this._shadowMap2) {
  8927. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8928. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8929. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8930. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8931. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8932. _this._downSamplePostprocess.onApply = function (effect) {
  8933. effect.setTexture("textureSampler", _this._shadowMap);
  8934. };
  8935. _this.blurBoxOffset = 1;
  8936. }
  8937. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8938. };
  8939. // Custom render function
  8940. var renderSubMesh = function (subMesh) {
  8941. var mesh = subMesh.getRenderingMesh();
  8942. var scene = _this._scene;
  8943. var engine = scene.getEngine();
  8944. // Culling
  8945. engine.setState(subMesh.getMaterial().backFaceCulling);
  8946. // Managing instances
  8947. var batch = mesh._getInstancesRenderList(subMesh._id);
  8948. if (batch.mustReturn) {
  8949. return;
  8950. }
  8951. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8952. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8953. engine.enableEffect(_this._effect);
  8954. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8955. var material = subMesh.getMaterial();
  8956. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8957. // Alpha test
  8958. if (material && material.needAlphaTesting()) {
  8959. var alphaTexture = material.getAlphaTestTexture();
  8960. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8961. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8962. }
  8963. // Bones
  8964. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8965. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8966. }
  8967. // Draw
  8968. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8969. }
  8970. else {
  8971. // Need to reset refresh rate of the shadowMap
  8972. _this._shadowMap.resetRefreshCounter();
  8973. }
  8974. };
  8975. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8976. var index;
  8977. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8978. renderSubMesh(opaqueSubMeshes.data[index]);
  8979. }
  8980. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8981. renderSubMesh(alphaTestSubMeshes.data[index]);
  8982. }
  8983. if (_this._transparencyShadow) {
  8984. for (index = 0; index < transparentSubMeshes.length; index++) {
  8985. renderSubMesh(transparentSubMeshes.data[index]);
  8986. }
  8987. }
  8988. };
  8989. this._shadowMap.onClear = function (engine) {
  8990. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8991. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8992. }
  8993. else {
  8994. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8995. }
  8996. };
  8997. }
  8998. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8999. // Static
  9000. get: function () {
  9001. return ShadowGenerator._FILTER_NONE;
  9002. },
  9003. enumerable: true,
  9004. configurable: true
  9005. });
  9006. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9007. get: function () {
  9008. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9009. },
  9010. enumerable: true,
  9011. configurable: true
  9012. });
  9013. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9014. get: function () {
  9015. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9016. },
  9017. enumerable: true,
  9018. configurable: true
  9019. });
  9020. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9021. get: function () {
  9022. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9023. },
  9024. enumerable: true,
  9025. configurable: true
  9026. });
  9027. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9028. get: function () {
  9029. return this._bias;
  9030. },
  9031. set: function (bias) {
  9032. this._bias = bias;
  9033. },
  9034. enumerable: true,
  9035. configurable: true
  9036. });
  9037. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9038. get: function () {
  9039. return this._blurBoxOffset;
  9040. },
  9041. set: function (value) {
  9042. var _this = this;
  9043. if (this._blurBoxOffset === value) {
  9044. return;
  9045. }
  9046. this._blurBoxOffset = value;
  9047. if (this._boxBlurPostprocess) {
  9048. this._boxBlurPostprocess.dispose();
  9049. }
  9050. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  9051. this._boxBlurPostprocess.onApply = function (effect) {
  9052. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9053. };
  9054. },
  9055. enumerable: true,
  9056. configurable: true
  9057. });
  9058. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9059. get: function () {
  9060. return this._filter;
  9061. },
  9062. set: function (value) {
  9063. if (this._filter === value) {
  9064. return;
  9065. }
  9066. this._filter = value;
  9067. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9068. this._shadowMap.anisotropicFilteringLevel = 16;
  9069. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9070. }
  9071. else {
  9072. this._shadowMap.anisotropicFilteringLevel = 1;
  9073. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9074. }
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9080. get: function () {
  9081. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9082. },
  9083. set: function (value) {
  9084. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9085. },
  9086. enumerable: true,
  9087. configurable: true
  9088. });
  9089. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9090. get: function () {
  9091. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9092. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9093. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9094. },
  9095. set: function (value) {
  9096. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9102. get: function () {
  9103. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9104. },
  9105. set: function (value) {
  9106. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9107. },
  9108. enumerable: true,
  9109. configurable: true
  9110. });
  9111. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9112. var defines = [];
  9113. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9114. defines.push("#define VSM");
  9115. }
  9116. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9117. var mesh = subMesh.getMesh();
  9118. var material = subMesh.getMaterial();
  9119. // Alpha test
  9120. if (material && material.needAlphaTesting()) {
  9121. defines.push("#define ALPHATEST");
  9122. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9123. attribs.push(BABYLON.VertexBuffer.UVKind);
  9124. defines.push("#define UV1");
  9125. }
  9126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9127. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9128. defines.push("#define UV2");
  9129. }
  9130. }
  9131. // Bones
  9132. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9133. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9134. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9135. defines.push("#define BONES");
  9136. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9137. }
  9138. // Instances
  9139. if (useInstances) {
  9140. defines.push("#define INSTANCES");
  9141. attribs.push("world0");
  9142. attribs.push("world1");
  9143. attribs.push("world2");
  9144. attribs.push("world3");
  9145. }
  9146. // Get correct effect
  9147. var join = defines.join("\n");
  9148. if (this._cachedDefines !== join) {
  9149. this._cachedDefines = join;
  9150. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9151. }
  9152. return this._effect.isReady();
  9153. };
  9154. ShadowGenerator.prototype.getShadowMap = function () {
  9155. return this._shadowMap;
  9156. };
  9157. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9158. if (this._shadowMap2) {
  9159. return this._shadowMap2;
  9160. }
  9161. return this._shadowMap;
  9162. };
  9163. ShadowGenerator.prototype.getLight = function () {
  9164. return this._light;
  9165. };
  9166. // Methods
  9167. ShadowGenerator.prototype.getTransformMatrix = function () {
  9168. var scene = this._scene;
  9169. if (this._currentRenderID === scene.getRenderId()) {
  9170. return this._transformMatrix;
  9171. }
  9172. this._currentRenderID = scene.getRenderId();
  9173. var lightPosition = this._light.position;
  9174. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9175. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9176. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9177. }
  9178. if (this._light.computeTransformedPosition()) {
  9179. lightPosition = this._light.transformedPosition;
  9180. }
  9181. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9182. this._cachedPosition = lightPosition.clone();
  9183. this._cachedDirection = this._lightDirection.clone();
  9184. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9185. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9186. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9187. }
  9188. return this._transformMatrix;
  9189. };
  9190. ShadowGenerator.prototype.getDarkness = function () {
  9191. return this._darkness;
  9192. };
  9193. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9194. if (darkness >= 1.0)
  9195. this._darkness = 1.0;
  9196. else if (darkness <= 0.0)
  9197. this._darkness = 0.0;
  9198. else
  9199. this._darkness = darkness;
  9200. };
  9201. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9202. this._transparencyShadow = hasShadow;
  9203. };
  9204. ShadowGenerator.prototype._packHalf = function (depth) {
  9205. var scale = depth * 255.0;
  9206. var fract = scale - Math.floor(scale);
  9207. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9208. };
  9209. ShadowGenerator.prototype.dispose = function () {
  9210. this._shadowMap.dispose();
  9211. if (this._shadowMap2) {
  9212. this._shadowMap2.dispose();
  9213. }
  9214. if (this._downSamplePostprocess) {
  9215. this._downSamplePostprocess.dispose();
  9216. }
  9217. if (this._boxBlurPostprocess) {
  9218. this._boxBlurPostprocess.dispose();
  9219. }
  9220. };
  9221. ShadowGenerator._FILTER_NONE = 0;
  9222. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9223. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9224. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9225. return ShadowGenerator;
  9226. })();
  9227. BABYLON.ShadowGenerator = ShadowGenerator;
  9228. })(BABYLON || (BABYLON = {}));
  9229. var BABYLON;
  9230. (function (BABYLON) {
  9231. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9232. if (boxMin.x > sphereCenter.x + sphereRadius)
  9233. return false;
  9234. if (sphereCenter.x - sphereRadius > boxMax.x)
  9235. return false;
  9236. if (boxMin.y > sphereCenter.y + sphereRadius)
  9237. return false;
  9238. if (sphereCenter.y - sphereRadius > boxMax.y)
  9239. return false;
  9240. if (boxMin.z > sphereCenter.z + sphereRadius)
  9241. return false;
  9242. if (sphereCenter.z - sphereRadius > boxMax.z)
  9243. return false;
  9244. return true;
  9245. };
  9246. var getLowestRoot = function (a, b, c, maxR) {
  9247. var determinant = b * b - 4.0 * a * c;
  9248. var result = { root: 0, found: false };
  9249. if (determinant < 0)
  9250. return result;
  9251. var sqrtD = Math.sqrt(determinant);
  9252. var r1 = (-b - sqrtD) / (2.0 * a);
  9253. var r2 = (-b + sqrtD) / (2.0 * a);
  9254. if (r1 > r2) {
  9255. var temp = r2;
  9256. r2 = r1;
  9257. r1 = temp;
  9258. }
  9259. if (r1 > 0 && r1 < maxR) {
  9260. result.root = r1;
  9261. result.found = true;
  9262. return result;
  9263. }
  9264. if (r2 > 0 && r2 < maxR) {
  9265. result.root = r2;
  9266. result.found = true;
  9267. return result;
  9268. }
  9269. return result;
  9270. };
  9271. var Collider = (function () {
  9272. function Collider() {
  9273. this.radius = new BABYLON.Vector3(1, 1, 1);
  9274. this.retry = 0;
  9275. this.basePointWorld = BABYLON.Vector3.Zero();
  9276. this.velocityWorld = BABYLON.Vector3.Zero();
  9277. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9278. this._collisionPoint = BABYLON.Vector3.Zero();
  9279. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9280. this._tempVector = BABYLON.Vector3.Zero();
  9281. this._tempVector2 = BABYLON.Vector3.Zero();
  9282. this._tempVector3 = BABYLON.Vector3.Zero();
  9283. this._tempVector4 = BABYLON.Vector3.Zero();
  9284. this._edge = BABYLON.Vector3.Zero();
  9285. this._baseToVertex = BABYLON.Vector3.Zero();
  9286. this._destinationPoint = BABYLON.Vector3.Zero();
  9287. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9288. this._displacementVector = BABYLON.Vector3.Zero();
  9289. }
  9290. // Methods
  9291. Collider.prototype._initialize = function (source, dir, e) {
  9292. this.velocity = dir;
  9293. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9294. this.basePoint = source;
  9295. source.multiplyToRef(this.radius, this.basePointWorld);
  9296. dir.multiplyToRef(this.radius, this.velocityWorld);
  9297. this.velocityWorldLength = this.velocityWorld.length();
  9298. this.epsilon = e;
  9299. this.collisionFound = false;
  9300. };
  9301. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9302. pa.subtractToRef(point, this._tempVector);
  9303. pb.subtractToRef(point, this._tempVector2);
  9304. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9305. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9306. if (d < 0)
  9307. return false;
  9308. pc.subtractToRef(point, this._tempVector3);
  9309. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9310. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9311. if (d < 0)
  9312. return false;
  9313. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9314. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9315. return d >= 0;
  9316. };
  9317. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9318. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9319. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9320. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9321. return false;
  9322. }
  9323. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9324. return false;
  9325. return true;
  9326. };
  9327. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9328. var t0;
  9329. var embeddedInPlane = false;
  9330. //defensive programming, actually not needed.
  9331. if (!trianglePlaneArray) {
  9332. trianglePlaneArray = [];
  9333. }
  9334. if (!trianglePlaneArray[faceIndex]) {
  9335. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9336. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9337. }
  9338. var trianglePlane = trianglePlaneArray[faceIndex];
  9339. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9340. return;
  9341. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9342. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9343. if (normalDotVelocity == 0) {
  9344. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9345. return;
  9346. embeddedInPlane = true;
  9347. t0 = 0;
  9348. }
  9349. else {
  9350. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9351. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9352. if (t0 > t1) {
  9353. var temp = t1;
  9354. t1 = t0;
  9355. t0 = temp;
  9356. }
  9357. if (t0 > 1.0 || t1 < 0.0)
  9358. return;
  9359. if (t0 < 0)
  9360. t0 = 0;
  9361. if (t0 > 1.0)
  9362. t0 = 1.0;
  9363. }
  9364. this._collisionPoint.copyFromFloats(0, 0, 0);
  9365. var found = false;
  9366. var t = 1.0;
  9367. if (!embeddedInPlane) {
  9368. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9369. this.velocity.scaleToRef(t0, this._tempVector);
  9370. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9371. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9372. found = true;
  9373. t = t0;
  9374. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9375. }
  9376. }
  9377. if (!found) {
  9378. var velocitySquaredLength = this.velocity.lengthSquared();
  9379. var a = velocitySquaredLength;
  9380. this.basePoint.subtractToRef(p1, this._tempVector);
  9381. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9382. var c = this._tempVector.lengthSquared() - 1.0;
  9383. var lowestRoot = getLowestRoot(a, b, c, t);
  9384. if (lowestRoot.found) {
  9385. t = lowestRoot.root;
  9386. found = true;
  9387. this._collisionPoint.copyFrom(p1);
  9388. }
  9389. this.basePoint.subtractToRef(p2, this._tempVector);
  9390. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9391. c = this._tempVector.lengthSquared() - 1.0;
  9392. lowestRoot = getLowestRoot(a, b, c, t);
  9393. if (lowestRoot.found) {
  9394. t = lowestRoot.root;
  9395. found = true;
  9396. this._collisionPoint.copyFrom(p2);
  9397. }
  9398. this.basePoint.subtractToRef(p3, this._tempVector);
  9399. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9400. c = this._tempVector.lengthSquared() - 1.0;
  9401. lowestRoot = getLowestRoot(a, b, c, t);
  9402. if (lowestRoot.found) {
  9403. t = lowestRoot.root;
  9404. found = true;
  9405. this._collisionPoint.copyFrom(p3);
  9406. }
  9407. p2.subtractToRef(p1, this._edge);
  9408. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9409. var edgeSquaredLength = this._edge.lengthSquared();
  9410. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9411. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9412. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9413. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9414. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9415. lowestRoot = getLowestRoot(a, b, c, t);
  9416. if (lowestRoot.found) {
  9417. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9418. if (f >= 0.0 && f <= 1.0) {
  9419. t = lowestRoot.root;
  9420. found = true;
  9421. this._edge.scaleInPlace(f);
  9422. p1.addToRef(this._edge, this._collisionPoint);
  9423. }
  9424. }
  9425. p3.subtractToRef(p2, this._edge);
  9426. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9427. edgeSquaredLength = this._edge.lengthSquared();
  9428. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9429. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9430. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9431. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9432. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9433. lowestRoot = getLowestRoot(a, b, c, t);
  9434. if (lowestRoot.found) {
  9435. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9436. if (f >= 0.0 && f <= 1.0) {
  9437. t = lowestRoot.root;
  9438. found = true;
  9439. this._edge.scaleInPlace(f);
  9440. p2.addToRef(this._edge, this._collisionPoint);
  9441. }
  9442. }
  9443. p1.subtractToRef(p3, this._edge);
  9444. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9445. edgeSquaredLength = this._edge.lengthSquared();
  9446. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9447. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9448. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9449. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9450. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9451. lowestRoot = getLowestRoot(a, b, c, t);
  9452. if (lowestRoot.found) {
  9453. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9454. if (f >= 0.0 && f <= 1.0) {
  9455. t = lowestRoot.root;
  9456. found = true;
  9457. this._edge.scaleInPlace(f);
  9458. p3.addToRef(this._edge, this._collisionPoint);
  9459. }
  9460. }
  9461. }
  9462. if (found) {
  9463. var distToCollision = t * this.velocity.length();
  9464. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9465. if (!this.intersectionPoint) {
  9466. this.intersectionPoint = this._collisionPoint.clone();
  9467. }
  9468. else {
  9469. this.intersectionPoint.copyFrom(this._collisionPoint);
  9470. }
  9471. this.nearestDistance = distToCollision;
  9472. this.collisionFound = true;
  9473. }
  9474. }
  9475. };
  9476. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9477. for (var i = indexStart; i < indexEnd; i += 3) {
  9478. var p1 = pts[indices[i] - decal];
  9479. var p2 = pts[indices[i + 1] - decal];
  9480. var p3 = pts[indices[i + 2] - decal];
  9481. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9482. }
  9483. };
  9484. Collider.prototype._getResponse = function (pos, vel) {
  9485. pos.addToRef(vel, this._destinationPoint);
  9486. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9487. this.basePoint.addToRef(vel, pos);
  9488. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9489. this._slidePlaneNormal.normalize();
  9490. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9491. pos.addInPlace(this._displacementVector);
  9492. this.intersectionPoint.addInPlace(this._displacementVector);
  9493. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9494. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9495. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9496. };
  9497. return Collider;
  9498. })();
  9499. BABYLON.Collider = Collider;
  9500. })(BABYLON || (BABYLON = {}));
  9501. var BABYLON;
  9502. (function (BABYLON) {
  9503. //WebWorker code will be inserted to this variable.
  9504. BABYLON.CollisionWorker = "";
  9505. (function (WorkerTaskType) {
  9506. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9507. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9508. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9509. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9510. var WorkerTaskType = BABYLON.WorkerTaskType;
  9511. (function (WorkerReplyType) {
  9512. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9513. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9514. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9515. var WorkerReplyType = BABYLON.WorkerReplyType;
  9516. var CollisionCoordinatorWorker = (function () {
  9517. function CollisionCoordinatorWorker() {
  9518. var _this = this;
  9519. this._scaledPosition = BABYLON.Vector3.Zero();
  9520. this._scaledVelocity = BABYLON.Vector3.Zero();
  9521. this.onMeshUpdated = function (mesh) {
  9522. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9523. };
  9524. this.onGeometryUpdated = function (geometry) {
  9525. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9526. };
  9527. this._afterRender = function () {
  9528. if (!_this._init)
  9529. return;
  9530. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9531. return;
  9532. }
  9533. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9534. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9535. if (_this._runningUpdated > 4) {
  9536. return;
  9537. }
  9538. ++_this._runningUpdated;
  9539. var payload = {
  9540. updatedMeshes: _this._addUpdateMeshesList,
  9541. updatedGeometries: _this._addUpdateGeometriesList,
  9542. removedGeometries: _this._toRemoveGeometryArray,
  9543. removedMeshes: _this._toRemoveMeshesArray
  9544. };
  9545. var message = {
  9546. payload: payload,
  9547. taskType: WorkerTaskType.UPDATE
  9548. };
  9549. var serializable = [];
  9550. for (var id in payload.updatedGeometries) {
  9551. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9552. //prepare transferables
  9553. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9554. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9555. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9556. }
  9557. }
  9558. _this._worker.postMessage(message, serializable);
  9559. _this._addUpdateMeshesList = {};
  9560. _this._addUpdateGeometriesList = {};
  9561. _this._toRemoveGeometryArray = [];
  9562. _this._toRemoveMeshesArray = [];
  9563. };
  9564. this._onMessageFromWorker = function (e) {
  9565. var returnData = e.data;
  9566. if (returnData.error != WorkerReplyType.SUCCESS) {
  9567. //TODO what errors can be returned from the worker?
  9568. BABYLON.Tools.Warn("error returned from worker!");
  9569. return;
  9570. }
  9571. switch (returnData.taskType) {
  9572. case WorkerTaskType.INIT:
  9573. _this._init = true;
  9574. //Update the worked with ALL of the scene's current state
  9575. _this._scene.meshes.forEach(function (mesh) {
  9576. _this.onMeshAdded(mesh);
  9577. });
  9578. _this._scene.getGeometries().forEach(function (geometry) {
  9579. _this.onGeometryAdded(geometry);
  9580. });
  9581. break;
  9582. case WorkerTaskType.UPDATE:
  9583. _this._runningUpdated--;
  9584. break;
  9585. case WorkerTaskType.COLLIDE:
  9586. _this._runningCollisionTask = false;
  9587. var returnPayload = returnData.payload;
  9588. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9589. return;
  9590. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9591. //cleanup
  9592. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9593. break;
  9594. }
  9595. };
  9596. this._collisionsCallbackArray = [];
  9597. this._init = false;
  9598. this._runningUpdated = 0;
  9599. this._runningCollisionTask = false;
  9600. this._addUpdateMeshesList = {};
  9601. this._addUpdateGeometriesList = {};
  9602. this._toRemoveGeometryArray = [];
  9603. this._toRemoveMeshesArray = [];
  9604. }
  9605. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9606. if (!this._init)
  9607. return;
  9608. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9609. return;
  9610. position.divideToRef(collider.radius, this._scaledPosition);
  9611. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9612. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9613. var payload = {
  9614. collider: {
  9615. position: this._scaledPosition.asArray(),
  9616. velocity: this._scaledVelocity.asArray(),
  9617. radius: collider.radius.asArray()
  9618. },
  9619. collisionId: collisionIndex,
  9620. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9621. maximumRetry: maximumRetry
  9622. };
  9623. var message = {
  9624. payload: payload,
  9625. taskType: WorkerTaskType.COLLIDE
  9626. };
  9627. this._worker.postMessage(message);
  9628. };
  9629. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9630. this._scene = scene;
  9631. this._scene.registerAfterRender(this._afterRender);
  9632. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9633. this._worker = new Worker(workerUrl);
  9634. this._worker.onmessage = this._onMessageFromWorker;
  9635. var message = {
  9636. payload: {},
  9637. taskType: WorkerTaskType.INIT
  9638. };
  9639. this._worker.postMessage(message);
  9640. };
  9641. CollisionCoordinatorWorker.prototype.destroy = function () {
  9642. this._scene.unregisterAfterRender(this._afterRender);
  9643. this._worker.terminate();
  9644. };
  9645. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9646. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9647. this.onMeshUpdated(mesh);
  9648. };
  9649. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9650. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9651. };
  9652. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9653. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9654. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9655. this.onGeometryUpdated(geometry);
  9656. };
  9657. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9658. this._toRemoveGeometryArray.push(geometry.id);
  9659. };
  9660. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9661. var submeshes = [];
  9662. if (mesh.subMeshes) {
  9663. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9664. return {
  9665. position: idx,
  9666. verticesStart: sm.verticesStart,
  9667. verticesCount: sm.verticesCount,
  9668. indexStart: sm.indexStart,
  9669. indexCount: sm.indexCount,
  9670. hasMaterial: !!sm.getMaterial(),
  9671. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9672. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9673. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9674. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9675. };
  9676. });
  9677. }
  9678. var geometryId = null;
  9679. if (mesh instanceof BABYLON.Mesh) {
  9680. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9681. }
  9682. else if (mesh instanceof BABYLON.InstancedMesh) {
  9683. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9684. }
  9685. return {
  9686. uniqueId: mesh.uniqueId,
  9687. id: mesh.id,
  9688. name: mesh.name,
  9689. geometryId: geometryId,
  9690. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9691. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9692. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9693. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9694. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9695. subMeshes: submeshes,
  9696. checkCollisions: mesh.checkCollisions
  9697. };
  9698. };
  9699. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9700. return {
  9701. id: geometry.id,
  9702. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9703. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9704. indices: new Int32Array(geometry.getIndices() || []),
  9705. };
  9706. };
  9707. return CollisionCoordinatorWorker;
  9708. })();
  9709. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9710. var CollisionCoordinatorLegacy = (function () {
  9711. function CollisionCoordinatorLegacy() {
  9712. this._scaledPosition = BABYLON.Vector3.Zero();
  9713. this._scaledVelocity = BABYLON.Vector3.Zero();
  9714. this._finalPosition = BABYLON.Vector3.Zero();
  9715. }
  9716. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9717. position.divideToRef(collider.radius, this._scaledPosition);
  9718. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9719. collider.collidedMesh = null;
  9720. collider.retry = 0;
  9721. collider.initialVelocity = this._scaledVelocity;
  9722. collider.initialPosition = this._scaledPosition;
  9723. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9724. this._finalPosition.multiplyInPlace(collider.radius);
  9725. //run the callback
  9726. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9727. };
  9728. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9729. this._scene = scene;
  9730. };
  9731. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9732. //Legacy need no destruction method.
  9733. };
  9734. //No update in legacy mode
  9735. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9736. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9737. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9738. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9739. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9740. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9741. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9742. if (excludedMesh === void 0) { excludedMesh = null; }
  9743. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9744. if (collider.retry >= maximumRetry) {
  9745. finalPosition.copyFrom(position);
  9746. return;
  9747. }
  9748. collider._initialize(position, velocity, closeDistance);
  9749. // Check all meshes
  9750. for (var index = 0; index < this._scene.meshes.length; index++) {
  9751. var mesh = this._scene.meshes[index];
  9752. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9753. mesh._checkCollision(collider);
  9754. }
  9755. }
  9756. if (!collider.collisionFound) {
  9757. position.addToRef(velocity, finalPosition);
  9758. return;
  9759. }
  9760. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9761. collider._getResponse(position, velocity);
  9762. }
  9763. if (velocity.length() <= closeDistance) {
  9764. finalPosition.copyFrom(position);
  9765. return;
  9766. }
  9767. collider.retry++;
  9768. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9769. };
  9770. return CollisionCoordinatorLegacy;
  9771. })();
  9772. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9773. })(BABYLON || (BABYLON = {}));
  9774. var BABYLON;
  9775. (function (BABYLON) {
  9776. var VRCameraMetrics = (function () {
  9777. function VRCameraMetrics() {
  9778. this.compensateDistorsion = true;
  9779. }
  9780. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9781. get: function () {
  9782. return this.hResolution / (2 * this.vResolution);
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9788. get: function () {
  9789. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9790. },
  9791. enumerable: true,
  9792. configurable: true
  9793. });
  9794. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9795. get: function () {
  9796. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9797. var h = (4 * meters) / this.hScreenSize;
  9798. return BABYLON.Matrix.Translation(h, 0, 0);
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9804. get: function () {
  9805. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9806. var h = (4 * meters) / this.hScreenSize;
  9807. return BABYLON.Matrix.Translation(-h, 0, 0);
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9813. get: function () {
  9814. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9820. get: function () {
  9821. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. VRCameraMetrics.GetDefault = function () {
  9827. var result = new VRCameraMetrics();
  9828. result.hResolution = 1280;
  9829. result.vResolution = 800;
  9830. result.hScreenSize = 0.149759993;
  9831. result.vScreenSize = 0.0935999975;
  9832. result.vScreenCenter = 0.0467999987,
  9833. result.eyeToScreenDistance = 0.0410000011;
  9834. result.lensSeparationDistance = 0.0635000020;
  9835. result.interpupillaryDistance = 0.0640000030;
  9836. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9837. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9838. result.postProcessScaleFactor = 1.714605507808412;
  9839. result.lensCenterOffset = 0.151976421;
  9840. return result;
  9841. };
  9842. return VRCameraMetrics;
  9843. })();
  9844. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9845. var Camera = (function (_super) {
  9846. __extends(Camera, _super);
  9847. function Camera(name, position, scene) {
  9848. _super.call(this, name, scene);
  9849. this.position = position;
  9850. // Members
  9851. this.upVector = BABYLON.Vector3.Up();
  9852. this.orthoLeft = null;
  9853. this.orthoRight = null;
  9854. this.orthoBottom = null;
  9855. this.orthoTop = null;
  9856. this.fov = 0.8;
  9857. this.minZ = 1.0;
  9858. this.maxZ = 10000.0;
  9859. this.inertia = 0.9;
  9860. this.mode = Camera.PERSPECTIVE_CAMERA;
  9861. this.isIntermediate = false;
  9862. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9863. this.layerMask = 0x0FFFFFFF;
  9864. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9865. // Camera rig members
  9866. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9867. this._rigCameras = new Array();
  9868. // Cache
  9869. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9870. this._projectionMatrix = new BABYLON.Matrix();
  9871. this._postProcesses = new Array();
  9872. this._postProcessesTakenIndices = [];
  9873. this._activeMeshes = new BABYLON.SmartArray(256);
  9874. this._globalPosition = BABYLON.Vector3.Zero();
  9875. scene.addCamera(this);
  9876. if (!scene.activeCamera) {
  9877. scene.activeCamera = this;
  9878. }
  9879. }
  9880. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9881. get: function () {
  9882. return Camera._PERSPECTIVE_CAMERA;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9888. get: function () {
  9889. return Camera._ORTHOGRAPHIC_CAMERA;
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9895. get: function () {
  9896. return Camera._FOVMODE_VERTICAL_FIXED;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9902. get: function () {
  9903. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9904. },
  9905. enumerable: true,
  9906. configurable: true
  9907. });
  9908. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9909. get: function () {
  9910. return Camera._RIG_MODE_NONE;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9916. get: function () {
  9917. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9918. },
  9919. enumerable: true,
  9920. configurable: true
  9921. });
  9922. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9923. get: function () {
  9924. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9930. get: function () {
  9931. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9932. },
  9933. enumerable: true,
  9934. configurable: true
  9935. });
  9936. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9937. get: function () {
  9938. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9944. get: function () {
  9945. return Camera._RIG_MODE_VR;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Camera.prototype, "globalPosition", {
  9951. get: function () {
  9952. return this._globalPosition;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Camera.prototype.getActiveMeshes = function () {
  9958. return this._activeMeshes;
  9959. };
  9960. Camera.prototype.isActiveMesh = function (mesh) {
  9961. return (this._activeMeshes.indexOf(mesh) !== -1);
  9962. };
  9963. //Cache
  9964. Camera.prototype._initCache = function () {
  9965. _super.prototype._initCache.call(this);
  9966. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9967. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9968. this._cache.mode = undefined;
  9969. this._cache.minZ = undefined;
  9970. this._cache.maxZ = undefined;
  9971. this._cache.fov = undefined;
  9972. this._cache.aspectRatio = undefined;
  9973. this._cache.orthoLeft = undefined;
  9974. this._cache.orthoRight = undefined;
  9975. this._cache.orthoBottom = undefined;
  9976. this._cache.orthoTop = undefined;
  9977. this._cache.renderWidth = undefined;
  9978. this._cache.renderHeight = undefined;
  9979. };
  9980. Camera.prototype._updateCache = function (ignoreParentClass) {
  9981. if (!ignoreParentClass) {
  9982. _super.prototype._updateCache.call(this);
  9983. }
  9984. var engine = this.getEngine();
  9985. this._cache.position.copyFrom(this.position);
  9986. this._cache.upVector.copyFrom(this.upVector);
  9987. this._cache.mode = this.mode;
  9988. this._cache.minZ = this.minZ;
  9989. this._cache.maxZ = this.maxZ;
  9990. this._cache.fov = this.fov;
  9991. this._cache.aspectRatio = engine.getAspectRatio(this);
  9992. this._cache.orthoLeft = this.orthoLeft;
  9993. this._cache.orthoRight = this.orthoRight;
  9994. this._cache.orthoBottom = this.orthoBottom;
  9995. this._cache.orthoTop = this.orthoTop;
  9996. this._cache.renderWidth = engine.getRenderWidth();
  9997. this._cache.renderHeight = engine.getRenderHeight();
  9998. };
  9999. Camera.prototype._updateFromScene = function () {
  10000. this.updateCache();
  10001. this._update();
  10002. };
  10003. // Synchronized
  10004. Camera.prototype._isSynchronized = function () {
  10005. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10006. };
  10007. Camera.prototype._isSynchronizedViewMatrix = function () {
  10008. if (!_super.prototype._isSynchronized.call(this))
  10009. return false;
  10010. return this._cache.position.equals(this.position)
  10011. && this._cache.upVector.equals(this.upVector)
  10012. && this.isSynchronizedWithParent();
  10013. };
  10014. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10015. var check = this._cache.mode === this.mode
  10016. && this._cache.minZ === this.minZ
  10017. && this._cache.maxZ === this.maxZ;
  10018. if (!check) {
  10019. return false;
  10020. }
  10021. var engine = this.getEngine();
  10022. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10023. check = this._cache.fov === this.fov
  10024. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10025. }
  10026. else {
  10027. check = this._cache.orthoLeft === this.orthoLeft
  10028. && this._cache.orthoRight === this.orthoRight
  10029. && this._cache.orthoBottom === this.orthoBottom
  10030. && this._cache.orthoTop === this.orthoTop
  10031. && this._cache.renderWidth === engine.getRenderWidth()
  10032. && this._cache.renderHeight === engine.getRenderHeight();
  10033. }
  10034. return check;
  10035. };
  10036. // Controls
  10037. Camera.prototype.attachControl = function (element) {
  10038. };
  10039. Camera.prototype.detachControl = function (element) {
  10040. };
  10041. Camera.prototype._update = function () {
  10042. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10043. this._updateRigCameras();
  10044. }
  10045. this._checkInputs();
  10046. };
  10047. Camera.prototype._checkInputs = function () {
  10048. };
  10049. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10050. if (insertAt === void 0) { insertAt = null; }
  10051. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10052. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10053. return 0;
  10054. }
  10055. if (insertAt == null || insertAt < 0) {
  10056. this._postProcesses.push(postProcess);
  10057. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10058. return this._postProcesses.length - 1;
  10059. }
  10060. var add = 0;
  10061. if (this._postProcesses[insertAt]) {
  10062. var start = this._postProcesses.length - 1;
  10063. for (var i = start; i >= insertAt + 1; --i) {
  10064. this._postProcesses[i + 1] = this._postProcesses[i];
  10065. }
  10066. add = 1;
  10067. }
  10068. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10069. if (this._postProcessesTakenIndices[i] < insertAt) {
  10070. continue;
  10071. }
  10072. start = this._postProcessesTakenIndices.length - 1;
  10073. for (var j = start; j >= i; --j) {
  10074. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10075. }
  10076. this._postProcessesTakenIndices[i] = insertAt;
  10077. break;
  10078. }
  10079. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10080. this._postProcessesTakenIndices.push(insertAt);
  10081. }
  10082. var result = insertAt + add;
  10083. this._postProcesses[result] = postProcess;
  10084. return result;
  10085. };
  10086. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10087. if (atIndices === void 0) { atIndices = null; }
  10088. var result = [];
  10089. if (!atIndices) {
  10090. var length = this._postProcesses.length;
  10091. for (var i = 0; i < length; i++) {
  10092. if (this._postProcesses[i] !== postProcess) {
  10093. continue;
  10094. }
  10095. delete this._postProcesses[i];
  10096. var index = this._postProcessesTakenIndices.indexOf(i);
  10097. this._postProcessesTakenIndices.splice(index, 1);
  10098. }
  10099. }
  10100. else {
  10101. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10102. for (i = 0; i < atIndices.length; i++) {
  10103. var foundPostProcess = this._postProcesses[atIndices[i]];
  10104. if (foundPostProcess !== postProcess) {
  10105. result.push(i);
  10106. continue;
  10107. }
  10108. delete this._postProcesses[atIndices[i]];
  10109. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10110. this._postProcessesTakenIndices.splice(index, 1);
  10111. }
  10112. }
  10113. return result;
  10114. };
  10115. Camera.prototype.getWorldMatrix = function () {
  10116. if (!this._worldMatrix) {
  10117. this._worldMatrix = BABYLON.Matrix.Identity();
  10118. }
  10119. var viewMatrix = this.getViewMatrix();
  10120. viewMatrix.invertToRef(this._worldMatrix);
  10121. return this._worldMatrix;
  10122. };
  10123. Camera.prototype._getViewMatrix = function () {
  10124. return BABYLON.Matrix.Identity();
  10125. };
  10126. Camera.prototype.getViewMatrix = function (force) {
  10127. this._computedViewMatrix = this._computeViewMatrix(force);
  10128. if (!force && this._isSynchronizedViewMatrix()) {
  10129. return this._computedViewMatrix;
  10130. }
  10131. if (!this.parent || !this.parent.getWorldMatrix) {
  10132. this._globalPosition.copyFrom(this.position);
  10133. }
  10134. else {
  10135. if (!this._worldMatrix) {
  10136. this._worldMatrix = BABYLON.Matrix.Identity();
  10137. }
  10138. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10139. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10140. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10141. this._computedViewMatrix.invert();
  10142. this._markSyncedWithParent();
  10143. }
  10144. this._currentRenderId = this.getScene().getRenderId();
  10145. return this._computedViewMatrix;
  10146. };
  10147. Camera.prototype._computeViewMatrix = function (force) {
  10148. if (!force && this._isSynchronizedViewMatrix()) {
  10149. return this._computedViewMatrix;
  10150. }
  10151. this._computedViewMatrix = this._getViewMatrix();
  10152. this._currentRenderId = this.getScene().getRenderId();
  10153. return this._computedViewMatrix;
  10154. };
  10155. Camera.prototype.getProjectionMatrix = function (force) {
  10156. if (!force && this._isSynchronizedProjectionMatrix()) {
  10157. return this._projectionMatrix;
  10158. }
  10159. var engine = this.getEngine();
  10160. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10161. if (this.minZ <= 0) {
  10162. this.minZ = 0.1;
  10163. }
  10164. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10165. return this._projectionMatrix;
  10166. }
  10167. var halfWidth = engine.getRenderWidth() / 2.0;
  10168. var halfHeight = engine.getRenderHeight() / 2.0;
  10169. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10170. return this._projectionMatrix;
  10171. };
  10172. Camera.prototype.dispose = function () {
  10173. // Remove from scene
  10174. this.getScene().removeCamera(this);
  10175. while (this._rigCameras.length > 0) {
  10176. this._rigCameras.pop().dispose();
  10177. }
  10178. // Postprocesses
  10179. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10180. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10181. }
  10182. };
  10183. // ---- Camera rigs section ----
  10184. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10185. while (this._rigCameras.length > 0) {
  10186. this._rigCameras.pop().dispose();
  10187. }
  10188. this.cameraRigMode = mode;
  10189. this._cameraRigParams = {};
  10190. switch (this.cameraRigMode) {
  10191. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10192. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10193. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10194. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10195. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10196. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10197. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10198. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10199. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10200. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10201. break;
  10202. }
  10203. var postProcesses = new Array();
  10204. switch (this.cameraRigMode) {
  10205. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10206. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10207. this._rigCameras[0].isIntermediate = true;
  10208. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10209. postProcesses[1].onApply = function (effect) {
  10210. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10211. };
  10212. break;
  10213. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10214. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10215. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10216. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10217. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10218. var secondCamIndex = 1 - firstCamIndex;
  10219. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10220. this._rigCameras[firstCamIndex].isIntermediate = true;
  10221. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10222. break;
  10223. case Camera.RIG_MODE_VR:
  10224. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10225. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10226. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10227. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10228. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10229. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10230. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10231. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10232. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10233. if (metrics.compensateDistorsion) {
  10234. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10235. }
  10236. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10237. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10238. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10239. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10240. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10241. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10242. if (metrics.compensateDistorsion) {
  10243. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10244. }
  10245. break;
  10246. }
  10247. this._update();
  10248. };
  10249. Camera.prototype._getVRProjectionMatrix = function () {
  10250. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10251. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10252. return this._projectionMatrix;
  10253. };
  10254. Camera.prototype.setCameraRigParameter = function (name, value) {
  10255. this._cameraRigParams[name] = value;
  10256. //provisionnally:
  10257. if (name === "interaxialDistance") {
  10258. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10259. }
  10260. };
  10261. /**
  10262. * May needs to be overridden by children so sub has required properties to be copied
  10263. */
  10264. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10265. return null;
  10266. };
  10267. /**
  10268. * May needs to be overridden by children
  10269. */
  10270. Camera.prototype._updateRigCameras = function () {
  10271. for (var i = 0; i < this._rigCameras.length; i++) {
  10272. this._rigCameras[i].minZ = this.minZ;
  10273. this._rigCameras[i].maxZ = this.maxZ;
  10274. this._rigCameras[i].fov = this.fov;
  10275. }
  10276. // only update viewport when ANAGLYPH
  10277. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10278. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10279. }
  10280. };
  10281. // Statics
  10282. Camera._PERSPECTIVE_CAMERA = 0;
  10283. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10284. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10285. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10286. Camera._RIG_MODE_NONE = 0;
  10287. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10288. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10289. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10290. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10291. Camera._RIG_MODE_VR = 20;
  10292. return Camera;
  10293. })(BABYLON.Node);
  10294. BABYLON.Camera = Camera;
  10295. })(BABYLON || (BABYLON = {}));
  10296. var BABYLON;
  10297. (function (BABYLON) {
  10298. var TargetCamera = (function (_super) {
  10299. __extends(TargetCamera, _super);
  10300. function TargetCamera(name, position, scene) {
  10301. _super.call(this, name, position, scene);
  10302. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10303. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10304. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10305. this.speed = 2.0;
  10306. this.noRotationConstraint = false;
  10307. this.lockedTarget = null;
  10308. this._currentTarget = BABYLON.Vector3.Zero();
  10309. this._viewMatrix = BABYLON.Matrix.Zero();
  10310. this._camMatrix = BABYLON.Matrix.Zero();
  10311. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10312. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10313. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10314. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10315. this._lookAtTemp = BABYLON.Matrix.Zero();
  10316. this._tempMatrix = BABYLON.Matrix.Zero();
  10317. }
  10318. TargetCamera.prototype.getFrontPosition = function (distance) {
  10319. var direction = this.getTarget().subtract(this.position);
  10320. direction.normalize();
  10321. direction.scaleInPlace(distance);
  10322. return this.globalPosition.add(direction);
  10323. };
  10324. TargetCamera.prototype._getLockedTargetPosition = function () {
  10325. if (!this.lockedTarget) {
  10326. return null;
  10327. }
  10328. return this.lockedTarget.position || this.lockedTarget;
  10329. };
  10330. // Cache
  10331. TargetCamera.prototype._initCache = function () {
  10332. _super.prototype._initCache.call(this);
  10333. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10334. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10335. };
  10336. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10337. if (!ignoreParentClass) {
  10338. _super.prototype._updateCache.call(this);
  10339. }
  10340. var lockedTargetPosition = this._getLockedTargetPosition();
  10341. if (!lockedTargetPosition) {
  10342. this._cache.lockedTarget = null;
  10343. }
  10344. else {
  10345. if (!this._cache.lockedTarget) {
  10346. this._cache.lockedTarget = lockedTargetPosition.clone();
  10347. }
  10348. else {
  10349. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10350. }
  10351. }
  10352. this._cache.rotation.copyFrom(this.rotation);
  10353. };
  10354. // Synchronized
  10355. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10356. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10357. return false;
  10358. }
  10359. var lockedTargetPosition = this._getLockedTargetPosition();
  10360. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10361. && this._cache.rotation.equals(this.rotation);
  10362. };
  10363. // Methods
  10364. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10365. var engine = this.getEngine();
  10366. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10367. };
  10368. // Target
  10369. TargetCamera.prototype.setTarget = function (target) {
  10370. this.upVector.normalize();
  10371. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10372. this._camMatrix.invert();
  10373. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10374. var vDir = target.subtract(this.position);
  10375. if (vDir.x >= 0.0) {
  10376. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10377. }
  10378. else {
  10379. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10380. }
  10381. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10382. if (isNaN(this.rotation.x)) {
  10383. this.rotation.x = 0;
  10384. }
  10385. if (isNaN(this.rotation.y)) {
  10386. this.rotation.y = 0;
  10387. }
  10388. if (isNaN(this.rotation.z)) {
  10389. this.rotation.z = 0;
  10390. }
  10391. };
  10392. TargetCamera.prototype.getTarget = function () {
  10393. return this._currentTarget;
  10394. };
  10395. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10396. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10397. };
  10398. TargetCamera.prototype._updatePosition = function () {
  10399. this.position.addInPlace(this.cameraDirection);
  10400. };
  10401. TargetCamera.prototype._checkInputs = function () {
  10402. var needToMove = this._decideIfNeedsToMove();
  10403. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10404. // Move
  10405. if (needToMove) {
  10406. this._updatePosition();
  10407. }
  10408. // Rotate
  10409. if (needToRotate) {
  10410. this.rotation.x += this.cameraRotation.x;
  10411. this.rotation.y += this.cameraRotation.y;
  10412. if (!this.noRotationConstraint) {
  10413. var limit = (Math.PI / 2) * 0.95;
  10414. if (this.rotation.x > limit)
  10415. this.rotation.x = limit;
  10416. if (this.rotation.x < -limit)
  10417. this.rotation.x = -limit;
  10418. }
  10419. }
  10420. // Inertia
  10421. if (needToMove) {
  10422. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10423. this.cameraDirection.x = 0;
  10424. }
  10425. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10426. this.cameraDirection.y = 0;
  10427. }
  10428. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10429. this.cameraDirection.z = 0;
  10430. }
  10431. this.cameraDirection.scaleInPlace(this.inertia);
  10432. }
  10433. if (needToRotate) {
  10434. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10435. this.cameraRotation.x = 0;
  10436. }
  10437. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10438. this.cameraRotation.y = 0;
  10439. }
  10440. this.cameraRotation.scaleInPlace(this.inertia);
  10441. }
  10442. _super.prototype._checkInputs.call(this);
  10443. };
  10444. TargetCamera.prototype._getViewMatrix = function () {
  10445. if (!this.lockedTarget) {
  10446. // Compute
  10447. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10448. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10449. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10450. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10451. this._lookAtTemp.invert();
  10452. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10453. }
  10454. else {
  10455. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10456. }
  10457. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10458. // Computing target and final matrix
  10459. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10460. }
  10461. else {
  10462. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10463. }
  10464. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10465. return this._viewMatrix;
  10466. };
  10467. TargetCamera.prototype._getVRViewMatrix = function () {
  10468. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10469. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10470. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10471. // Computing target and final matrix
  10472. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10473. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10474. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10475. return this._viewMatrix;
  10476. };
  10477. /**
  10478. * @override
  10479. * Override Camera.createRigCamera
  10480. */
  10481. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10482. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10483. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10484. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10485. rigCamera._cameraRigParams = {};
  10486. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10487. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10488. }
  10489. return rigCamera;
  10490. }
  10491. return null;
  10492. };
  10493. /**
  10494. * @override
  10495. * Override Camera._updateRigCameras
  10496. */
  10497. TargetCamera.prototype._updateRigCameras = function () {
  10498. switch (this.cameraRigMode) {
  10499. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10500. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10501. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10503. case BABYLON.Camera.RIG_MODE_VR:
  10504. var camLeft = this._rigCameras[0];
  10505. var camRight = this._rigCameras[1];
  10506. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10507. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10508. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10509. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10510. camLeft.position.copyFrom(this.position);
  10511. camRight.position.copyFrom(this.position);
  10512. }
  10513. else {
  10514. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10515. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10516. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10517. camLeft.setTarget(this.getTarget());
  10518. camRight.setTarget(this.getTarget());
  10519. }
  10520. break;
  10521. }
  10522. _super.prototype._updateRigCameras.call(this);
  10523. };
  10524. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10525. if (!this._rigCamTransformMatrix) {
  10526. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10527. }
  10528. var target = this.getTarget();
  10529. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10530. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10531. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10532. };
  10533. return TargetCamera;
  10534. })(BABYLON.Camera);
  10535. BABYLON.TargetCamera = TargetCamera;
  10536. })(BABYLON || (BABYLON = {}));
  10537. var BABYLON;
  10538. (function (BABYLON) {
  10539. var FreeCamera = (function (_super) {
  10540. __extends(FreeCamera, _super);
  10541. function FreeCamera(name, position, scene) {
  10542. var _this = this;
  10543. _super.call(this, name, position, scene);
  10544. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10545. this.keysUp = [38];
  10546. this.keysDown = [40];
  10547. this.keysLeft = [37];
  10548. this.keysRight = [39];
  10549. this.checkCollisions = false;
  10550. this.applyGravity = false;
  10551. this.angularSensibility = 2000.0;
  10552. this._keys = [];
  10553. this._collider = new BABYLON.Collider();
  10554. this._needMoveForGravity = false;
  10555. this._oldPosition = BABYLON.Vector3.Zero();
  10556. this._diffPosition = BABYLON.Vector3.Zero();
  10557. this._newPosition = BABYLON.Vector3.Zero();
  10558. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10559. if (collidedMesh === void 0) { collidedMesh = null; }
  10560. //TODO move this to the collision coordinator!
  10561. if (_this.getScene().workerCollisions)
  10562. newPosition.multiplyInPlace(_this._collider.radius);
  10563. var updatePosition = function (newPos) {
  10564. _this._newPosition.copyFrom(newPos);
  10565. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10566. var oldPosition = _this.position.clone();
  10567. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10568. _this.position.addInPlace(_this._diffPosition);
  10569. if (_this.onCollide && collidedMesh) {
  10570. _this.onCollide(collidedMesh);
  10571. }
  10572. }
  10573. };
  10574. updatePosition(newPosition);
  10575. };
  10576. }
  10577. // Controls
  10578. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10579. var _this = this;
  10580. var previousPosition;
  10581. var engine = this.getEngine();
  10582. if (this._attachedElement) {
  10583. return;
  10584. }
  10585. this._attachedElement = element;
  10586. if (this._onMouseDown === undefined) {
  10587. this._onMouseDown = function (evt) {
  10588. previousPosition = {
  10589. x: evt.clientX,
  10590. y: evt.clientY
  10591. };
  10592. if (!noPreventDefault) {
  10593. evt.preventDefault();
  10594. }
  10595. };
  10596. this._onMouseUp = function (evt) {
  10597. previousPosition = null;
  10598. if (!noPreventDefault) {
  10599. evt.preventDefault();
  10600. }
  10601. };
  10602. this._onMouseOut = function (evt) {
  10603. previousPosition = null;
  10604. _this._keys = [];
  10605. if (!noPreventDefault) {
  10606. evt.preventDefault();
  10607. }
  10608. };
  10609. this._onMouseMove = function (evt) {
  10610. if (!previousPosition && !engine.isPointerLock) {
  10611. return;
  10612. }
  10613. var offsetX;
  10614. var offsetY;
  10615. if (!engine.isPointerLock) {
  10616. offsetX = evt.clientX - previousPosition.x;
  10617. offsetY = evt.clientY - previousPosition.y;
  10618. }
  10619. else {
  10620. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10621. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10622. }
  10623. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10624. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10625. previousPosition = {
  10626. x: evt.clientX,
  10627. y: evt.clientY
  10628. };
  10629. if (!noPreventDefault) {
  10630. evt.preventDefault();
  10631. }
  10632. };
  10633. this._onKeyDown = function (evt) {
  10634. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10635. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10636. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10637. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10638. var index = _this._keys.indexOf(evt.keyCode);
  10639. if (index === -1) {
  10640. _this._keys.push(evt.keyCode);
  10641. }
  10642. if (!noPreventDefault) {
  10643. evt.preventDefault();
  10644. }
  10645. }
  10646. };
  10647. this._onKeyUp = function (evt) {
  10648. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10649. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10650. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10651. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10652. var index = _this._keys.indexOf(evt.keyCode);
  10653. if (index >= 0) {
  10654. _this._keys.splice(index, 1);
  10655. }
  10656. if (!noPreventDefault) {
  10657. evt.preventDefault();
  10658. }
  10659. }
  10660. };
  10661. this._onLostFocus = function () {
  10662. _this._keys = [];
  10663. };
  10664. this._reset = function () {
  10665. _this._keys = [];
  10666. previousPosition = null;
  10667. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10668. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10669. };
  10670. }
  10671. element.addEventListener("mousedown", this._onMouseDown, false);
  10672. element.addEventListener("mouseup", this._onMouseUp, false);
  10673. element.addEventListener("mouseout", this._onMouseOut, false);
  10674. element.addEventListener("mousemove", this._onMouseMove, false);
  10675. BABYLON.Tools.RegisterTopRootEvents([
  10676. { name: "keydown", handler: this._onKeyDown },
  10677. { name: "keyup", handler: this._onKeyUp },
  10678. { name: "blur", handler: this._onLostFocus }
  10679. ]);
  10680. };
  10681. FreeCamera.prototype.detachControl = function (element) {
  10682. if (this._attachedElement != element) {
  10683. return;
  10684. }
  10685. element.removeEventListener("mousedown", this._onMouseDown);
  10686. element.removeEventListener("mouseup", this._onMouseUp);
  10687. element.removeEventListener("mouseout", this._onMouseOut);
  10688. element.removeEventListener("mousemove", this._onMouseMove);
  10689. BABYLON.Tools.UnregisterTopRootEvents([
  10690. { name: "keydown", handler: this._onKeyDown },
  10691. { name: "keyup", handler: this._onKeyUp },
  10692. { name: "blur", handler: this._onLostFocus }
  10693. ]);
  10694. this._attachedElement = null;
  10695. if (this._reset) {
  10696. this._reset();
  10697. }
  10698. };
  10699. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10700. var globalPosition;
  10701. if (this.parent) {
  10702. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10703. }
  10704. else {
  10705. globalPosition = this.position;
  10706. }
  10707. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10708. this._collider.radius = this.ellipsoid;
  10709. //add gravity to the velocity to prevent the dual-collision checking
  10710. if (this.applyGravity) {
  10711. velocity.addInPlace(this.getScene().gravity);
  10712. }
  10713. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10714. };
  10715. FreeCamera.prototype._checkInputs = function () {
  10716. if (!this._localDirection) {
  10717. this._localDirection = BABYLON.Vector3.Zero();
  10718. this._transformedDirection = BABYLON.Vector3.Zero();
  10719. }
  10720. // Keyboard
  10721. for (var index = 0; index < this._keys.length; index++) {
  10722. var keyCode = this._keys[index];
  10723. var speed = this._computeLocalCameraSpeed();
  10724. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10725. this._localDirection.copyFromFloats(-speed, 0, 0);
  10726. }
  10727. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10728. this._localDirection.copyFromFloats(0, 0, speed);
  10729. }
  10730. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10731. this._localDirection.copyFromFloats(speed, 0, 0);
  10732. }
  10733. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10734. this._localDirection.copyFromFloats(0, 0, -speed);
  10735. }
  10736. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10737. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10738. this.cameraDirection.addInPlace(this._transformedDirection);
  10739. }
  10740. _super.prototype._checkInputs.call(this);
  10741. };
  10742. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10743. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10744. };
  10745. FreeCamera.prototype._updatePosition = function () {
  10746. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10747. this._collideWithWorld(this.cameraDirection);
  10748. }
  10749. else {
  10750. this.position.addInPlace(this.cameraDirection);
  10751. }
  10752. };
  10753. return FreeCamera;
  10754. })(BABYLON.TargetCamera);
  10755. BABYLON.FreeCamera = FreeCamera;
  10756. })(BABYLON || (BABYLON = {}));
  10757. var BABYLON;
  10758. (function (BABYLON) {
  10759. var FollowCamera = (function (_super) {
  10760. __extends(FollowCamera, _super);
  10761. function FollowCamera(name, position, scene) {
  10762. _super.call(this, name, position, scene);
  10763. this.radius = 12;
  10764. this.rotationOffset = 0;
  10765. this.heightOffset = 4;
  10766. this.cameraAcceleration = 0.05;
  10767. this.maxCameraSpeed = 20;
  10768. }
  10769. FollowCamera.prototype.getRadians = function (degrees) {
  10770. return degrees * Math.PI / 180;
  10771. };
  10772. FollowCamera.prototype.follow = function (cameraTarget) {
  10773. if (!cameraTarget)
  10774. return;
  10775. var yRotation;
  10776. if (cameraTarget.rotationQuaternion) {
  10777. var rotMatrix = new BABYLON.Matrix();
  10778. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10779. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10780. }
  10781. else {
  10782. yRotation = cameraTarget.rotation.y;
  10783. }
  10784. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10785. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10786. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10787. var dx = targetX - this.position.x;
  10788. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10789. var dz = (targetZ) - this.position.z;
  10790. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10791. var vy = dy * this.cameraAcceleration;
  10792. var vz = dz * this.cameraAcceleration * 2;
  10793. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10794. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10795. }
  10796. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10797. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10798. }
  10799. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10800. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10801. }
  10802. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10803. this.setTarget(cameraTarget.position);
  10804. };
  10805. FollowCamera.prototype._checkInputs = function () {
  10806. _super.prototype._checkInputs.call(this);
  10807. this.follow(this.target);
  10808. };
  10809. return FollowCamera;
  10810. })(BABYLON.TargetCamera);
  10811. BABYLON.FollowCamera = FollowCamera;
  10812. var ArcFollowCamera = (function (_super) {
  10813. __extends(ArcFollowCamera, _super);
  10814. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10815. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10816. this.alpha = alpha;
  10817. this.beta = beta;
  10818. this.radius = radius;
  10819. this.target = target;
  10820. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10821. this.follow();
  10822. }
  10823. ArcFollowCamera.prototype.follow = function () {
  10824. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10825. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10826. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10827. this.position = this.target.position.add(this._cartesianCoordinates);
  10828. this.setTarget(this.target.position);
  10829. };
  10830. ArcFollowCamera.prototype._checkInputs = function () {
  10831. _super.prototype._checkInputs.call(this);
  10832. this.follow();
  10833. };
  10834. return ArcFollowCamera;
  10835. })(BABYLON.TargetCamera);
  10836. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10837. })(BABYLON || (BABYLON = {}));
  10838. var BABYLON;
  10839. (function (BABYLON) {
  10840. // We're mainly based on the logic defined into the FreeCamera code
  10841. var TouchCamera = (function (_super) {
  10842. __extends(TouchCamera, _super);
  10843. function TouchCamera(name, position, scene) {
  10844. _super.call(this, name, position, scene);
  10845. this._offsetX = null;
  10846. this._offsetY = null;
  10847. this._pointerCount = 0;
  10848. this._pointerPressed = [];
  10849. this.angularSensibility = 200000.0;
  10850. this.moveSensibility = 500.0;
  10851. }
  10852. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10853. var _this = this;
  10854. var previousPosition;
  10855. if (this._attachedCanvas) {
  10856. return;
  10857. }
  10858. this._attachedCanvas = canvas;
  10859. if (this._onPointerDown === undefined) {
  10860. this._onPointerDown = function (evt) {
  10861. if (!noPreventDefault) {
  10862. evt.preventDefault();
  10863. }
  10864. _this._pointerPressed.push(evt.pointerId);
  10865. if (_this._pointerPressed.length !== 1) {
  10866. return;
  10867. }
  10868. previousPosition = {
  10869. x: evt.clientX,
  10870. y: evt.clientY
  10871. };
  10872. };
  10873. this._onPointerUp = function (evt) {
  10874. if (!noPreventDefault) {
  10875. evt.preventDefault();
  10876. }
  10877. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10878. if (index === -1) {
  10879. return;
  10880. }
  10881. _this._pointerPressed.splice(index, 1);
  10882. if (index != 0) {
  10883. return;
  10884. }
  10885. previousPosition = null;
  10886. _this._offsetX = null;
  10887. _this._offsetY = null;
  10888. };
  10889. this._onPointerMove = function (evt) {
  10890. if (!noPreventDefault) {
  10891. evt.preventDefault();
  10892. }
  10893. if (!previousPosition) {
  10894. return;
  10895. }
  10896. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10897. if (index != 0) {
  10898. return;
  10899. }
  10900. _this._offsetX = evt.clientX - previousPosition.x;
  10901. _this._offsetY = -(evt.clientY - previousPosition.y);
  10902. };
  10903. this._onLostFocus = function () {
  10904. _this._offsetX = null;
  10905. _this._offsetY = null;
  10906. };
  10907. }
  10908. canvas.addEventListener("pointerdown", this._onPointerDown);
  10909. canvas.addEventListener("pointerup", this._onPointerUp);
  10910. canvas.addEventListener("pointerout", this._onPointerUp);
  10911. canvas.addEventListener("pointermove", this._onPointerMove);
  10912. BABYLON.Tools.RegisterTopRootEvents([
  10913. { name: "blur", handler: this._onLostFocus }
  10914. ]);
  10915. };
  10916. TouchCamera.prototype.detachControl = function (canvas) {
  10917. if (this._attachedCanvas != canvas) {
  10918. return;
  10919. }
  10920. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10921. canvas.removeEventListener("pointerup", this._onPointerUp);
  10922. canvas.removeEventListener("pointerout", this._onPointerUp);
  10923. canvas.removeEventListener("pointermove", this._onPointerMove);
  10924. BABYLON.Tools.UnregisterTopRootEvents([
  10925. { name: "blur", handler: this._onLostFocus }
  10926. ]);
  10927. this._attachedCanvas = null;
  10928. };
  10929. TouchCamera.prototype._checkInputs = function () {
  10930. if (this._offsetX) {
  10931. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10932. if (this._pointerPressed.length > 1) {
  10933. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10934. }
  10935. else {
  10936. var speed = this._computeLocalCameraSpeed();
  10937. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10938. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10939. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10940. }
  10941. }
  10942. _super.prototype._checkInputs.call(this);
  10943. };
  10944. return TouchCamera;
  10945. })(BABYLON.FreeCamera);
  10946. BABYLON.TouchCamera = TouchCamera;
  10947. })(BABYLON || (BABYLON = {}));
  10948. var BABYLON;
  10949. (function (BABYLON) {
  10950. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10951. var ArcRotateCamera = (function (_super) {
  10952. __extends(ArcRotateCamera, _super);
  10953. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10954. var _this = this;
  10955. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10956. this.alpha = alpha;
  10957. this.beta = beta;
  10958. this.radius = radius;
  10959. this.target = target;
  10960. this.inertialAlphaOffset = 0;
  10961. this.inertialBetaOffset = 0;
  10962. this.inertialRadiusOffset = 0;
  10963. this.lowerAlphaLimit = null;
  10964. this.upperAlphaLimit = null;
  10965. this.lowerBetaLimit = 0.01;
  10966. this.upperBetaLimit = Math.PI;
  10967. this.lowerRadiusLimit = null;
  10968. this.upperRadiusLimit = null;
  10969. this.angularSensibilityX = 1000.0;
  10970. this.angularSensibilityY = 1000.0;
  10971. this.wheelPrecision = 3.0;
  10972. this.pinchPrecision = 2.0;
  10973. this.panningSensibility = 50.0;
  10974. this.inertialPanningX = 0;
  10975. this.inertialPanningY = 0;
  10976. this.keysUp = [38];
  10977. this.keysDown = [40];
  10978. this.keysLeft = [37];
  10979. this.keysRight = [39];
  10980. this.zoomOnFactor = 1;
  10981. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10982. this.pinchInwards = true;
  10983. this.allowUpsideDown = true;
  10984. this._keys = [];
  10985. this._viewMatrix = new BABYLON.Matrix();
  10986. this._isRightClick = false;
  10987. this._isCtrlPushed = false;
  10988. this.checkCollisions = false;
  10989. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10990. this._collider = new BABYLON.Collider();
  10991. this._previousPosition = BABYLON.Vector3.Zero();
  10992. this._collisionVelocity = BABYLON.Vector3.Zero();
  10993. this._newPosition = BABYLON.Vector3.Zero();
  10994. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10995. if (collidedMesh === void 0) { collidedMesh = null; }
  10996. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10997. newPosition.multiplyInPlace(_this._collider.radius);
  10998. }
  10999. if (!collidedMesh) {
  11000. _this._previousPosition.copyFrom(_this.position);
  11001. }
  11002. else {
  11003. _this.setPosition(_this.position);
  11004. if (_this.onCollide) {
  11005. _this.onCollide(collidedMesh);
  11006. }
  11007. }
  11008. // Recompute because of constraints
  11009. var cosa = Math.cos(_this.alpha);
  11010. var sina = Math.sin(_this.alpha);
  11011. var cosb = Math.cos(_this.beta);
  11012. var sinb = Math.sin(_this.beta);
  11013. var target = _this._getTargetPosition();
  11014. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11015. _this.position.copyFrom(_this._newPosition);
  11016. var up = _this.upVector;
  11017. if (_this.allowUpsideDown && _this.beta < 0) {
  11018. var up = up.clone();
  11019. up = up.negate();
  11020. }
  11021. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11022. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11023. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11024. _this._collisionTriggered = false;
  11025. };
  11026. if (!this.target) {
  11027. this.target = BABYLON.Vector3.Zero();
  11028. }
  11029. this.getViewMatrix();
  11030. }
  11031. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11032. //deprecated angularSensibility support
  11033. get: function () {
  11034. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11035. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11036. },
  11037. //deprecated angularSensibility support
  11038. set: function (value) {
  11039. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11040. this.angularSensibilityX = value;
  11041. this.angularSensibilityY = value;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. ArcRotateCamera.prototype._getTargetPosition = function () {
  11047. return this.target.position || this.target;
  11048. };
  11049. // Cache
  11050. ArcRotateCamera.prototype._initCache = function () {
  11051. _super.prototype._initCache.call(this);
  11052. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11053. this._cache.alpha = undefined;
  11054. this._cache.beta = undefined;
  11055. this._cache.radius = undefined;
  11056. this._cache.targetScreenOffset = undefined;
  11057. };
  11058. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11059. if (!ignoreParentClass) {
  11060. _super.prototype._updateCache.call(this);
  11061. }
  11062. this._cache.target.copyFrom(this._getTargetPosition());
  11063. this._cache.alpha = this.alpha;
  11064. this._cache.beta = this.beta;
  11065. this._cache.radius = this.radius;
  11066. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11067. };
  11068. // Synchronized
  11069. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11070. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11071. return false;
  11072. return this._cache.target.equals(this._getTargetPosition())
  11073. && this._cache.alpha === this.alpha
  11074. && this._cache.beta === this.beta
  11075. && this._cache.radius === this.radius
  11076. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11077. };
  11078. // Methods
  11079. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11080. var _this = this;
  11081. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11082. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11083. var previousPinchDistance = 0;
  11084. var pointers = new BABYLON.SmartCollection();
  11085. if (this._attachedElement) {
  11086. return;
  11087. }
  11088. this._attachedElement = element;
  11089. var engine = this.getEngine();
  11090. if (this._onPointerDown === undefined) {
  11091. this._onPointerDown = function (evt) {
  11092. // Manage panning with right click
  11093. _this._isRightClick = evt.button === 2 ? true : false;
  11094. // manage pointers
  11095. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11096. cacheSoloPointer = pointers.item(evt.pointerId);
  11097. if (!noPreventDefault) {
  11098. evt.preventDefault();
  11099. }
  11100. };
  11101. this._onPointerUp = function (evt) {
  11102. cacheSoloPointer = null;
  11103. previousPinchDistance = 0;
  11104. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11105. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11106. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11107. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11108. pointers.empty();
  11109. if (!noPreventDefault) {
  11110. evt.preventDefault();
  11111. }
  11112. };
  11113. this._onContextMenu = function (evt) {
  11114. evt.preventDefault();
  11115. };
  11116. this._onPointerMove = function (evt) {
  11117. if (!noPreventDefault) {
  11118. evt.preventDefault();
  11119. }
  11120. switch (pointers.count) {
  11121. case 1:
  11122. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11123. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11124. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11125. }
  11126. else {
  11127. var offsetX = evt.clientX - cacheSoloPointer.x;
  11128. var offsetY = evt.clientY - cacheSoloPointer.y;
  11129. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11130. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11131. }
  11132. cacheSoloPointer.x = evt.clientX;
  11133. cacheSoloPointer.y = evt.clientY;
  11134. break;
  11135. case 2:
  11136. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11137. pointers.item(evt.pointerId).x = evt.clientX;
  11138. pointers.item(evt.pointerId).y = evt.clientY;
  11139. var direction = _this.pinchInwards ? 1 : -1;
  11140. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11141. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11142. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11143. if (previousPinchDistance === 0) {
  11144. previousPinchDistance = pinchSquaredDistance;
  11145. return;
  11146. }
  11147. if (pinchSquaredDistance !== previousPinchDistance) {
  11148. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11149. previousPinchDistance = pinchSquaredDistance;
  11150. }
  11151. break;
  11152. default:
  11153. if (pointers.item(evt.pointerId)) {
  11154. pointers.item(evt.pointerId).x = evt.clientX;
  11155. pointers.item(evt.pointerId).y = evt.clientY;
  11156. }
  11157. }
  11158. };
  11159. this._onMouseMove = function (evt) {
  11160. if (!engine.isPointerLock) {
  11161. return;
  11162. }
  11163. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11164. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11165. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11166. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11167. if (!noPreventDefault) {
  11168. evt.preventDefault();
  11169. }
  11170. };
  11171. this._wheel = function (event) {
  11172. var delta = 0;
  11173. if (event.wheelDelta) {
  11174. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11175. }
  11176. else if (event.detail) {
  11177. delta = -event.detail / _this.wheelPrecision;
  11178. }
  11179. if (delta)
  11180. _this.inertialRadiusOffset += delta;
  11181. if (event.preventDefault) {
  11182. if (!noPreventDefault) {
  11183. event.preventDefault();
  11184. }
  11185. }
  11186. };
  11187. this._onKeyDown = function (evt) {
  11188. _this._isCtrlPushed = evt.ctrlKey;
  11189. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11190. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11191. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11192. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11193. var index = _this._keys.indexOf(evt.keyCode);
  11194. if (index === -1) {
  11195. _this._keys.push(evt.keyCode);
  11196. }
  11197. if (evt.preventDefault) {
  11198. if (!noPreventDefault) {
  11199. evt.preventDefault();
  11200. }
  11201. }
  11202. }
  11203. };
  11204. this._onKeyUp = function (evt) {
  11205. _this._isCtrlPushed = evt.ctrlKey;
  11206. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11207. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11208. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11209. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11210. var index = _this._keys.indexOf(evt.keyCode);
  11211. if (index >= 0) {
  11212. _this._keys.splice(index, 1);
  11213. }
  11214. if (evt.preventDefault) {
  11215. if (!noPreventDefault) {
  11216. evt.preventDefault();
  11217. }
  11218. }
  11219. }
  11220. };
  11221. this._onLostFocus = function () {
  11222. _this._keys = [];
  11223. pointers.empty();
  11224. previousPinchDistance = 0;
  11225. cacheSoloPointer = null;
  11226. };
  11227. this._onGestureStart = function (e) {
  11228. if (window.MSGesture === undefined) {
  11229. return;
  11230. }
  11231. if (!_this._MSGestureHandler) {
  11232. _this._MSGestureHandler = new MSGesture();
  11233. _this._MSGestureHandler.target = element;
  11234. }
  11235. _this._MSGestureHandler.addPointer(e.pointerId);
  11236. };
  11237. this._onGesture = function (e) {
  11238. _this.radius *= e.scale;
  11239. if (e.preventDefault) {
  11240. if (!noPreventDefault) {
  11241. e.stopPropagation();
  11242. e.preventDefault();
  11243. }
  11244. }
  11245. };
  11246. this._reset = function () {
  11247. _this._keys = [];
  11248. _this.inertialAlphaOffset = 0;
  11249. _this.inertialBetaOffset = 0;
  11250. _this.inertialRadiusOffset = 0;
  11251. pointers.empty();
  11252. previousPinchDistance = 0;
  11253. cacheSoloPointer = null;
  11254. };
  11255. }
  11256. if (!useCtrlForPanning) {
  11257. element.addEventListener("contextmenu", this._onContextMenu, false);
  11258. }
  11259. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11260. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11261. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11262. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11263. element.addEventListener("mousemove", this._onMouseMove, false);
  11264. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11265. element.addEventListener("MSGestureChange", this._onGesture, false);
  11266. element.addEventListener('mousewheel', this._wheel, false);
  11267. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11268. BABYLON.Tools.RegisterTopRootEvents([
  11269. { name: "keydown", handler: this._onKeyDown },
  11270. { name: "keyup", handler: this._onKeyUp },
  11271. { name: "blur", handler: this._onLostFocus }
  11272. ]);
  11273. };
  11274. ArcRotateCamera.prototype.detachControl = function (element) {
  11275. if (this._attachedElement !== element) {
  11276. return;
  11277. }
  11278. element.removeEventListener("contextmenu", this._onContextMenu);
  11279. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11280. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11281. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11282. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11283. element.removeEventListener("mousemove", this._onMouseMove);
  11284. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11285. element.removeEventListener("MSGestureChange", this._onGesture);
  11286. element.removeEventListener('mousewheel', this._wheel);
  11287. element.removeEventListener('DOMMouseScroll', this._wheel);
  11288. BABYLON.Tools.UnregisterTopRootEvents([
  11289. { name: "keydown", handler: this._onKeyDown },
  11290. { name: "keyup", handler: this._onKeyUp },
  11291. { name: "blur", handler: this._onLostFocus }
  11292. ]);
  11293. this._MSGestureHandler = null;
  11294. this._attachedElement = null;
  11295. if (this._reset) {
  11296. this._reset();
  11297. }
  11298. };
  11299. ArcRotateCamera.prototype._checkInputs = function () {
  11300. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11301. if (this._collisionTriggered) {
  11302. return;
  11303. }
  11304. // Keyboard
  11305. for (var index = 0; index < this._keys.length; index++) {
  11306. var keyCode = this._keys[index];
  11307. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11308. this.inertialAlphaOffset -= 0.01;
  11309. }
  11310. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11311. this.inertialBetaOffset -= 0.01;
  11312. }
  11313. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11314. this.inertialAlphaOffset += 0.01;
  11315. }
  11316. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11317. this.inertialBetaOffset += 0.01;
  11318. }
  11319. }
  11320. // Inertia
  11321. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11322. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11323. this.beta += this.inertialBetaOffset;
  11324. this.radius -= this.inertialRadiusOffset;
  11325. this.inertialAlphaOffset *= this.inertia;
  11326. this.inertialBetaOffset *= this.inertia;
  11327. this.inertialRadiusOffset *= this.inertia;
  11328. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11329. this.inertialAlphaOffset = 0;
  11330. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11331. this.inertialBetaOffset = 0;
  11332. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11333. this.inertialRadiusOffset = 0;
  11334. }
  11335. // Panning inertia
  11336. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11337. if (!this._localDirection) {
  11338. this._localDirection = BABYLON.Vector3.Zero();
  11339. this._transformedDirection = BABYLON.Vector3.Zero();
  11340. }
  11341. this.inertialPanningX *= this.inertia;
  11342. this.inertialPanningY *= this.inertia;
  11343. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11344. this.inertialPanningX = 0;
  11345. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11346. this.inertialPanningY = 0;
  11347. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11348. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11349. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11350. this.target.addInPlace(this._transformedDirection);
  11351. }
  11352. // Limits
  11353. this._checkLimits();
  11354. _super.prototype._checkInputs.call(this);
  11355. };
  11356. ArcRotateCamera.prototype._checkLimits = function () {
  11357. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11358. if (this.allowUpsideDown && this.beta > Math.PI) {
  11359. this.beta = this.beta - (2 * Math.PI);
  11360. }
  11361. }
  11362. else {
  11363. if (this.beta < this.lowerBetaLimit) {
  11364. this.beta = this.lowerBetaLimit;
  11365. }
  11366. }
  11367. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11368. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11369. this.beta = this.beta + (2 * Math.PI);
  11370. }
  11371. }
  11372. else {
  11373. if (this.beta > this.upperBetaLimit) {
  11374. this.beta = this.upperBetaLimit;
  11375. }
  11376. }
  11377. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11378. this.alpha = this.lowerAlphaLimit;
  11379. }
  11380. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11381. this.alpha = this.upperAlphaLimit;
  11382. }
  11383. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11384. this.radius = this.lowerRadiusLimit;
  11385. }
  11386. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11387. this.radius = this.upperRadiusLimit;
  11388. }
  11389. };
  11390. ArcRotateCamera.prototype.setPosition = function (position) {
  11391. var radiusv3 = position.subtract(this._getTargetPosition());
  11392. this.radius = radiusv3.length();
  11393. // Alpha
  11394. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11395. if (radiusv3.z < 0) {
  11396. this.alpha = 2 * Math.PI - this.alpha;
  11397. }
  11398. // Beta
  11399. this.beta = Math.acos(radiusv3.y / this.radius);
  11400. this._checkLimits();
  11401. };
  11402. ArcRotateCamera.prototype.setTarget = function (target) {
  11403. this.target = target;
  11404. };
  11405. ArcRotateCamera.prototype._getViewMatrix = function () {
  11406. // Compute
  11407. var cosa = Math.cos(this.alpha);
  11408. var sina = Math.sin(this.alpha);
  11409. var cosb = Math.cos(this.beta);
  11410. var sinb = Math.sin(this.beta);
  11411. var target = this._getTargetPosition();
  11412. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11413. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11414. this._collider.radius = this.collisionRadius;
  11415. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11416. this._collisionTriggered = true;
  11417. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11418. }
  11419. else {
  11420. this.position.copyFrom(this._newPosition);
  11421. var up = this.upVector;
  11422. if (this.allowUpsideDown && this.beta < 0) {
  11423. var up = up.clone();
  11424. up = up.negate();
  11425. }
  11426. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11427. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11428. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11429. }
  11430. return this._viewMatrix;
  11431. };
  11432. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11433. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11434. meshes = meshes || this.getScene().meshes;
  11435. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11436. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11437. this.radius = distance * this.zoomOnFactor;
  11438. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11439. };
  11440. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11441. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11442. var meshesOrMinMaxVector;
  11443. var distance;
  11444. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11445. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11446. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11447. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11448. }
  11449. else {
  11450. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11451. distance = meshesOrMinMaxVectorAndDistance.distance;
  11452. }
  11453. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11454. if (!doNotUpdateMaxZ) {
  11455. this.maxZ = distance * 2;
  11456. }
  11457. };
  11458. /**
  11459. * @override
  11460. * Override Camera.createRigCamera
  11461. */
  11462. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11463. switch (this.cameraRigMode) {
  11464. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11465. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11466. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11467. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11468. case BABYLON.Camera.RIG_MODE_VR:
  11469. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11470. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11471. }
  11472. };
  11473. /**
  11474. * @override
  11475. * Override Camera._updateRigCameras
  11476. */
  11477. ArcRotateCamera.prototype._updateRigCameras = function () {
  11478. switch (this.cameraRigMode) {
  11479. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11480. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11481. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11482. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11483. case BABYLON.Camera.RIG_MODE_VR:
  11484. var camLeft = this._rigCameras[0];
  11485. var camRight = this._rigCameras[1];
  11486. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11487. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11488. camLeft.beta = camRight.beta = this.beta;
  11489. camLeft.radius = camRight.radius = this.radius;
  11490. break;
  11491. }
  11492. _super.prototype._updateRigCameras.call(this);
  11493. };
  11494. return ArcRotateCamera;
  11495. })(BABYLON.TargetCamera);
  11496. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11497. })(BABYLON || (BABYLON = {}));
  11498. var BABYLON;
  11499. (function (BABYLON) {
  11500. // We're mainly based on the logic defined into the FreeCamera code
  11501. var DeviceOrientationCamera = (function (_super) {
  11502. __extends(DeviceOrientationCamera, _super);
  11503. function DeviceOrientationCamera(name, position, scene) {
  11504. var _this = this;
  11505. _super.call(this, name, position, scene);
  11506. this._offsetX = null;
  11507. this._offsetY = null;
  11508. this._orientationGamma = 0;
  11509. this._orientationBeta = 0;
  11510. this._initialOrientationGamma = 0;
  11511. this._initialOrientationBeta = 0;
  11512. this.angularSensibility = 10000.0;
  11513. this.moveSensibility = 50.0;
  11514. window.addEventListener("resize", function () {
  11515. _this._initialOrientationGamma = null;
  11516. }, false);
  11517. }
  11518. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11519. var _this = this;
  11520. if (this._attachedCanvas) {
  11521. return;
  11522. }
  11523. this._attachedCanvas = canvas;
  11524. if (!this._orientationChanged) {
  11525. this._orientationChanged = function (evt) {
  11526. if (!_this._initialOrientationGamma) {
  11527. _this._initialOrientationGamma = evt.gamma;
  11528. _this._initialOrientationBeta = evt.beta;
  11529. }
  11530. _this._orientationGamma = evt.gamma;
  11531. _this._orientationBeta = evt.beta;
  11532. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11533. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11534. };
  11535. }
  11536. window.addEventListener("deviceorientation", this._orientationChanged);
  11537. };
  11538. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11539. if (this._attachedCanvas != canvas) {
  11540. return;
  11541. }
  11542. window.removeEventListener("deviceorientation", this._orientationChanged);
  11543. this._attachedCanvas = null;
  11544. this._orientationGamma = 0;
  11545. this._orientationBeta = 0;
  11546. this._initialOrientationGamma = 0;
  11547. this._initialOrientationBeta = 0;
  11548. };
  11549. DeviceOrientationCamera.prototype._checkInputs = function () {
  11550. if (!this._offsetX) {
  11551. return;
  11552. }
  11553. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11554. var speed = this._computeLocalCameraSpeed();
  11555. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11556. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11557. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11558. _super.prototype._checkInputs.call(this);
  11559. };
  11560. return DeviceOrientationCamera;
  11561. })(BABYLON.FreeCamera);
  11562. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11563. })(BABYLON || (BABYLON = {}));
  11564. var BABYLON;
  11565. (function (BABYLON) {
  11566. var Gamepads = (function () {
  11567. function Gamepads(ongamedpadconnected) {
  11568. var _this = this;
  11569. this.babylonGamepads = [];
  11570. this.oneGamepadConnected = false;
  11571. this.isMonitoring = false;
  11572. this.gamepadEventSupported = 'GamepadEvent' in window;
  11573. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11574. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11575. 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=";
  11576. this._callbackGamepadConnected = ongamedpadconnected;
  11577. if (this.gamepadSupportAvailable) {
  11578. // Checking if the gamepad connected event is supported (like in Firefox)
  11579. if (this.gamepadEventSupported) {
  11580. window.addEventListener('gamepadconnected', function (evt) {
  11581. _this._onGamepadConnected(evt);
  11582. }, false);
  11583. window.addEventListener('gamepaddisconnected', function (evt) {
  11584. _this._onGamepadDisconnected(evt);
  11585. }, false);
  11586. }
  11587. else {
  11588. this._startMonitoringGamepads();
  11589. }
  11590. if (!this.oneGamepadConnected) {
  11591. this._insertGamepadDOMInstructions();
  11592. }
  11593. }
  11594. else {
  11595. this._insertGamepadDOMNotSupported();
  11596. }
  11597. }
  11598. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11599. Gamepads.gamepadDOMInfo = document.createElement("div");
  11600. var buttonAImage = document.createElement("img");
  11601. buttonAImage.src = this.buttonADataURL;
  11602. var spanMessage = document.createElement("span");
  11603. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11604. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11605. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11606. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11607. Gamepads.gamepadDOMInfo.style.width = "100%";
  11608. Gamepads.gamepadDOMInfo.style.height = "48px";
  11609. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11610. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11611. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11612. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11613. buttonAImage.style.position = "relative";
  11614. buttonAImage.style.bottom = "8px";
  11615. spanMessage.style.position = "relative";
  11616. spanMessage.style.fontSize = "32px";
  11617. spanMessage.style.bottom = "32px";
  11618. spanMessage.style.color = "green";
  11619. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11620. };
  11621. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11622. Gamepads.gamepadDOMInfo = document.createElement("div");
  11623. var spanMessage = document.createElement("span");
  11624. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11625. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11626. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11627. Gamepads.gamepadDOMInfo.style.width = "100%";
  11628. Gamepads.gamepadDOMInfo.style.height = "40px";
  11629. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11630. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11631. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11632. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11633. spanMessage.style.position = "relative";
  11634. spanMessage.style.fontSize = "32px";
  11635. spanMessage.style.color = "red";
  11636. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11637. };
  11638. Gamepads.prototype.dispose = function () {
  11639. if (Gamepads.gamepadDOMInfo) {
  11640. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11641. }
  11642. };
  11643. Gamepads.prototype._onGamepadConnected = function (evt) {
  11644. var newGamepad = this._addNewGamepad(evt.gamepad);
  11645. if (this._callbackGamepadConnected)
  11646. this._callbackGamepadConnected(newGamepad);
  11647. this._startMonitoringGamepads();
  11648. };
  11649. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11650. if (!this.oneGamepadConnected) {
  11651. this.oneGamepadConnected = true;
  11652. if (Gamepads.gamepadDOMInfo) {
  11653. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11654. Gamepads.gamepadDOMInfo = null;
  11655. }
  11656. }
  11657. var newGamepad;
  11658. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11659. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11660. }
  11661. else {
  11662. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11663. }
  11664. this.babylonGamepads.push(newGamepad);
  11665. return newGamepad;
  11666. };
  11667. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11668. // Remove the gamepad from the list of gamepads to monitor.
  11669. for (var i in this.babylonGamepads) {
  11670. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11671. this.babylonGamepads.splice(i, 1);
  11672. break;
  11673. }
  11674. }
  11675. // If no gamepads are left, stop the polling loop.
  11676. if (this.babylonGamepads.length == 0) {
  11677. this._stopMonitoringGamepads();
  11678. }
  11679. };
  11680. Gamepads.prototype._startMonitoringGamepads = function () {
  11681. if (!this.isMonitoring) {
  11682. this.isMonitoring = true;
  11683. this._checkGamepadsStatus();
  11684. }
  11685. };
  11686. Gamepads.prototype._stopMonitoringGamepads = function () {
  11687. this.isMonitoring = false;
  11688. };
  11689. Gamepads.prototype._checkGamepadsStatus = function () {
  11690. var _this = this;
  11691. // updating gamepad objects
  11692. this._updateGamepadObjects();
  11693. for (var i in this.babylonGamepads) {
  11694. this.babylonGamepads[i].update();
  11695. }
  11696. if (this.isMonitoring) {
  11697. if (window.requestAnimationFrame) {
  11698. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11699. }
  11700. else if (window.mozRequestAnimationFrame) {
  11701. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11702. }
  11703. else if (window.webkitRequestAnimationFrame) {
  11704. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11705. }
  11706. }
  11707. };
  11708. // This function is called only on Chrome, which does not yet support
  11709. // connection/disconnection events, but requires you to monitor
  11710. // an array for changes.
  11711. Gamepads.prototype._updateGamepadObjects = function () {
  11712. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11713. for (var i = 0; i < gamepads.length; i++) {
  11714. if (gamepads[i]) {
  11715. if (!(gamepads[i].index in this.babylonGamepads)) {
  11716. var newGamepad = this._addNewGamepad(gamepads[i]);
  11717. if (this._callbackGamepadConnected) {
  11718. this._callbackGamepadConnected(newGamepad);
  11719. }
  11720. }
  11721. else {
  11722. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11723. }
  11724. }
  11725. }
  11726. };
  11727. return Gamepads;
  11728. })();
  11729. BABYLON.Gamepads = Gamepads;
  11730. var StickValues = (function () {
  11731. function StickValues(x, y) {
  11732. this.x = x;
  11733. this.y = y;
  11734. }
  11735. return StickValues;
  11736. })();
  11737. BABYLON.StickValues = StickValues;
  11738. var Gamepad = (function () {
  11739. function Gamepad(id, index, browserGamepad) {
  11740. this.id = id;
  11741. this.index = index;
  11742. this.browserGamepad = browserGamepad;
  11743. if (this.browserGamepad.axes.length >= 2) {
  11744. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11745. }
  11746. if (this.browserGamepad.axes.length >= 4) {
  11747. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11748. }
  11749. }
  11750. Gamepad.prototype.onleftstickchanged = function (callback) {
  11751. this._onleftstickchanged = callback;
  11752. };
  11753. Gamepad.prototype.onrightstickchanged = function (callback) {
  11754. this._onrightstickchanged = callback;
  11755. };
  11756. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11757. get: function () {
  11758. return this._leftStick;
  11759. },
  11760. set: function (newValues) {
  11761. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11762. this._onleftstickchanged(newValues);
  11763. }
  11764. this._leftStick = newValues;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11770. get: function () {
  11771. return this._rightStick;
  11772. },
  11773. set: function (newValues) {
  11774. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11775. this._onrightstickchanged(newValues);
  11776. }
  11777. this._rightStick = newValues;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Gamepad.prototype.update = function () {
  11783. if (this._leftStick) {
  11784. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11785. }
  11786. if (this._rightStick) {
  11787. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11788. }
  11789. };
  11790. return Gamepad;
  11791. })();
  11792. BABYLON.Gamepad = Gamepad;
  11793. var GenericPad = (function (_super) {
  11794. __extends(GenericPad, _super);
  11795. function GenericPad(id, index, gamepad) {
  11796. _super.call(this, id, index, gamepad);
  11797. this.id = id;
  11798. this.index = index;
  11799. this.gamepad = gamepad;
  11800. this._buttons = new Array(gamepad.buttons.length);
  11801. }
  11802. GenericPad.prototype.onbuttondown = function (callback) {
  11803. this._onbuttondown = callback;
  11804. };
  11805. GenericPad.prototype.onbuttonup = function (callback) {
  11806. this._onbuttonup = callback;
  11807. };
  11808. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11809. if (newValue !== currentValue) {
  11810. if (this._onbuttondown && newValue === 1) {
  11811. this._onbuttondown(buttonIndex);
  11812. }
  11813. if (this._onbuttonup && newValue === 0) {
  11814. this._onbuttonup(buttonIndex);
  11815. }
  11816. }
  11817. return newValue;
  11818. };
  11819. GenericPad.prototype.update = function () {
  11820. _super.prototype.update.call(this);
  11821. for (var index = 0; index < this._buttons.length; index++) {
  11822. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11823. }
  11824. };
  11825. return GenericPad;
  11826. })(Gamepad);
  11827. BABYLON.GenericPad = GenericPad;
  11828. (function (Xbox360Button) {
  11829. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11830. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11831. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11832. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11833. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11834. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11835. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11836. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11837. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11838. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11839. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11840. var Xbox360Button = BABYLON.Xbox360Button;
  11841. (function (Xbox360Dpad) {
  11842. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11843. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11844. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11845. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11846. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11847. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11848. var Xbox360Pad = (function (_super) {
  11849. __extends(Xbox360Pad, _super);
  11850. function Xbox360Pad() {
  11851. _super.apply(this, arguments);
  11852. this._leftTrigger = 0;
  11853. this._rightTrigger = 0;
  11854. this._buttonA = 0;
  11855. this._buttonB = 0;
  11856. this._buttonX = 0;
  11857. this._buttonY = 0;
  11858. this._buttonBack = 0;
  11859. this._buttonStart = 0;
  11860. this._buttonLB = 0;
  11861. this._buttonRB = 0;
  11862. this._buttonLeftStick = 0;
  11863. this._buttonRightStick = 0;
  11864. this._dPadUp = 0;
  11865. this._dPadDown = 0;
  11866. this._dPadLeft = 0;
  11867. this._dPadRight = 0;
  11868. }
  11869. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11870. this._onlefttriggerchanged = callback;
  11871. };
  11872. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11873. this._onrighttriggerchanged = callback;
  11874. };
  11875. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11876. get: function () {
  11877. return this._leftTrigger;
  11878. },
  11879. set: function (newValue) {
  11880. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11881. this._onlefttriggerchanged(newValue);
  11882. }
  11883. this._leftTrigger = newValue;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11889. get: function () {
  11890. return this._rightTrigger;
  11891. },
  11892. set: function (newValue) {
  11893. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11894. this._onrighttriggerchanged(newValue);
  11895. }
  11896. this._rightTrigger = newValue;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11902. this._onbuttondown = callback;
  11903. };
  11904. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11905. this._onbuttonup = callback;
  11906. };
  11907. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11908. this._ondpaddown = callback;
  11909. };
  11910. Xbox360Pad.prototype.ondpadup = function (callback) {
  11911. this._ondpadup = callback;
  11912. };
  11913. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11914. if (newValue !== currentValue) {
  11915. if (this._onbuttondown && newValue === 1) {
  11916. this._onbuttondown(buttonType);
  11917. }
  11918. if (this._onbuttonup && newValue === 0) {
  11919. this._onbuttonup(buttonType);
  11920. }
  11921. }
  11922. return newValue;
  11923. };
  11924. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11925. if (newValue !== currentValue) {
  11926. if (this._ondpaddown && newValue === 1) {
  11927. this._ondpaddown(buttonType);
  11928. }
  11929. if (this._ondpadup && newValue === 0) {
  11930. this._ondpadup(buttonType);
  11931. }
  11932. }
  11933. return newValue;
  11934. };
  11935. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11936. get: function () {
  11937. return this._buttonA;
  11938. },
  11939. set: function (value) {
  11940. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11946. get: function () {
  11947. return this._buttonB;
  11948. },
  11949. set: function (value) {
  11950. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11956. get: function () {
  11957. return this._buttonX;
  11958. },
  11959. set: function (value) {
  11960. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11966. get: function () {
  11967. return this._buttonY;
  11968. },
  11969. set: function (value) {
  11970. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11976. get: function () {
  11977. return this._buttonStart;
  11978. },
  11979. set: function (value) {
  11980. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11986. get: function () {
  11987. return this._buttonBack;
  11988. },
  11989. set: function (value) {
  11990. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11996. get: function () {
  11997. return this._buttonLB;
  11998. },
  11999. set: function (value) {
  12000. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12006. get: function () {
  12007. return this._buttonRB;
  12008. },
  12009. set: function (value) {
  12010. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12016. get: function () {
  12017. return this._buttonLeftStick;
  12018. },
  12019. set: function (value) {
  12020. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12026. get: function () {
  12027. return this._buttonRightStick;
  12028. },
  12029. set: function (value) {
  12030. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12036. get: function () {
  12037. return this._dPadUp;
  12038. },
  12039. set: function (value) {
  12040. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12046. get: function () {
  12047. return this._dPadDown;
  12048. },
  12049. set: function (value) {
  12050. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12056. get: function () {
  12057. return this._dPadLeft;
  12058. },
  12059. set: function (value) {
  12060. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12066. get: function () {
  12067. return this._dPadRight;
  12068. },
  12069. set: function (value) {
  12070. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12071. },
  12072. enumerable: true,
  12073. configurable: true
  12074. });
  12075. Xbox360Pad.prototype.update = function () {
  12076. _super.prototype.update.call(this);
  12077. this.buttonA = this.browserGamepad.buttons[0].value;
  12078. this.buttonB = this.browserGamepad.buttons[1].value;
  12079. this.buttonX = this.browserGamepad.buttons[2].value;
  12080. this.buttonY = this.browserGamepad.buttons[3].value;
  12081. this.buttonLB = this.browserGamepad.buttons[4].value;
  12082. this.buttonRB = this.browserGamepad.buttons[5].value;
  12083. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12084. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12085. this.buttonBack = this.browserGamepad.buttons[8].value;
  12086. this.buttonStart = this.browserGamepad.buttons[9].value;
  12087. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12088. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12089. this.dPadUp = this.browserGamepad.buttons[12].value;
  12090. this.dPadDown = this.browserGamepad.buttons[13].value;
  12091. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12092. this.dPadRight = this.browserGamepad.buttons[15].value;
  12093. };
  12094. return Xbox360Pad;
  12095. })(Gamepad);
  12096. BABYLON.Xbox360Pad = Xbox360Pad;
  12097. })(BABYLON || (BABYLON = {}));
  12098. var BABYLON;
  12099. (function (BABYLON) {
  12100. // We're mainly based on the logic defined into the FreeCamera code
  12101. var GamepadCamera = (function (_super) {
  12102. __extends(GamepadCamera, _super);
  12103. function GamepadCamera(name, position, scene) {
  12104. var _this = this;
  12105. _super.call(this, name, position, scene);
  12106. this.angularSensibility = 200;
  12107. this.moveSensibility = 75;
  12108. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12109. }
  12110. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12111. // Only the first gamepad can control the camera
  12112. if (gamepad.index === 0) {
  12113. this._gamepad = gamepad;
  12114. }
  12115. };
  12116. GamepadCamera.prototype._checkInputs = function () {
  12117. if (this._gamepad) {
  12118. var LSValues = this._gamepad.leftStick;
  12119. var normalizedLX = LSValues.x / this.moveSensibility;
  12120. var normalizedLY = LSValues.y / this.moveSensibility;
  12121. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12122. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12123. var RSValues = this._gamepad.rightStick;
  12124. var normalizedRX = RSValues.x / this.angularSensibility;
  12125. var normalizedRY = RSValues.y / this.angularSensibility;
  12126. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12127. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12128. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12129. var speed = this._computeLocalCameraSpeed() * 50.0;
  12130. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12131. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12132. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12133. }
  12134. _super.prototype._checkInputs.call(this);
  12135. };
  12136. GamepadCamera.prototype.dispose = function () {
  12137. this._gamepads.dispose();
  12138. _super.prototype.dispose.call(this);
  12139. };
  12140. return GamepadCamera;
  12141. })(BABYLON.FreeCamera);
  12142. BABYLON.GamepadCamera = GamepadCamera;
  12143. })(BABYLON || (BABYLON = {}));
  12144. var BABYLON;
  12145. (function (BABYLON) {
  12146. var RenderingManager = (function () {
  12147. function RenderingManager(scene) {
  12148. this._renderingGroups = new Array();
  12149. this._scene = scene;
  12150. }
  12151. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12152. if (this._scene._activeParticleSystems.length === 0) {
  12153. return;
  12154. }
  12155. // Particles
  12156. var activeCamera = this._scene.activeCamera;
  12157. var beforeParticlesDate = BABYLON.Tools.Now;
  12158. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12159. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12160. if (particleSystem.renderingGroupId !== index) {
  12161. continue;
  12162. }
  12163. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12164. continue;
  12165. }
  12166. this._clearDepthBuffer();
  12167. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12168. this._scene._activeParticles += particleSystem.render();
  12169. }
  12170. }
  12171. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12172. };
  12173. RenderingManager.prototype._renderSprites = function (index) {
  12174. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12175. return;
  12176. }
  12177. // Sprites
  12178. var activeCamera = this._scene.activeCamera;
  12179. var beforeSpritessDate = BABYLON.Tools.Now;
  12180. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12181. var spriteManager = this._scene.spriteManagers[id];
  12182. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12183. this._clearDepthBuffer();
  12184. spriteManager.render();
  12185. }
  12186. }
  12187. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12188. };
  12189. RenderingManager.prototype._clearDepthBuffer = function () {
  12190. if (this._depthBufferAlreadyCleaned) {
  12191. return;
  12192. }
  12193. this._scene.getEngine().clear(0, false, true);
  12194. this._depthBufferAlreadyCleaned = true;
  12195. };
  12196. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12197. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12198. this._depthBufferAlreadyCleaned = false;
  12199. var renderingGroup = this._renderingGroups[index];
  12200. var needToStepBack = false;
  12201. if (renderingGroup) {
  12202. this._clearDepthBuffer();
  12203. if (!renderingGroup.render(customRenderFunction)) {
  12204. this._renderingGroups.splice(index, 1);
  12205. needToStepBack = true;
  12206. }
  12207. }
  12208. if (renderSprites) {
  12209. this._renderSprites(index);
  12210. }
  12211. if (renderParticles) {
  12212. this._renderParticles(index, activeMeshes);
  12213. }
  12214. if (needToStepBack) {
  12215. index--;
  12216. }
  12217. }
  12218. };
  12219. RenderingManager.prototype.reset = function () {
  12220. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12221. if (renderingGroup) {
  12222. renderingGroup.prepare();
  12223. }
  12224. });
  12225. };
  12226. RenderingManager.prototype.dispatch = function (subMesh) {
  12227. var mesh = subMesh.getMesh();
  12228. var renderingGroupId = mesh.renderingGroupId || 0;
  12229. if (!this._renderingGroups[renderingGroupId]) {
  12230. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12231. }
  12232. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12233. };
  12234. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12235. return RenderingManager;
  12236. })();
  12237. BABYLON.RenderingManager = RenderingManager;
  12238. })(BABYLON || (BABYLON = {}));
  12239. var BABYLON;
  12240. (function (BABYLON) {
  12241. var RenderingGroup = (function () {
  12242. function RenderingGroup(index, scene) {
  12243. this.index = index;
  12244. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12245. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12246. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12247. this._scene = scene;
  12248. }
  12249. RenderingGroup.prototype.render = function (customRenderFunction) {
  12250. if (customRenderFunction) {
  12251. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12252. return true;
  12253. }
  12254. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12255. return false;
  12256. }
  12257. var engine = this._scene.getEngine();
  12258. // Opaque
  12259. var subIndex;
  12260. var submesh;
  12261. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12262. submesh = this._opaqueSubMeshes.data[subIndex];
  12263. submesh.render(false);
  12264. }
  12265. // Alpha test
  12266. engine.setAlphaTesting(true);
  12267. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12268. submesh = this._alphaTestSubMeshes.data[subIndex];
  12269. submesh.render(false);
  12270. }
  12271. engine.setAlphaTesting(false);
  12272. // Transparent
  12273. if (this._transparentSubMeshes.length) {
  12274. // Sorting
  12275. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12276. submesh = this._transparentSubMeshes.data[subIndex];
  12277. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12278. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12279. }
  12280. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12281. sortedArray.sort(function (a, b) {
  12282. // Alpha index first
  12283. if (a._alphaIndex > b._alphaIndex) {
  12284. return 1;
  12285. }
  12286. if (a._alphaIndex < b._alphaIndex) {
  12287. return -1;
  12288. }
  12289. // Then distance to camera
  12290. if (a._distanceToCamera < b._distanceToCamera) {
  12291. return 1;
  12292. }
  12293. if (a._distanceToCamera > b._distanceToCamera) {
  12294. return -1;
  12295. }
  12296. return 0;
  12297. });
  12298. // Rendering
  12299. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12300. submesh = sortedArray[subIndex];
  12301. submesh.render(true);
  12302. }
  12303. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12304. }
  12305. return true;
  12306. };
  12307. RenderingGroup.prototype.prepare = function () {
  12308. this._opaqueSubMeshes.reset();
  12309. this._transparentSubMeshes.reset();
  12310. this._alphaTestSubMeshes.reset();
  12311. };
  12312. RenderingGroup.prototype.dispatch = function (subMesh) {
  12313. var material = subMesh.getMaterial();
  12314. var mesh = subMesh.getMesh();
  12315. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12316. this._transparentSubMeshes.push(subMesh);
  12317. }
  12318. else if (material.needAlphaTesting()) {
  12319. this._alphaTestSubMeshes.push(subMesh);
  12320. }
  12321. else {
  12322. this._opaqueSubMeshes.push(subMesh); // Opaque
  12323. }
  12324. };
  12325. return RenderingGroup;
  12326. })();
  12327. BABYLON.RenderingGroup = RenderingGroup;
  12328. })(BABYLON || (BABYLON = {}));
  12329. var BABYLON;
  12330. (function (BABYLON) {
  12331. /**
  12332. * Represents a scene to be rendered by the engine.
  12333. * @see http://doc.babylonjs.com/page.php?p=21911
  12334. */
  12335. var Scene = (function () {
  12336. /**
  12337. * @constructor
  12338. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12339. */
  12340. function Scene(engine) {
  12341. // Members
  12342. this.autoClear = true;
  12343. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12344. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12345. this.forceWireframe = false;
  12346. this.forcePointsCloud = false;
  12347. this.forceShowBoundingBoxes = false;
  12348. this.animationsEnabled = true;
  12349. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  12350. // Fog
  12351. /**
  12352. * is fog enabled on this scene.
  12353. * @type {boolean}
  12354. */
  12355. this.fogEnabled = true;
  12356. this.fogMode = Scene.FOGMODE_NONE;
  12357. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12358. this.fogDensity = 0.1;
  12359. this.fogStart = 0;
  12360. this.fogEnd = 1000.0;
  12361. // Lights
  12362. /**
  12363. * is shadow enabled on this scene.
  12364. * @type {boolean}
  12365. */
  12366. this.shadowsEnabled = true;
  12367. /**
  12368. * is light enabled on this scene.
  12369. * @type {boolean}
  12370. */
  12371. this.lightsEnabled = true;
  12372. /**
  12373. * All of the lights added to this scene.
  12374. * @see BABYLON.Light
  12375. * @type {BABYLON.Light[]}
  12376. */
  12377. this.lights = new Array();
  12378. // Cameras
  12379. /**
  12380. * All of the cameras added to this scene.
  12381. * @see BABYLON.Camera
  12382. * @type {BABYLON.Camera[]}
  12383. */
  12384. this.cameras = new Array();
  12385. this.activeCameras = new Array();
  12386. // Meshes
  12387. /**
  12388. * All of the (abstract) meshes added to this scene.
  12389. * @see BABYLON.AbstractMesh
  12390. * @type {BABYLON.AbstractMesh[]}
  12391. */
  12392. this.meshes = new Array();
  12393. // Geometries
  12394. this._geometries = new Array();
  12395. this.materials = new Array();
  12396. this.multiMaterials = new Array();
  12397. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12398. // Textures
  12399. this.texturesEnabled = true;
  12400. this.textures = new Array();
  12401. // Particles
  12402. this.particlesEnabled = true;
  12403. this.particleSystems = new Array();
  12404. // Sprites
  12405. this.spritesEnabled = true;
  12406. this.spriteManagers = new Array();
  12407. // Layers
  12408. this.layers = new Array();
  12409. // Skeletons
  12410. this.skeletonsEnabled = true;
  12411. this.skeletons = new Array();
  12412. // Lens flares
  12413. this.lensFlaresEnabled = true;
  12414. this.lensFlareSystems = new Array();
  12415. // Collisions
  12416. this.collisionsEnabled = true;
  12417. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12418. // Postprocesses
  12419. this.postProcessesEnabled = true;
  12420. // Customs render targets
  12421. this.renderTargetsEnabled = true;
  12422. this.dumpNextRenderTargets = false;
  12423. this.customRenderTargets = new Array();
  12424. // Imported meshes
  12425. this.importedMeshesFiles = new Array();
  12426. this._actionManagers = new Array();
  12427. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12428. // Procedural textures
  12429. this.proceduralTexturesEnabled = true;
  12430. this._proceduralTextures = new Array();
  12431. this.soundTracks = new Array();
  12432. this._audioEnabled = true;
  12433. this._headphone = false;
  12434. this._totalVertices = 0;
  12435. this._activeIndices = 0;
  12436. this._activeParticles = 0;
  12437. this._lastFrameDuration = 0;
  12438. this._evaluateActiveMeshesDuration = 0;
  12439. this._renderTargetsDuration = 0;
  12440. this._particlesDuration = 0;
  12441. this._renderDuration = 0;
  12442. this._spritesDuration = 0;
  12443. this._animationRatio = 0;
  12444. this._renderId = 0;
  12445. this._executeWhenReadyTimeoutId = -1;
  12446. this._toBeDisposed = new BABYLON.SmartArray(256);
  12447. this._onReadyCallbacks = new Array();
  12448. this._pendingData = []; //ANY
  12449. this._onBeforeRenderCallbacks = new Array();
  12450. this._onAfterRenderCallbacks = new Array();
  12451. this._activeMeshes = new BABYLON.SmartArray(256);
  12452. this._processedMaterials = new BABYLON.SmartArray(256);
  12453. this._renderTargets = new BABYLON.SmartArray(256);
  12454. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12455. this._activeSkeletons = new BABYLON.SmartArray(32);
  12456. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12457. this._activeBones = 0;
  12458. this._activeAnimatables = new Array();
  12459. this._transformMatrix = BABYLON.Matrix.Zero();
  12460. this._edgesRenderers = new BABYLON.SmartArray(16);
  12461. this._uniqueIdCounter = 0;
  12462. this._engine = engine;
  12463. engine.scenes.push(this);
  12464. this._renderingManager = new BABYLON.RenderingManager(this);
  12465. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12466. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12467. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12468. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12469. this.attachControl();
  12470. this._debugLayer = new BABYLON.DebugLayer(this);
  12471. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12472. //simplification queue
  12473. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12474. //collision coordinator initialization. For now legacy per default.
  12475. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12476. }
  12477. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12478. get: function () {
  12479. return Scene._FOGMODE_NONE;
  12480. },
  12481. enumerable: true,
  12482. configurable: true
  12483. });
  12484. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12485. get: function () {
  12486. return Scene._FOGMODE_EXP;
  12487. },
  12488. enumerable: true,
  12489. configurable: true
  12490. });
  12491. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12492. get: function () {
  12493. return Scene._FOGMODE_EXP2;
  12494. },
  12495. enumerable: true,
  12496. configurable: true
  12497. });
  12498. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12499. get: function () {
  12500. return Scene._FOGMODE_LINEAR;
  12501. },
  12502. enumerable: true,
  12503. configurable: true
  12504. });
  12505. Object.defineProperty(Scene.prototype, "debugLayer", {
  12506. // Properties
  12507. get: function () {
  12508. return this._debugLayer;
  12509. },
  12510. enumerable: true,
  12511. configurable: true
  12512. });
  12513. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12514. get: function () {
  12515. return this._workerCollisions;
  12516. },
  12517. set: function (enabled) {
  12518. enabled = (enabled && !!Worker);
  12519. this._workerCollisions = enabled;
  12520. if (this.collisionCoordinator) {
  12521. this.collisionCoordinator.destroy();
  12522. }
  12523. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12524. this.collisionCoordinator.init(this);
  12525. },
  12526. enumerable: true,
  12527. configurable: true
  12528. });
  12529. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12530. get: function () {
  12531. return this._selectionOctree;
  12532. },
  12533. enumerable: true,
  12534. configurable: true
  12535. });
  12536. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12537. /**
  12538. * The mesh that is currently under the pointer.
  12539. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12540. */
  12541. get: function () {
  12542. return this._meshUnderPointer;
  12543. },
  12544. enumerable: true,
  12545. configurable: true
  12546. });
  12547. Object.defineProperty(Scene.prototype, "pointerX", {
  12548. /**
  12549. * Current on-screen X position of the pointer
  12550. * @return {number} X position of the pointer
  12551. */
  12552. get: function () {
  12553. return this._pointerX;
  12554. },
  12555. enumerable: true,
  12556. configurable: true
  12557. });
  12558. Object.defineProperty(Scene.prototype, "pointerY", {
  12559. /**
  12560. * Current on-screen Y position of the pointer
  12561. * @return {number} Y position of the pointer
  12562. */
  12563. get: function () {
  12564. return this._pointerY;
  12565. },
  12566. enumerable: true,
  12567. configurable: true
  12568. });
  12569. Scene.prototype.getCachedMaterial = function () {
  12570. return this._cachedMaterial;
  12571. };
  12572. Scene.prototype.getBoundingBoxRenderer = function () {
  12573. return this._boundingBoxRenderer;
  12574. };
  12575. Scene.prototype.getOutlineRenderer = function () {
  12576. return this._outlineRenderer;
  12577. };
  12578. Scene.prototype.getEngine = function () {
  12579. return this._engine;
  12580. };
  12581. Scene.prototype.getTotalVertices = function () {
  12582. return this._totalVertices;
  12583. };
  12584. Scene.prototype.getActiveIndices = function () {
  12585. return this._activeIndices;
  12586. };
  12587. Scene.prototype.getActiveParticles = function () {
  12588. return this._activeParticles;
  12589. };
  12590. Scene.prototype.getActiveBones = function () {
  12591. return this._activeBones;
  12592. };
  12593. // Stats
  12594. Scene.prototype.getLastFrameDuration = function () {
  12595. return this._lastFrameDuration;
  12596. };
  12597. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12598. return this._evaluateActiveMeshesDuration;
  12599. };
  12600. Scene.prototype.getActiveMeshes = function () {
  12601. return this._activeMeshes;
  12602. };
  12603. Scene.prototype.getRenderTargetsDuration = function () {
  12604. return this._renderTargetsDuration;
  12605. };
  12606. Scene.prototype.getRenderDuration = function () {
  12607. return this._renderDuration;
  12608. };
  12609. Scene.prototype.getParticlesDuration = function () {
  12610. return this._particlesDuration;
  12611. };
  12612. Scene.prototype.getSpritesDuration = function () {
  12613. return this._spritesDuration;
  12614. };
  12615. Scene.prototype.getAnimationRatio = function () {
  12616. return this._animationRatio;
  12617. };
  12618. Scene.prototype.getRenderId = function () {
  12619. return this._renderId;
  12620. };
  12621. Scene.prototype.incrementRenderId = function () {
  12622. this._renderId++;
  12623. };
  12624. Scene.prototype._updatePointerPosition = function (evt) {
  12625. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12626. this._pointerX = evt.clientX - canvasRect.left;
  12627. this._pointerY = evt.clientY - canvasRect.top;
  12628. if (this.cameraToUseForPointers) {
  12629. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12630. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12631. }
  12632. };
  12633. // Pointers handling
  12634. Scene.prototype.attachControl = function () {
  12635. var _this = this;
  12636. this._onPointerMove = function (evt) {
  12637. var canvas = _this._engine.getRenderingCanvas();
  12638. _this._updatePointerPosition(evt);
  12639. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12640. if (pickResult.hit) {
  12641. _this._meshUnderPointer = pickResult.pickedMesh;
  12642. _this.setPointerOverMesh(pickResult.pickedMesh);
  12643. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12644. canvas.style.cursor = "pointer";
  12645. }
  12646. else {
  12647. canvas.style.cursor = "";
  12648. }
  12649. }
  12650. else {
  12651. _this.setPointerOverMesh(null);
  12652. canvas.style.cursor = "";
  12653. _this._meshUnderPointer = null;
  12654. }
  12655. };
  12656. this._onPointerDown = function (evt) {
  12657. var predicate = null;
  12658. if (!_this.onPointerDown) {
  12659. predicate = function (mesh) {
  12660. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12661. };
  12662. }
  12663. _this._updatePointerPosition(evt);
  12664. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12665. if (pickResult.hit) {
  12666. if (pickResult.pickedMesh.actionManager) {
  12667. switch (evt.button) {
  12668. case 0:
  12669. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12670. break;
  12671. case 1:
  12672. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12673. break;
  12674. case 2:
  12675. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12676. break;
  12677. }
  12678. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12679. }
  12680. }
  12681. if (_this.onPointerDown) {
  12682. _this.onPointerDown(evt, pickResult);
  12683. }
  12684. };
  12685. this._onPointerUp = function (evt) {
  12686. var predicate = null;
  12687. if (!_this.onPointerUp) {
  12688. predicate = function (mesh) {
  12689. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12690. };
  12691. }
  12692. _this._updatePointerPosition(evt);
  12693. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12694. if (pickResult.hit) {
  12695. if (pickResult.pickedMesh.actionManager) {
  12696. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12697. }
  12698. }
  12699. if (_this.onPointerUp) {
  12700. _this.onPointerUp(evt, pickResult);
  12701. }
  12702. };
  12703. this._onKeyDown = function (evt) {
  12704. if (_this.actionManager) {
  12705. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12706. }
  12707. };
  12708. this._onKeyUp = function (evt) {
  12709. if (_this.actionManager) {
  12710. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12711. }
  12712. };
  12713. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12714. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12715. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12716. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12717. // Wheel
  12718. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12719. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12720. BABYLON.Tools.RegisterTopRootEvents([
  12721. { name: "keydown", handler: this._onKeyDown },
  12722. { name: "keyup", handler: this._onKeyUp }
  12723. ]);
  12724. };
  12725. Scene.prototype.detachControl = function () {
  12726. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12727. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12728. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12729. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12730. // Wheel
  12731. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12732. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12733. BABYLON.Tools.UnregisterTopRootEvents([
  12734. { name: "keydown", handler: this._onKeyDown },
  12735. { name: "keyup", handler: this._onKeyUp }
  12736. ]);
  12737. };
  12738. // Ready
  12739. Scene.prototype.isReady = function () {
  12740. if (this._pendingData.length > 0) {
  12741. return false;
  12742. }
  12743. var index;
  12744. for (index = 0; index < this._geometries.length; index++) {
  12745. var geometry = this._geometries[index];
  12746. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12747. return false;
  12748. }
  12749. }
  12750. for (index = 0; index < this.meshes.length; index++) {
  12751. var mesh = this.meshes[index];
  12752. if (!mesh.isReady()) {
  12753. return false;
  12754. }
  12755. var mat = mesh.material;
  12756. if (mat) {
  12757. if (!mat.isReady(mesh)) {
  12758. return false;
  12759. }
  12760. }
  12761. }
  12762. return true;
  12763. };
  12764. Scene.prototype.resetCachedMaterial = function () {
  12765. this._cachedMaterial = null;
  12766. };
  12767. Scene.prototype.registerBeforeRender = function (func) {
  12768. this._onBeforeRenderCallbacks.push(func);
  12769. };
  12770. Scene.prototype.unregisterBeforeRender = function (func) {
  12771. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12772. if (index > -1) {
  12773. this._onBeforeRenderCallbacks.splice(index, 1);
  12774. }
  12775. };
  12776. Scene.prototype.registerAfterRender = function (func) {
  12777. this._onAfterRenderCallbacks.push(func);
  12778. };
  12779. Scene.prototype.unregisterAfterRender = function (func) {
  12780. var index = this._onAfterRenderCallbacks.indexOf(func);
  12781. if (index > -1) {
  12782. this._onAfterRenderCallbacks.splice(index, 1);
  12783. }
  12784. };
  12785. Scene.prototype._addPendingData = function (data) {
  12786. this._pendingData.push(data);
  12787. };
  12788. Scene.prototype._removePendingData = function (data) {
  12789. var index = this._pendingData.indexOf(data);
  12790. if (index !== -1) {
  12791. this._pendingData.splice(index, 1);
  12792. }
  12793. };
  12794. Scene.prototype.getWaitingItemsCount = function () {
  12795. return this._pendingData.length;
  12796. };
  12797. /**
  12798. * Registers a function to be executed when the scene is ready.
  12799. * @param {Function} func - the function to be executed.
  12800. */
  12801. Scene.prototype.executeWhenReady = function (func) {
  12802. var _this = this;
  12803. this._onReadyCallbacks.push(func);
  12804. if (this._executeWhenReadyTimeoutId !== -1) {
  12805. return;
  12806. }
  12807. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12808. _this._checkIsReady();
  12809. }, 150);
  12810. };
  12811. Scene.prototype._checkIsReady = function () {
  12812. var _this = this;
  12813. if (this.isReady()) {
  12814. this._onReadyCallbacks.forEach(function (func) {
  12815. func();
  12816. });
  12817. this._onReadyCallbacks = [];
  12818. this._executeWhenReadyTimeoutId = -1;
  12819. return;
  12820. }
  12821. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12822. _this._checkIsReady();
  12823. }, 150);
  12824. };
  12825. // Animations
  12826. /**
  12827. * Will start the animation sequence of a given target
  12828. * @param target - the target
  12829. * @param {number} from - from which frame should animation start
  12830. * @param {number} to - till which frame should animation run.
  12831. * @param {boolean} [loop] - should the animation loop
  12832. * @param {number} [speedRatio] - the speed in which to run the animation
  12833. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12834. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12835. * @return {BABYLON.Animatable} the animatable object created for this animation
  12836. * @see BABYLON.Animatable
  12837. * @see http://doc.babylonjs.com/page.php?p=22081
  12838. */
  12839. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12840. if (speedRatio === undefined) {
  12841. speedRatio = 1.0;
  12842. }
  12843. this.stopAnimation(target);
  12844. if (!animatable) {
  12845. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12846. }
  12847. // Local animations
  12848. if (target.animations) {
  12849. animatable.appendAnimations(target, target.animations);
  12850. }
  12851. // Children animations
  12852. if (target.getAnimatables) {
  12853. var animatables = target.getAnimatables();
  12854. for (var index = 0; index < animatables.length; index++) {
  12855. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12856. }
  12857. }
  12858. return animatable;
  12859. };
  12860. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12861. if (speedRatio === undefined) {
  12862. speedRatio = 1.0;
  12863. }
  12864. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12865. return animatable;
  12866. };
  12867. Scene.prototype.getAnimatableByTarget = function (target) {
  12868. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12869. if (this._activeAnimatables[index].target === target) {
  12870. return this._activeAnimatables[index];
  12871. }
  12872. }
  12873. return null;
  12874. };
  12875. /**
  12876. * Will stop the animation of the given target
  12877. * @param target - the target
  12878. * @see beginAnimation
  12879. */
  12880. Scene.prototype.stopAnimation = function (target) {
  12881. var animatable = this.getAnimatableByTarget(target);
  12882. if (animatable) {
  12883. animatable.stop();
  12884. }
  12885. };
  12886. Scene.prototype._animate = function () {
  12887. if (!this.animationsEnabled) {
  12888. return;
  12889. }
  12890. if (!this._animationStartDate) {
  12891. this._animationStartDate = BABYLON.Tools.Now;
  12892. }
  12893. // Getting time
  12894. var now = BABYLON.Tools.Now;
  12895. var delay = now - this._animationStartDate;
  12896. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12897. this._activeAnimatables[index]._animate(delay);
  12898. }
  12899. };
  12900. // Matrix
  12901. Scene.prototype.getViewMatrix = function () {
  12902. return this._viewMatrix;
  12903. };
  12904. Scene.prototype.getProjectionMatrix = function () {
  12905. return this._projectionMatrix;
  12906. };
  12907. Scene.prototype.getTransformMatrix = function () {
  12908. return this._transformMatrix;
  12909. };
  12910. Scene.prototype.setTransformMatrix = function (view, projection) {
  12911. this._viewMatrix = view;
  12912. this._projectionMatrix = projection;
  12913. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12914. };
  12915. // Methods
  12916. Scene.prototype.addMesh = function (newMesh) {
  12917. newMesh.uniqueId = this._uniqueIdCounter++;
  12918. var position = this.meshes.push(newMesh);
  12919. //notify the collision coordinator
  12920. this.collisionCoordinator.onMeshAdded(newMesh);
  12921. if (this.onNewMeshAdded) {
  12922. this.onNewMeshAdded(newMesh, position, this);
  12923. }
  12924. };
  12925. Scene.prototype.removeMesh = function (toRemove) {
  12926. var index = this.meshes.indexOf(toRemove);
  12927. if (index !== -1) {
  12928. // Remove from the scene if mesh found
  12929. this.meshes.splice(index, 1);
  12930. }
  12931. //notify the collision coordinator
  12932. this.collisionCoordinator.onMeshRemoved(toRemove);
  12933. if (this.onMeshRemoved) {
  12934. this.onMeshRemoved(toRemove);
  12935. }
  12936. return index;
  12937. };
  12938. Scene.prototype.removeLight = function (toRemove) {
  12939. var index = this.lights.indexOf(toRemove);
  12940. if (index !== -1) {
  12941. // Remove from the scene if mesh found
  12942. this.lights.splice(index, 1);
  12943. }
  12944. if (this.onLightRemoved) {
  12945. this.onLightRemoved(toRemove);
  12946. }
  12947. return index;
  12948. };
  12949. Scene.prototype.removeCamera = function (toRemove) {
  12950. var index = this.cameras.indexOf(toRemove);
  12951. if (index !== -1) {
  12952. // Remove from the scene if mesh found
  12953. this.cameras.splice(index, 1);
  12954. }
  12955. // Remove from activeCameras
  12956. var index2 = this.activeCameras.indexOf(toRemove);
  12957. if (index2 !== -1) {
  12958. // Remove from the scene if mesh found
  12959. this.activeCameras.splice(index2, 1);
  12960. }
  12961. // Reset the activeCamera
  12962. if (this.activeCamera === toRemove) {
  12963. if (this.cameras.length > 0) {
  12964. this.activeCamera = this.cameras[0];
  12965. }
  12966. else {
  12967. this.activeCamera = null;
  12968. }
  12969. }
  12970. if (this.onCameraRemoved) {
  12971. this.onCameraRemoved(toRemove);
  12972. }
  12973. return index;
  12974. };
  12975. Scene.prototype.addLight = function (newLight) {
  12976. newLight.uniqueId = this._uniqueIdCounter++;
  12977. var position = this.lights.push(newLight);
  12978. if (this.onNewLightAdded) {
  12979. this.onNewLightAdded(newLight, position, this);
  12980. }
  12981. };
  12982. Scene.prototype.addCamera = function (newCamera) {
  12983. newCamera.uniqueId = this._uniqueIdCounter++;
  12984. var position = this.cameras.push(newCamera);
  12985. if (this.onNewCameraAdded) {
  12986. this.onNewCameraAdded(newCamera, position, this);
  12987. }
  12988. };
  12989. /**
  12990. * sets the active camera of the scene using its ID
  12991. * @param {string} id - the camera's ID
  12992. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12993. * @see activeCamera
  12994. */
  12995. Scene.prototype.setActiveCameraByID = function (id) {
  12996. var camera = this.getCameraByID(id);
  12997. if (camera) {
  12998. this.activeCamera = camera;
  12999. return camera;
  13000. }
  13001. return null;
  13002. };
  13003. /**
  13004. * sets the active camera of the scene using its name
  13005. * @param {string} name - the camera's name
  13006. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13007. * @see activeCamera
  13008. */
  13009. Scene.prototype.setActiveCameraByName = function (name) {
  13010. var camera = this.getCameraByName(name);
  13011. if (camera) {
  13012. this.activeCamera = camera;
  13013. return camera;
  13014. }
  13015. return null;
  13016. };
  13017. /**
  13018. * get a material using its id
  13019. * @param {string} the material's ID
  13020. * @return {BABYLON.Material|null} the material or null if none found.
  13021. */
  13022. Scene.prototype.getMaterialByID = function (id) {
  13023. for (var index = 0; index < this.materials.length; index++) {
  13024. if (this.materials[index].id === id) {
  13025. return this.materials[index];
  13026. }
  13027. }
  13028. return null;
  13029. };
  13030. /**
  13031. * get a material using its name
  13032. * @param {string} the material's name
  13033. * @return {BABYLON.Material|null} the material or null if none found.
  13034. */
  13035. Scene.prototype.getMaterialByName = function (name) {
  13036. for (var index = 0; index < this.materials.length; index++) {
  13037. if (this.materials[index].name === name) {
  13038. return this.materials[index];
  13039. }
  13040. }
  13041. return null;
  13042. };
  13043. Scene.prototype.getLensFlareSystemByName = function (name) {
  13044. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13045. if (this.lensFlareSystems[index].name === name) {
  13046. return this.lensFlareSystems[index];
  13047. }
  13048. }
  13049. return null;
  13050. };
  13051. Scene.prototype.getCameraByID = function (id) {
  13052. for (var index = 0; index < this.cameras.length; index++) {
  13053. if (this.cameras[index].id === id) {
  13054. return this.cameras[index];
  13055. }
  13056. }
  13057. return null;
  13058. };
  13059. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13060. for (var index = 0; index < this.cameras.length; index++) {
  13061. if (this.cameras[index].uniqueId === uniqueId) {
  13062. return this.cameras[index];
  13063. }
  13064. }
  13065. return null;
  13066. };
  13067. /**
  13068. * get a camera using its name
  13069. * @param {string} the camera's name
  13070. * @return {BABYLON.Camera|null} the camera or null if none found.
  13071. */
  13072. Scene.prototype.getCameraByName = function (name) {
  13073. for (var index = 0; index < this.cameras.length; index++) {
  13074. if (this.cameras[index].name === name) {
  13075. return this.cameras[index];
  13076. }
  13077. }
  13078. return null;
  13079. };
  13080. /**
  13081. * get a light node using its name
  13082. * @param {string} the light's name
  13083. * @return {BABYLON.Light|null} the light or null if none found.
  13084. */
  13085. Scene.prototype.getLightByName = function (name) {
  13086. for (var index = 0; index < this.lights.length; index++) {
  13087. if (this.lights[index].name === name) {
  13088. return this.lights[index];
  13089. }
  13090. }
  13091. return null;
  13092. };
  13093. /**
  13094. * get a light node using its ID
  13095. * @param {string} the light's id
  13096. * @return {BABYLON.Light|null} the light or null if none found.
  13097. */
  13098. Scene.prototype.getLightByID = function (id) {
  13099. for (var index = 0; index < this.lights.length; index++) {
  13100. if (this.lights[index].id === id) {
  13101. return this.lights[index];
  13102. }
  13103. }
  13104. return null;
  13105. };
  13106. /**
  13107. * get a light node using its scene-generated unique ID
  13108. * @param {number} the light's unique id
  13109. * @return {BABYLON.Light|null} the light or null if none found.
  13110. */
  13111. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13112. for (var index = 0; index < this.lights.length; index++) {
  13113. if (this.lights[index].uniqueId === uniqueId) {
  13114. return this.lights[index];
  13115. }
  13116. }
  13117. return null;
  13118. };
  13119. /**
  13120. * get a geometry using its ID
  13121. * @param {string} the geometry's id
  13122. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13123. */
  13124. Scene.prototype.getGeometryByID = function (id) {
  13125. for (var index = 0; index < this._geometries.length; index++) {
  13126. if (this._geometries[index].id === id) {
  13127. return this._geometries[index];
  13128. }
  13129. }
  13130. return null;
  13131. };
  13132. /**
  13133. * add a new geometry to this scene.
  13134. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13135. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13136. * @return {boolean} was the geometry added or not
  13137. */
  13138. Scene.prototype.pushGeometry = function (geometry, force) {
  13139. if (!force && this.getGeometryByID(geometry.id)) {
  13140. return false;
  13141. }
  13142. this._geometries.push(geometry);
  13143. //notify the collision coordinator
  13144. this.collisionCoordinator.onGeometryAdded(geometry);
  13145. if (this.onGeometryAdded) {
  13146. this.onGeometryAdded(geometry);
  13147. }
  13148. return true;
  13149. };
  13150. /**
  13151. * Removes an existing geometry
  13152. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13153. * @return {boolean} was the geometry removed or not
  13154. */
  13155. Scene.prototype.removeGeometry = function (geometry) {
  13156. var index = this._geometries.indexOf(geometry);
  13157. if (index > -1) {
  13158. this._geometries.splice(index, 1);
  13159. //notify the collision coordinator
  13160. this.collisionCoordinator.onGeometryDeleted(geometry);
  13161. if (this.onGeometryRemoved) {
  13162. this.onGeometryRemoved(geometry);
  13163. }
  13164. return true;
  13165. }
  13166. return false;
  13167. };
  13168. Scene.prototype.getGeometries = function () {
  13169. return this._geometries;
  13170. };
  13171. /**
  13172. * Get the first added mesh found of a given ID
  13173. * @param {string} id - the id to search for
  13174. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13175. */
  13176. Scene.prototype.getMeshByID = function (id) {
  13177. for (var index = 0; index < this.meshes.length; index++) {
  13178. if (this.meshes[index].id === id) {
  13179. return this.meshes[index];
  13180. }
  13181. }
  13182. return null;
  13183. };
  13184. /**
  13185. * Get a mesh with its auto-generated unique id
  13186. * @param {number} uniqueId - the unique id to search for
  13187. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13188. */
  13189. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13190. for (var index = 0; index < this.meshes.length; index++) {
  13191. if (this.meshes[index].uniqueId === uniqueId) {
  13192. return this.meshes[index];
  13193. }
  13194. }
  13195. return null;
  13196. };
  13197. /**
  13198. * Get a the last added mesh found of a given ID
  13199. * @param {string} id - the id to search for
  13200. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13201. */
  13202. Scene.prototype.getLastMeshByID = function (id) {
  13203. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13204. if (this.meshes[index].id === id) {
  13205. return this.meshes[index];
  13206. }
  13207. }
  13208. return null;
  13209. };
  13210. /**
  13211. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13212. * @param {string} id - the id to search for
  13213. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13214. */
  13215. Scene.prototype.getLastEntryByID = function (id) {
  13216. var index;
  13217. for (index = this.meshes.length - 1; index >= 0; index--) {
  13218. if (this.meshes[index].id === id) {
  13219. return this.meshes[index];
  13220. }
  13221. }
  13222. for (index = this.cameras.length - 1; index >= 0; index--) {
  13223. if (this.cameras[index].id === id) {
  13224. return this.cameras[index];
  13225. }
  13226. }
  13227. for (index = this.lights.length - 1; index >= 0; index--) {
  13228. if (this.lights[index].id === id) {
  13229. return this.lights[index];
  13230. }
  13231. }
  13232. return null;
  13233. };
  13234. Scene.prototype.getNodeByID = function (id) {
  13235. var mesh = this.getMeshByID(id);
  13236. if (mesh) {
  13237. return mesh;
  13238. }
  13239. var light = this.getLightByID(id);
  13240. if (light) {
  13241. return light;
  13242. }
  13243. return this.getCameraByID(id);
  13244. };
  13245. Scene.prototype.getNodeByName = function (name) {
  13246. var mesh = this.getMeshByName(name);
  13247. if (mesh) {
  13248. return mesh;
  13249. }
  13250. var light = this.getLightByName(name);
  13251. if (light) {
  13252. return light;
  13253. }
  13254. return this.getCameraByName(name);
  13255. };
  13256. Scene.prototype.getMeshByName = function (name) {
  13257. for (var index = 0; index < this.meshes.length; index++) {
  13258. if (this.meshes[index].name === name) {
  13259. return this.meshes[index];
  13260. }
  13261. }
  13262. return null;
  13263. };
  13264. Scene.prototype.getSoundByName = function (name) {
  13265. var index;
  13266. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13267. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13268. return this.mainSoundTrack.soundCollection[index];
  13269. }
  13270. }
  13271. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13272. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13273. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13274. return this.soundTracks[sdIndex].soundCollection[index];
  13275. }
  13276. }
  13277. }
  13278. return null;
  13279. };
  13280. Scene.prototype.getLastSkeletonByID = function (id) {
  13281. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13282. if (this.skeletons[index].id === id) {
  13283. return this.skeletons[index];
  13284. }
  13285. }
  13286. return null;
  13287. };
  13288. Scene.prototype.getSkeletonById = function (id) {
  13289. for (var index = 0; index < this.skeletons.length; index++) {
  13290. if (this.skeletons[index].id === id) {
  13291. return this.skeletons[index];
  13292. }
  13293. }
  13294. return null;
  13295. };
  13296. Scene.prototype.getSkeletonByName = function (name) {
  13297. for (var index = 0; index < this.skeletons.length; index++) {
  13298. if (this.skeletons[index].name === name) {
  13299. return this.skeletons[index];
  13300. }
  13301. }
  13302. return null;
  13303. };
  13304. Scene.prototype.isActiveMesh = function (mesh) {
  13305. return (this._activeMeshes.indexOf(mesh) !== -1);
  13306. };
  13307. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13308. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13309. var material = subMesh.getMaterial();
  13310. if (mesh.showSubMeshesBoundingBox) {
  13311. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13312. }
  13313. if (material) {
  13314. // Render targets
  13315. if (material.getRenderTargetTextures) {
  13316. if (this._processedMaterials.indexOf(material) === -1) {
  13317. this._processedMaterials.push(material);
  13318. this._renderTargets.concat(material.getRenderTargetTextures());
  13319. }
  13320. }
  13321. // Dispatch
  13322. this._activeIndices += subMesh.indexCount;
  13323. this._renderingManager.dispatch(subMesh);
  13324. }
  13325. }
  13326. };
  13327. Scene.prototype._evaluateActiveMeshes = function () {
  13328. this.activeCamera._activeMeshes.reset();
  13329. this._activeMeshes.reset();
  13330. this._renderingManager.reset();
  13331. this._processedMaterials.reset();
  13332. this._activeParticleSystems.reset();
  13333. this._activeSkeletons.reset();
  13334. this._softwareSkinnedMeshes.reset();
  13335. this._boundingBoxRenderer.reset();
  13336. this._edgesRenderers.reset();
  13337. if (!this._frustumPlanes) {
  13338. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13339. }
  13340. else {
  13341. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13342. }
  13343. // Meshes
  13344. var meshes;
  13345. var len;
  13346. if (this._selectionOctree) {
  13347. var selection = this._selectionOctree.select(this._frustumPlanes);
  13348. meshes = selection.data;
  13349. len = selection.length;
  13350. }
  13351. else {
  13352. len = this.meshes.length;
  13353. meshes = this.meshes;
  13354. }
  13355. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13356. var mesh = meshes[meshIndex];
  13357. if (mesh.isBlocked) {
  13358. continue;
  13359. }
  13360. this._totalVertices += mesh.getTotalVertices();
  13361. if (!mesh.isReady() || !mesh.isEnabled()) {
  13362. continue;
  13363. }
  13364. mesh.computeWorldMatrix();
  13365. // Intersections
  13366. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13367. this._meshesForIntersections.pushNoDuplicate(mesh);
  13368. }
  13369. // Switch to current LOD
  13370. var meshLOD = mesh.getLOD(this.activeCamera);
  13371. if (!meshLOD) {
  13372. continue;
  13373. }
  13374. mesh._preActivate();
  13375. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13376. this._activeMeshes.push(mesh);
  13377. this.activeCamera._activeMeshes.push(mesh);
  13378. mesh._activate(this._renderId);
  13379. this._activeMesh(meshLOD);
  13380. }
  13381. }
  13382. // Particle systems
  13383. var beforeParticlesDate = BABYLON.Tools.Now;
  13384. if (this.particlesEnabled) {
  13385. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13386. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13387. var particleSystem = this.particleSystems[particleIndex];
  13388. if (!particleSystem.isStarted()) {
  13389. continue;
  13390. }
  13391. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13392. this._activeParticleSystems.push(particleSystem);
  13393. particleSystem.animate();
  13394. }
  13395. }
  13396. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13397. }
  13398. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13399. };
  13400. Scene.prototype._activeMesh = function (mesh) {
  13401. if (mesh.skeleton && this.skeletonsEnabled) {
  13402. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13403. if (!mesh.computeBonesUsingShaders) {
  13404. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13405. }
  13406. }
  13407. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13408. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13409. }
  13410. if (mesh._edgesRenderer) {
  13411. this._edgesRenderers.push(mesh._edgesRenderer);
  13412. }
  13413. if (mesh && mesh.subMeshes) {
  13414. // Submeshes Octrees
  13415. var len;
  13416. var subMeshes;
  13417. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13418. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13419. len = intersections.length;
  13420. subMeshes = intersections.data;
  13421. }
  13422. else {
  13423. subMeshes = mesh.subMeshes;
  13424. len = subMeshes.length;
  13425. }
  13426. for (var subIndex = 0; subIndex < len; subIndex++) {
  13427. var subMesh = subMeshes[subIndex];
  13428. this._evaluateSubMesh(subMesh, mesh);
  13429. }
  13430. }
  13431. };
  13432. Scene.prototype.updateTransformMatrix = function (force) {
  13433. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13434. };
  13435. Scene.prototype._renderForCamera = function (camera) {
  13436. var engine = this._engine;
  13437. this.activeCamera = camera;
  13438. if (!this.activeCamera)
  13439. throw new Error("Active camera not set");
  13440. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13441. // Viewport
  13442. engine.setViewport(this.activeCamera.viewport);
  13443. // Camera
  13444. this.resetCachedMaterial();
  13445. this._renderId++;
  13446. this.updateTransformMatrix();
  13447. if (this.beforeCameraRender) {
  13448. this.beforeCameraRender(this.activeCamera);
  13449. }
  13450. // Meshes
  13451. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13452. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13453. this._evaluateActiveMeshes();
  13454. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13455. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13456. // Skeletons
  13457. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13458. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13459. skeleton.prepare();
  13460. }
  13461. // Software skinning
  13462. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13463. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13464. mesh.applySkeleton(mesh.skeleton);
  13465. }
  13466. // Render targets
  13467. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13468. if (this.renderTargetsEnabled) {
  13469. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13470. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13471. var renderTarget = this._renderTargets.data[renderIndex];
  13472. if (renderTarget._shouldRender()) {
  13473. this._renderId++;
  13474. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13475. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13476. }
  13477. }
  13478. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13479. this._renderId++;
  13480. }
  13481. if (this._renderTargets.length > 0) {
  13482. engine.restoreDefaultFramebuffer();
  13483. }
  13484. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13485. // Prepare Frame
  13486. this.postProcessManager._prepareFrame();
  13487. var beforeRenderDate = BABYLON.Tools.Now;
  13488. // Backgrounds
  13489. var layerIndex;
  13490. var layer;
  13491. if (this.layers.length) {
  13492. engine.setDepthBuffer(false);
  13493. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13494. layer = this.layers[layerIndex];
  13495. if (layer.isBackground) {
  13496. layer.render();
  13497. }
  13498. }
  13499. engine.setDepthBuffer(true);
  13500. }
  13501. // Render
  13502. BABYLON.Tools.StartPerformanceCounter("Main render");
  13503. this._renderingManager.render(null, null, true, true);
  13504. BABYLON.Tools.EndPerformanceCounter("Main render");
  13505. // Bounding boxes
  13506. this._boundingBoxRenderer.render();
  13507. // Edges
  13508. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13509. this._edgesRenderers.data[edgesRendererIndex].render();
  13510. }
  13511. // Lens flares
  13512. if (this.lensFlaresEnabled) {
  13513. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13514. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13515. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13516. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13517. lensFlareSystem.render();
  13518. }
  13519. }
  13520. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13521. }
  13522. // Foregrounds
  13523. if (this.layers.length) {
  13524. engine.setDepthBuffer(false);
  13525. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13526. layer = this.layers[layerIndex];
  13527. if (!layer.isBackground) {
  13528. layer.render();
  13529. }
  13530. }
  13531. engine.setDepthBuffer(true);
  13532. }
  13533. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13534. // Finalize frame
  13535. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13536. // Update camera
  13537. this.activeCamera._updateFromScene();
  13538. // Reset some special arrays
  13539. this._renderTargets.reset();
  13540. if (this.afterCameraRender) {
  13541. this.afterCameraRender(this.activeCamera);
  13542. }
  13543. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13544. };
  13545. Scene.prototype._processSubCameras = function (camera) {
  13546. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13547. this._renderForCamera(camera);
  13548. return;
  13549. }
  13550. // rig cameras
  13551. for (var index = 0; index < camera._rigCameras.length; index++) {
  13552. this._renderForCamera(camera._rigCameras[index]);
  13553. }
  13554. this.activeCamera = camera;
  13555. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13556. // Update camera
  13557. this.activeCamera._updateFromScene();
  13558. };
  13559. Scene.prototype._checkIntersections = function () {
  13560. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13561. var sourceMesh = this._meshesForIntersections.data[index];
  13562. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13563. var action = sourceMesh.actionManager.actions[actionIndex];
  13564. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13565. var parameters = action.getTriggerParameter();
  13566. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13567. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13568. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13569. if (areIntersecting && currentIntersectionInProgress === -1) {
  13570. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13571. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13572. sourceMesh._intersectionsInProgress.push(otherMesh);
  13573. }
  13574. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13575. sourceMesh._intersectionsInProgress.push(otherMesh);
  13576. }
  13577. }
  13578. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13579. //They intersected, and now they don't.
  13580. //is this trigger an exit trigger? execute an event.
  13581. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13582. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13583. }
  13584. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13585. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13586. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13587. }
  13588. }
  13589. }
  13590. }
  13591. }
  13592. };
  13593. Scene.prototype.render = function () {
  13594. var startDate = BABYLON.Tools.Now;
  13595. this._particlesDuration = 0;
  13596. this._spritesDuration = 0;
  13597. this._activeParticles = 0;
  13598. this._renderDuration = 0;
  13599. this._renderTargetsDuration = 0;
  13600. this._evaluateActiveMeshesDuration = 0;
  13601. this._totalVertices = 0;
  13602. this._activeIndices = 0;
  13603. this._activeBones = 0;
  13604. this.getEngine().resetDrawCalls();
  13605. this._meshesForIntersections.reset();
  13606. this.resetCachedMaterial();
  13607. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13608. // Actions
  13609. if (this.actionManager) {
  13610. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13611. }
  13612. //Simplification Queue
  13613. if (!this.simplificationQueue.running) {
  13614. this.simplificationQueue.executeNext();
  13615. }
  13616. // Animations
  13617. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13618. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13619. this._animate();
  13620. // Physics
  13621. if (this._physicsEngine) {
  13622. BABYLON.Tools.StartPerformanceCounter("Physics");
  13623. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13624. BABYLON.Tools.EndPerformanceCounter("Physics");
  13625. }
  13626. // Before render
  13627. if (this.beforeRender) {
  13628. this.beforeRender();
  13629. }
  13630. var callbackIndex;
  13631. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13632. this._onBeforeRenderCallbacks[callbackIndex]();
  13633. }
  13634. // Customs render targets
  13635. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13636. var engine = this.getEngine();
  13637. var currentActiveCamera = this.activeCamera;
  13638. if (this.renderTargetsEnabled) {
  13639. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13640. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13641. var renderTarget = this.customRenderTargets[customIndex];
  13642. if (renderTarget._shouldRender()) {
  13643. this._renderId++;
  13644. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13645. if (!this.activeCamera)
  13646. throw new Error("Active camera not set");
  13647. // Viewport
  13648. engine.setViewport(this.activeCamera.viewport);
  13649. // Camera
  13650. this.updateTransformMatrix();
  13651. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13652. }
  13653. }
  13654. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13655. this._renderId++;
  13656. }
  13657. if (this.customRenderTargets.length > 0) {
  13658. engine.restoreDefaultFramebuffer();
  13659. }
  13660. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13661. this.activeCamera = currentActiveCamera;
  13662. // Procedural textures
  13663. if (this.proceduralTexturesEnabled) {
  13664. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13665. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13666. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13667. if (proceduralTexture._shouldRender()) {
  13668. proceduralTexture.render();
  13669. }
  13670. }
  13671. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13672. }
  13673. // Clear
  13674. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13675. // Shadows
  13676. if (this.shadowsEnabled) {
  13677. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13678. var light = this.lights[lightIndex];
  13679. var shadowGenerator = light.getShadowGenerator();
  13680. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13681. this._renderTargets.push(shadowGenerator.getShadowMap());
  13682. }
  13683. }
  13684. }
  13685. // Depth renderer
  13686. if (this._depthRenderer) {
  13687. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13688. }
  13689. // RenderPipeline
  13690. this.postProcessRenderPipelineManager.update();
  13691. // Multi-cameras?
  13692. if (this.activeCameras.length > 0) {
  13693. var currentRenderId = this._renderId;
  13694. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13695. this._renderId = currentRenderId;
  13696. this._processSubCameras(this.activeCameras[cameraIndex]);
  13697. }
  13698. }
  13699. else {
  13700. if (!this.activeCamera) {
  13701. throw new Error("No camera defined");
  13702. }
  13703. this._processSubCameras(this.activeCamera);
  13704. }
  13705. // Intersection checks
  13706. this._checkIntersections();
  13707. // Update the audio listener attached to the camera
  13708. this._updateAudioParameters();
  13709. // After render
  13710. if (this.afterRender) {
  13711. this.afterRender();
  13712. }
  13713. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13714. this._onAfterRenderCallbacks[callbackIndex]();
  13715. }
  13716. // Cleaning
  13717. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13718. this._toBeDisposed.data[index].dispose();
  13719. this._toBeDisposed[index] = null;
  13720. }
  13721. this._toBeDisposed.reset();
  13722. if (this.dumpNextRenderTargets) {
  13723. this.dumpNextRenderTargets = false;
  13724. }
  13725. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13726. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13727. };
  13728. Scene.prototype._updateAudioParameters = function () {
  13729. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13730. return;
  13731. }
  13732. var listeningCamera;
  13733. var audioEngine = BABYLON.Engine.audioEngine;
  13734. if (this.activeCameras.length > 0) {
  13735. listeningCamera = this.activeCameras[0];
  13736. }
  13737. else {
  13738. listeningCamera = this.activeCamera;
  13739. }
  13740. if (listeningCamera && audioEngine.canUseWebAudio) {
  13741. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13742. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13743. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13744. cameraDirection.normalize();
  13745. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13746. var i;
  13747. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13748. var sound = this.mainSoundTrack.soundCollection[i];
  13749. if (sound.useCustomAttenuation) {
  13750. sound.updateDistanceFromListener();
  13751. }
  13752. }
  13753. for (i = 0; i < this.soundTracks.length; i++) {
  13754. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13755. sound = this.soundTracks[i].soundCollection[j];
  13756. if (sound.useCustomAttenuation) {
  13757. sound.updateDistanceFromListener();
  13758. }
  13759. }
  13760. }
  13761. }
  13762. };
  13763. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13764. // Audio
  13765. get: function () {
  13766. return this._audioEnabled;
  13767. },
  13768. set: function (value) {
  13769. this._audioEnabled = value;
  13770. if (this._audioEnabled) {
  13771. this._enableAudio();
  13772. }
  13773. else {
  13774. this._disableAudio();
  13775. }
  13776. },
  13777. enumerable: true,
  13778. configurable: true
  13779. });
  13780. Scene.prototype._disableAudio = function () {
  13781. var i;
  13782. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13783. this.mainSoundTrack.soundCollection[i].pause();
  13784. }
  13785. for (i = 0; i < this.soundTracks.length; i++) {
  13786. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13787. this.soundTracks[i].soundCollection[j].pause();
  13788. }
  13789. }
  13790. };
  13791. Scene.prototype._enableAudio = function () {
  13792. var i;
  13793. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13794. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13795. this.mainSoundTrack.soundCollection[i].play();
  13796. }
  13797. }
  13798. for (i = 0; i < this.soundTracks.length; i++) {
  13799. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13800. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13801. this.soundTracks[i].soundCollection[j].play();
  13802. }
  13803. }
  13804. }
  13805. };
  13806. Object.defineProperty(Scene.prototype, "headphone", {
  13807. get: function () {
  13808. return this._headphone;
  13809. },
  13810. set: function (value) {
  13811. this._headphone = value;
  13812. if (this._headphone) {
  13813. this._switchAudioModeForHeadphones();
  13814. }
  13815. else {
  13816. this._switchAudioModeForNormalSpeakers();
  13817. }
  13818. },
  13819. enumerable: true,
  13820. configurable: true
  13821. });
  13822. Scene.prototype._switchAudioModeForHeadphones = function () {
  13823. this.mainSoundTrack.switchPanningModelToHRTF();
  13824. for (var i = 0; i < this.soundTracks.length; i++) {
  13825. this.soundTracks[i].switchPanningModelToHRTF();
  13826. }
  13827. };
  13828. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13829. this.mainSoundTrack.switchPanningModelToEqualPower();
  13830. for (var i = 0; i < this.soundTracks.length; i++) {
  13831. this.soundTracks[i].switchPanningModelToEqualPower();
  13832. }
  13833. };
  13834. Scene.prototype.enableDepthRenderer = function () {
  13835. if (this._depthRenderer) {
  13836. return this._depthRenderer;
  13837. }
  13838. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13839. return this._depthRenderer;
  13840. };
  13841. Scene.prototype.disableDepthRenderer = function () {
  13842. if (!this._depthRenderer) {
  13843. return;
  13844. }
  13845. this._depthRenderer.dispose();
  13846. this._depthRenderer = null;
  13847. };
  13848. Scene.prototype.dispose = function () {
  13849. this.beforeRender = null;
  13850. this.afterRender = null;
  13851. this.skeletons = [];
  13852. this._boundingBoxRenderer.dispose();
  13853. if (this._depthRenderer) {
  13854. this._depthRenderer.dispose();
  13855. }
  13856. // Debug layer
  13857. this.debugLayer.hide();
  13858. // Events
  13859. if (this.onDispose) {
  13860. this.onDispose();
  13861. }
  13862. this._onBeforeRenderCallbacks = [];
  13863. this._onAfterRenderCallbacks = [];
  13864. this.detachControl();
  13865. // Release sounds & sounds tracks
  13866. this.disposeSounds();
  13867. // Detach cameras
  13868. var canvas = this._engine.getRenderingCanvas();
  13869. var index;
  13870. for (index = 0; index < this.cameras.length; index++) {
  13871. this.cameras[index].detachControl(canvas);
  13872. }
  13873. // Release lights
  13874. while (this.lights.length) {
  13875. this.lights[0].dispose();
  13876. }
  13877. // Release meshes
  13878. while (this.meshes.length) {
  13879. this.meshes[0].dispose(true);
  13880. }
  13881. // Release cameras
  13882. while (this.cameras.length) {
  13883. this.cameras[0].dispose();
  13884. }
  13885. // Release materials
  13886. while (this.materials.length) {
  13887. this.materials[0].dispose();
  13888. }
  13889. // Release particles
  13890. while (this.particleSystems.length) {
  13891. this.particleSystems[0].dispose();
  13892. }
  13893. // Release sprites
  13894. while (this.spriteManagers.length) {
  13895. this.spriteManagers[0].dispose();
  13896. }
  13897. // Release layers
  13898. while (this.layers.length) {
  13899. this.layers[0].dispose();
  13900. }
  13901. // Release textures
  13902. while (this.textures.length) {
  13903. this.textures[0].dispose();
  13904. }
  13905. // Post-processes
  13906. this.postProcessManager.dispose();
  13907. // Physics
  13908. if (this._physicsEngine) {
  13909. this.disablePhysicsEngine();
  13910. }
  13911. // Remove from engine
  13912. index = this._engine.scenes.indexOf(this);
  13913. if (index > -1) {
  13914. this._engine.scenes.splice(index, 1);
  13915. }
  13916. this._engine.wipeCaches();
  13917. };
  13918. // Release sounds & sounds tracks
  13919. Scene.prototype.disposeSounds = function () {
  13920. this.mainSoundTrack.dispose();
  13921. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13922. this.soundTracks[scIndex].dispose();
  13923. }
  13924. };
  13925. // Octrees
  13926. Scene.prototype.getWorldExtends = function () {
  13927. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13928. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13929. for (var index = 0; index < this.meshes.length; index++) {
  13930. var mesh = this.meshes[index];
  13931. mesh.computeWorldMatrix(true);
  13932. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13933. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13934. BABYLON.Tools.CheckExtends(minBox, min, max);
  13935. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13936. }
  13937. return {
  13938. min: min,
  13939. max: max
  13940. };
  13941. };
  13942. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13943. if (maxCapacity === void 0) { maxCapacity = 64; }
  13944. if (maxDepth === void 0) { maxDepth = 2; }
  13945. if (!this._selectionOctree) {
  13946. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13947. }
  13948. var worldExtends = this.getWorldExtends();
  13949. // Update octree
  13950. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13951. return this._selectionOctree;
  13952. };
  13953. // Picking
  13954. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13955. var engine = this._engine;
  13956. if (!camera) {
  13957. if (!this.activeCamera)
  13958. throw new Error("Active camera not set");
  13959. camera = this.activeCamera;
  13960. }
  13961. var cameraViewport = camera.viewport;
  13962. var viewport = cameraViewport.toGlobal(engine);
  13963. // Moving coordinates to local viewport world
  13964. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13965. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13966. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13967. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13968. };
  13969. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13970. var pickingInfo = null;
  13971. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13972. var mesh = this.meshes[meshIndex];
  13973. if (predicate) {
  13974. if (!predicate(mesh)) {
  13975. continue;
  13976. }
  13977. }
  13978. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13979. continue;
  13980. }
  13981. var world = mesh.getWorldMatrix();
  13982. var ray = rayFunction(world);
  13983. var result = mesh.intersects(ray, fastCheck);
  13984. if (!result || !result.hit)
  13985. continue;
  13986. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13987. continue;
  13988. pickingInfo = result;
  13989. if (fastCheck) {
  13990. break;
  13991. }
  13992. }
  13993. return pickingInfo || new BABYLON.PickingInfo();
  13994. };
  13995. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13996. var _this = this;
  13997. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13998. /// <param name="x">X position on screen</param>
  13999. /// <param name="y">Y position on screen</param>
  14000. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  14001. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14002. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  14003. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14004. };
  14005. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14006. var _this = this;
  14007. return this._internalPick(function (world) {
  14008. if (!_this._pickWithRayInverseMatrix) {
  14009. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14010. }
  14011. world.invertToRef(_this._pickWithRayInverseMatrix);
  14012. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14013. }, predicate, fastCheck);
  14014. };
  14015. Scene.prototype.setPointerOverMesh = function (mesh) {
  14016. if (this._pointerOverMesh === mesh) {
  14017. return;
  14018. }
  14019. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14020. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14021. }
  14022. this._pointerOverMesh = mesh;
  14023. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14024. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14025. }
  14026. };
  14027. Scene.prototype.getPointerOverMesh = function () {
  14028. return this._pointerOverMesh;
  14029. };
  14030. // Physics
  14031. Scene.prototype.getPhysicsEngine = function () {
  14032. return this._physicsEngine;
  14033. };
  14034. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14035. if (this._physicsEngine) {
  14036. return true;
  14037. }
  14038. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14039. if (!this._physicsEngine.isSupported()) {
  14040. this._physicsEngine = null;
  14041. return false;
  14042. }
  14043. this._physicsEngine._initialize(gravity);
  14044. return true;
  14045. };
  14046. Scene.prototype.disablePhysicsEngine = function () {
  14047. if (!this._physicsEngine) {
  14048. return;
  14049. }
  14050. this._physicsEngine.dispose();
  14051. this._physicsEngine = undefined;
  14052. };
  14053. Scene.prototype.isPhysicsEnabled = function () {
  14054. return this._physicsEngine !== undefined;
  14055. };
  14056. Scene.prototype.setGravity = function (gravity) {
  14057. if (!this._physicsEngine) {
  14058. return;
  14059. }
  14060. this._physicsEngine._setGravity(gravity);
  14061. };
  14062. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14063. if (parts.parts) {
  14064. options = parts;
  14065. parts = parts.parts;
  14066. }
  14067. if (!this._physicsEngine) {
  14068. return null;
  14069. }
  14070. for (var index = 0; index < parts.length; index++) {
  14071. var mesh = parts[index].mesh;
  14072. mesh._physicImpostor = parts[index].impostor;
  14073. mesh._physicsMass = options.mass / parts.length;
  14074. mesh._physicsFriction = options.friction;
  14075. mesh._physicRestitution = options.restitution;
  14076. }
  14077. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14078. };
  14079. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14080. for (var index = 0; index < compound.parts.length; index++) {
  14081. var mesh = compound.parts[index].mesh;
  14082. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14083. this._physicsEngine._unregisterMesh(mesh);
  14084. }
  14085. };
  14086. // Misc.
  14087. Scene.prototype.createDefaultCameraOrLight = function () {
  14088. // Light
  14089. if (this.lights.length === 0) {
  14090. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14091. }
  14092. // Camera
  14093. if (!this.activeCamera) {
  14094. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14095. // Compute position
  14096. var worldExtends = this.getWorldExtends();
  14097. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14098. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14099. camera.setTarget(worldCenter);
  14100. this.activeCamera = camera;
  14101. }
  14102. };
  14103. // Tags
  14104. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14105. if (tagsQuery === undefined) {
  14106. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14107. return list;
  14108. }
  14109. var listByTags = [];
  14110. forEach = forEach || (function (item) { return; });
  14111. for (var i in list) {
  14112. var item = list[i];
  14113. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14114. listByTags.push(item);
  14115. forEach(item);
  14116. }
  14117. }
  14118. return listByTags;
  14119. };
  14120. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14121. return this._getByTags(this.meshes, tagsQuery, forEach);
  14122. };
  14123. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14124. return this._getByTags(this.cameras, tagsQuery, forEach);
  14125. };
  14126. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14127. return this._getByTags(this.lights, tagsQuery, forEach);
  14128. };
  14129. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14130. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14131. };
  14132. // Statics
  14133. Scene._FOGMODE_NONE = 0;
  14134. Scene._FOGMODE_EXP = 1;
  14135. Scene._FOGMODE_EXP2 = 2;
  14136. Scene._FOGMODE_LINEAR = 3;
  14137. Scene.MinDeltaTime = 1.0;
  14138. Scene.MaxDeltaTime = 1000.0;
  14139. return Scene;
  14140. })();
  14141. BABYLON.Scene = Scene;
  14142. })(BABYLON || (BABYLON = {}));
  14143. var BABYLON;
  14144. (function (BABYLON) {
  14145. var VertexBuffer = (function () {
  14146. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14147. if (engine instanceof BABYLON.Mesh) {
  14148. this._engine = engine.getScene().getEngine();
  14149. }
  14150. else {
  14151. this._engine = engine;
  14152. }
  14153. this._updatable = updatable;
  14154. this._data = data;
  14155. if (!postponeInternalCreation) {
  14156. this.create();
  14157. }
  14158. this._kind = kind;
  14159. if (stride) {
  14160. this._strideSize = stride;
  14161. return;
  14162. }
  14163. // Deduce stride from kind
  14164. switch (kind) {
  14165. case VertexBuffer.PositionKind:
  14166. this._strideSize = 3;
  14167. break;
  14168. case VertexBuffer.NormalKind:
  14169. this._strideSize = 3;
  14170. break;
  14171. case VertexBuffer.UVKind:
  14172. case VertexBuffer.UV2Kind:
  14173. case VertexBuffer.UV3Kind:
  14174. case VertexBuffer.UV4Kind:
  14175. case VertexBuffer.UV5Kind:
  14176. case VertexBuffer.UV6Kind:
  14177. this._strideSize = 2;
  14178. break;
  14179. case VertexBuffer.ColorKind:
  14180. this._strideSize = 4;
  14181. break;
  14182. case VertexBuffer.MatricesIndicesKind:
  14183. this._strideSize = 4;
  14184. break;
  14185. case VertexBuffer.MatricesWeightsKind:
  14186. this._strideSize = 4;
  14187. break;
  14188. }
  14189. }
  14190. // Properties
  14191. VertexBuffer.prototype.isUpdatable = function () {
  14192. return this._updatable;
  14193. };
  14194. VertexBuffer.prototype.getData = function () {
  14195. return this._data;
  14196. };
  14197. VertexBuffer.prototype.getBuffer = function () {
  14198. return this._buffer;
  14199. };
  14200. VertexBuffer.prototype.getStrideSize = function () {
  14201. return this._strideSize;
  14202. };
  14203. // Methods
  14204. VertexBuffer.prototype.create = function (data) {
  14205. if (!data && this._buffer) {
  14206. return; // nothing to do
  14207. }
  14208. data = data || this._data;
  14209. if (!this._buffer) {
  14210. if (this._updatable) {
  14211. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14212. }
  14213. else {
  14214. this._buffer = this._engine.createVertexBuffer(data);
  14215. }
  14216. }
  14217. if (this._updatable) {
  14218. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14219. this._data = data;
  14220. }
  14221. };
  14222. VertexBuffer.prototype.update = function (data) {
  14223. this.create(data);
  14224. };
  14225. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14226. if (!this._buffer) {
  14227. return;
  14228. }
  14229. if (this._updatable) {
  14230. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14231. this._data = null;
  14232. }
  14233. };
  14234. VertexBuffer.prototype.dispose = function () {
  14235. if (!this._buffer) {
  14236. return;
  14237. }
  14238. if (this._engine._releaseBuffer(this._buffer)) {
  14239. this._buffer = null;
  14240. }
  14241. };
  14242. Object.defineProperty(VertexBuffer, "PositionKind", {
  14243. get: function () {
  14244. return VertexBuffer._PositionKind;
  14245. },
  14246. enumerable: true,
  14247. configurable: true
  14248. });
  14249. Object.defineProperty(VertexBuffer, "NormalKind", {
  14250. get: function () {
  14251. return VertexBuffer._NormalKind;
  14252. },
  14253. enumerable: true,
  14254. configurable: true
  14255. });
  14256. Object.defineProperty(VertexBuffer, "UVKind", {
  14257. get: function () {
  14258. return VertexBuffer._UVKind;
  14259. },
  14260. enumerable: true,
  14261. configurable: true
  14262. });
  14263. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14264. get: function () {
  14265. return VertexBuffer._UV2Kind;
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14271. get: function () {
  14272. return VertexBuffer._UV3Kind;
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14278. get: function () {
  14279. return VertexBuffer._UV4Kind;
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14285. get: function () {
  14286. return VertexBuffer._UV5Kind;
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14292. get: function () {
  14293. return VertexBuffer._UV6Kind;
  14294. },
  14295. enumerable: true,
  14296. configurable: true
  14297. });
  14298. Object.defineProperty(VertexBuffer, "ColorKind", {
  14299. get: function () {
  14300. return VertexBuffer._ColorKind;
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14306. get: function () {
  14307. return VertexBuffer._MatricesIndicesKind;
  14308. },
  14309. enumerable: true,
  14310. configurable: true
  14311. });
  14312. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14313. get: function () {
  14314. return VertexBuffer._MatricesWeightsKind;
  14315. },
  14316. enumerable: true,
  14317. configurable: true
  14318. });
  14319. // Enums
  14320. VertexBuffer._PositionKind = "position";
  14321. VertexBuffer._NormalKind = "normal";
  14322. VertexBuffer._UVKind = "uv";
  14323. VertexBuffer._UV2Kind = "uv2";
  14324. VertexBuffer._UV3Kind = "uv3";
  14325. VertexBuffer._UV4Kind = "uv4";
  14326. VertexBuffer._UV5Kind = "uv5";
  14327. VertexBuffer._UV6Kind = "uv6";
  14328. VertexBuffer._ColorKind = "color";
  14329. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14330. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14331. return VertexBuffer;
  14332. })();
  14333. BABYLON.VertexBuffer = VertexBuffer;
  14334. })(BABYLON || (BABYLON = {}));
  14335. var BABYLON;
  14336. (function (BABYLON) {
  14337. /**
  14338. * Creates an instance based on a source mesh.
  14339. */
  14340. var InstancedMesh = (function (_super) {
  14341. __extends(InstancedMesh, _super);
  14342. function InstancedMesh(name, source) {
  14343. _super.call(this, name, source.getScene());
  14344. source.instances.push(this);
  14345. this._sourceMesh = source;
  14346. this.position.copyFrom(source.position);
  14347. this.rotation.copyFrom(source.rotation);
  14348. this.scaling.copyFrom(source.scaling);
  14349. if (source.rotationQuaternion) {
  14350. this.rotationQuaternion = source.rotationQuaternion.clone();
  14351. }
  14352. this.infiniteDistance = source.infiniteDistance;
  14353. this.setPivotMatrix(source.getPivotMatrix());
  14354. this.refreshBoundingInfo();
  14355. this._syncSubMeshes();
  14356. }
  14357. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14358. // Methods
  14359. get: function () {
  14360. return this._sourceMesh.receiveShadows;
  14361. },
  14362. enumerable: true,
  14363. configurable: true
  14364. });
  14365. Object.defineProperty(InstancedMesh.prototype, "material", {
  14366. get: function () {
  14367. return this._sourceMesh.material;
  14368. },
  14369. enumerable: true,
  14370. configurable: true
  14371. });
  14372. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14373. get: function () {
  14374. return this._sourceMesh.visibility;
  14375. },
  14376. enumerable: true,
  14377. configurable: true
  14378. });
  14379. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14380. get: function () {
  14381. return this._sourceMesh.skeleton;
  14382. },
  14383. enumerable: true,
  14384. configurable: true
  14385. });
  14386. InstancedMesh.prototype.getTotalVertices = function () {
  14387. return this._sourceMesh.getTotalVertices();
  14388. };
  14389. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14390. get: function () {
  14391. return this._sourceMesh;
  14392. },
  14393. enumerable: true,
  14394. configurable: true
  14395. });
  14396. InstancedMesh.prototype.getVerticesData = function (kind) {
  14397. return this._sourceMesh.getVerticesData(kind);
  14398. };
  14399. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14400. return this._sourceMesh.isVerticesDataPresent(kind);
  14401. };
  14402. InstancedMesh.prototype.getIndices = function () {
  14403. return this._sourceMesh.getIndices();
  14404. };
  14405. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14406. get: function () {
  14407. return this._sourceMesh._positions;
  14408. },
  14409. enumerable: true,
  14410. configurable: true
  14411. });
  14412. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14413. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14414. if (data) {
  14415. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14416. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14417. }
  14418. this._updateBoundingInfo();
  14419. };
  14420. InstancedMesh.prototype._preActivate = function () {
  14421. if (this._currentLOD) {
  14422. this._currentLOD._preActivate();
  14423. }
  14424. };
  14425. InstancedMesh.prototype._activate = function (renderId) {
  14426. if (this._currentLOD) {
  14427. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14428. }
  14429. };
  14430. InstancedMesh.prototype.getLOD = function (camera) {
  14431. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14432. if (this._currentLOD === this.sourceMesh) {
  14433. return this;
  14434. }
  14435. return this._currentLOD;
  14436. };
  14437. InstancedMesh.prototype._syncSubMeshes = function () {
  14438. this.releaseSubMeshes();
  14439. if (this._sourceMesh.subMeshes) {
  14440. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14441. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14442. }
  14443. }
  14444. };
  14445. InstancedMesh.prototype._generatePointsArray = function () {
  14446. return this._sourceMesh._generatePointsArray();
  14447. };
  14448. // Clone
  14449. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14450. var result = this._sourceMesh.createInstance(name);
  14451. // Deep copy
  14452. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14453. // Bounding info
  14454. this.refreshBoundingInfo();
  14455. // Parent
  14456. if (newParent) {
  14457. result.parent = newParent;
  14458. }
  14459. if (!doNotCloneChildren) {
  14460. // Children
  14461. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14462. var mesh = this.getScene().meshes[index];
  14463. if (mesh.parent === this) {
  14464. mesh.clone(mesh.name, result);
  14465. }
  14466. }
  14467. }
  14468. result.computeWorldMatrix(true);
  14469. return result;
  14470. };
  14471. // Dispoe
  14472. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14473. // Remove from mesh
  14474. var index = this._sourceMesh.instances.indexOf(this);
  14475. this._sourceMesh.instances.splice(index, 1);
  14476. _super.prototype.dispose.call(this, doNotRecurse);
  14477. };
  14478. return InstancedMesh;
  14479. })(BABYLON.AbstractMesh);
  14480. BABYLON.InstancedMesh = InstancedMesh;
  14481. })(BABYLON || (BABYLON = {}));
  14482. var BABYLON;
  14483. (function (BABYLON) {
  14484. var _InstancesBatch = (function () {
  14485. function _InstancesBatch() {
  14486. this.mustReturn = false;
  14487. this.visibleInstances = new Array();
  14488. this.renderSelf = new Array();
  14489. }
  14490. return _InstancesBatch;
  14491. })();
  14492. BABYLON._InstancesBatch = _InstancesBatch;
  14493. var Mesh = (function (_super) {
  14494. __extends(Mesh, _super);
  14495. /**
  14496. * @constructor
  14497. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14498. * @param {Scene} scene - The scene to add this mesh to.
  14499. * @param {Node} parent - The parent of this mesh, if it has one
  14500. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14501. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14502. * When false, achieved by calling a clone(), also passing False.
  14503. * This will make creation of children, recursive.
  14504. */
  14505. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14506. if (parent === void 0) { parent = null; }
  14507. _super.call(this, name, scene);
  14508. // Members
  14509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14510. this.instances = new Array();
  14511. this._LODLevels = new Array();
  14512. this._onBeforeRenderCallbacks = new Array();
  14513. this._onAfterRenderCallbacks = new Array();
  14514. this._visibleInstances = {};
  14515. this._renderIdForInstances = new Array();
  14516. this._batchCache = new _InstancesBatch();
  14517. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14518. this._sideOrientation = Mesh._DEFAULTSIDE;
  14519. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14520. if (source) {
  14521. // Geometry
  14522. if (source._geometry) {
  14523. source._geometry.applyToMesh(this);
  14524. }
  14525. // Deep copy
  14526. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14527. this.id = name + "." + source.id;
  14528. // Material
  14529. this.material = source.material;
  14530. if (!doNotCloneChildren) {
  14531. // Children
  14532. for (var index = 0; index < scene.meshes.length; index++) {
  14533. var mesh = scene.meshes[index];
  14534. if (mesh.parent === source) {
  14535. // doNotCloneChildren is always going to be False
  14536. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14537. }
  14538. }
  14539. }
  14540. // Particles
  14541. for (index = 0; index < scene.particleSystems.length; index++) {
  14542. var system = scene.particleSystems[index];
  14543. if (system.emitter === source) {
  14544. system.clone(system.name, this);
  14545. }
  14546. }
  14547. this.computeWorldMatrix(true);
  14548. }
  14549. // Parent
  14550. if (parent !== null) {
  14551. this.parent = parent;
  14552. }
  14553. }
  14554. Object.defineProperty(Mesh, "FRONTSIDE", {
  14555. get: function () {
  14556. return Mesh._FRONTSIDE;
  14557. },
  14558. enumerable: true,
  14559. configurable: true
  14560. });
  14561. Object.defineProperty(Mesh, "BACKSIDE", {
  14562. get: function () {
  14563. return Mesh._BACKSIDE;
  14564. },
  14565. enumerable: true,
  14566. configurable: true
  14567. });
  14568. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14569. get: function () {
  14570. return Mesh._DOUBLESIDE;
  14571. },
  14572. enumerable: true,
  14573. configurable: true
  14574. });
  14575. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14576. get: function () {
  14577. return Mesh._DEFAULTSIDE;
  14578. },
  14579. enumerable: true,
  14580. configurable: true
  14581. });
  14582. Object.defineProperty(Mesh, "NO_CAP", {
  14583. get: function () {
  14584. return Mesh._NO_CAP;
  14585. },
  14586. enumerable: true,
  14587. configurable: true
  14588. });
  14589. Object.defineProperty(Mesh, "CAP_START", {
  14590. get: function () {
  14591. return Mesh._CAP_START;
  14592. },
  14593. enumerable: true,
  14594. configurable: true
  14595. });
  14596. Object.defineProperty(Mesh, "CAP_END", {
  14597. get: function () {
  14598. return Mesh._CAP_END;
  14599. },
  14600. enumerable: true,
  14601. configurable: true
  14602. });
  14603. Object.defineProperty(Mesh, "CAP_ALL", {
  14604. get: function () {
  14605. return Mesh._CAP_ALL;
  14606. },
  14607. enumerable: true,
  14608. configurable: true
  14609. });
  14610. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14611. // Methods
  14612. get: function () {
  14613. return this._LODLevels.length > 0;
  14614. },
  14615. enumerable: true,
  14616. configurable: true
  14617. });
  14618. Mesh.prototype._sortLODLevels = function () {
  14619. this._LODLevels.sort(function (a, b) {
  14620. if (a.distance < b.distance) {
  14621. return 1;
  14622. }
  14623. if (a.distance > b.distance) {
  14624. return -1;
  14625. }
  14626. return 0;
  14627. });
  14628. };
  14629. /**
  14630. * Add a mesh as LOD level triggered at the given distance.
  14631. * @param {number} distance - the distance from the center of the object to show this level
  14632. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14633. * @return {BABYLON.Mesh} this mesh (for chaining)
  14634. */
  14635. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14636. if (mesh && mesh._masterMesh) {
  14637. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14638. return this;
  14639. }
  14640. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14641. this._LODLevels.push(level);
  14642. if (mesh) {
  14643. mesh._masterMesh = this;
  14644. }
  14645. this._sortLODLevels();
  14646. return this;
  14647. };
  14648. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14649. for (var index = 0; index < this._LODLevels.length; index++) {
  14650. var level = this._LODLevels[index];
  14651. if (level.distance === distance) {
  14652. return level.mesh;
  14653. }
  14654. }
  14655. return null;
  14656. };
  14657. /**
  14658. * Remove a mesh from the LOD array
  14659. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14660. * @return {BABYLON.Mesh} this mesh (for chaining)
  14661. */
  14662. Mesh.prototype.removeLODLevel = function (mesh) {
  14663. for (var index = 0; index < this._LODLevels.length; index++) {
  14664. if (this._LODLevels[index].mesh === mesh) {
  14665. this._LODLevels.splice(index, 1);
  14666. if (mesh) {
  14667. mesh._masterMesh = null;
  14668. }
  14669. }
  14670. }
  14671. this._sortLODLevels();
  14672. return this;
  14673. };
  14674. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14675. if (!this._LODLevels || this._LODLevels.length === 0) {
  14676. return this;
  14677. }
  14678. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14679. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14680. if (this.onLODLevelSelection) {
  14681. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14682. }
  14683. return this;
  14684. }
  14685. for (var index = 0; index < this._LODLevels.length; index++) {
  14686. var level = this._LODLevels[index];
  14687. if (level.distance < distanceToCamera) {
  14688. if (level.mesh) {
  14689. level.mesh._preActivate();
  14690. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14691. }
  14692. if (this.onLODLevelSelection) {
  14693. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14694. }
  14695. return level.mesh;
  14696. }
  14697. }
  14698. if (this.onLODLevelSelection) {
  14699. this.onLODLevelSelection(distanceToCamera, this, this);
  14700. }
  14701. return this;
  14702. };
  14703. Object.defineProperty(Mesh.prototype, "geometry", {
  14704. get: function () {
  14705. return this._geometry;
  14706. },
  14707. enumerable: true,
  14708. configurable: true
  14709. });
  14710. Mesh.prototype.getTotalVertices = function () {
  14711. if (!this._geometry) {
  14712. return 0;
  14713. }
  14714. return this._geometry.getTotalVertices();
  14715. };
  14716. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14717. if (!this._geometry) {
  14718. return null;
  14719. }
  14720. return this._geometry.getVerticesData(kind, copyWhenShared);
  14721. };
  14722. Mesh.prototype.getVertexBuffer = function (kind) {
  14723. if (!this._geometry) {
  14724. return undefined;
  14725. }
  14726. return this._geometry.getVertexBuffer(kind);
  14727. };
  14728. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14729. if (!this._geometry) {
  14730. if (this._delayInfo) {
  14731. return this._delayInfo.indexOf(kind) !== -1;
  14732. }
  14733. return false;
  14734. }
  14735. return this._geometry.isVerticesDataPresent(kind);
  14736. };
  14737. Mesh.prototype.getVerticesDataKinds = function () {
  14738. if (!this._geometry) {
  14739. var result = [];
  14740. if (this._delayInfo) {
  14741. for (var kind in this._delayInfo) {
  14742. result.push(kind);
  14743. }
  14744. }
  14745. return result;
  14746. }
  14747. return this._geometry.getVerticesDataKinds();
  14748. };
  14749. Mesh.prototype.getTotalIndices = function () {
  14750. if (!this._geometry) {
  14751. return 0;
  14752. }
  14753. return this._geometry.getTotalIndices();
  14754. };
  14755. Mesh.prototype.getIndices = function (copyWhenShared) {
  14756. if (!this._geometry) {
  14757. return [];
  14758. }
  14759. return this._geometry.getIndices(copyWhenShared);
  14760. };
  14761. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14762. get: function () {
  14763. return this._masterMesh !== null && this._masterMesh !== undefined;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Mesh.prototype.isReady = function () {
  14769. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14770. return false;
  14771. }
  14772. return _super.prototype.isReady.call(this);
  14773. };
  14774. Mesh.prototype.isDisposed = function () {
  14775. return this._isDisposed;
  14776. };
  14777. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14778. get: function () {
  14779. return this._sideOrientation;
  14780. },
  14781. set: function (sideO) {
  14782. this._sideOrientation = sideO;
  14783. },
  14784. enumerable: true,
  14785. configurable: true
  14786. });
  14787. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14788. get: function () {
  14789. return this._areNormalsFrozen;
  14790. },
  14791. enumerable: true,
  14792. configurable: true
  14793. });
  14794. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14795. Mesh.prototype.freezeNormals = function () {
  14796. this._areNormalsFrozen = true;
  14797. };
  14798. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14799. Mesh.prototype.unfreezeNormals = function () {
  14800. this._areNormalsFrozen = false;
  14801. };
  14802. // Methods
  14803. Mesh.prototype._preActivate = function () {
  14804. var sceneRenderId = this.getScene().getRenderId();
  14805. if (this._preActivateId === sceneRenderId) {
  14806. return;
  14807. }
  14808. this._preActivateId = sceneRenderId;
  14809. this._visibleInstances = null;
  14810. };
  14811. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14812. if (!this._visibleInstances) {
  14813. this._visibleInstances = {};
  14814. this._visibleInstances.defaultRenderId = renderId;
  14815. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14816. }
  14817. if (!this._visibleInstances[renderId]) {
  14818. this._visibleInstances[renderId] = new Array();
  14819. }
  14820. this._visibleInstances[renderId].push(instance);
  14821. };
  14822. Mesh.prototype.refreshBoundingInfo = function () {
  14823. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14824. if (data) {
  14825. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14826. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14827. }
  14828. if (this.subMeshes) {
  14829. for (var index = 0; index < this.subMeshes.length; index++) {
  14830. this.subMeshes[index].refreshBoundingInfo();
  14831. }
  14832. }
  14833. this._updateBoundingInfo();
  14834. };
  14835. Mesh.prototype._createGlobalSubMesh = function () {
  14836. var totalVertices = this.getTotalVertices();
  14837. if (!totalVertices || !this.getIndices()) {
  14838. return null;
  14839. }
  14840. this.releaseSubMeshes();
  14841. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14842. };
  14843. Mesh.prototype.subdivide = function (count) {
  14844. if (count < 1) {
  14845. return;
  14846. }
  14847. var totalIndices = this.getTotalIndices();
  14848. var subdivisionSize = (totalIndices / count) | 0;
  14849. var offset = 0;
  14850. // Ensure that subdivisionSize is a multiple of 3
  14851. while (subdivisionSize % 3 !== 0) {
  14852. subdivisionSize++;
  14853. }
  14854. this.releaseSubMeshes();
  14855. for (var index = 0; index < count; index++) {
  14856. if (offset >= totalIndices) {
  14857. break;
  14858. }
  14859. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14860. offset += subdivisionSize;
  14861. }
  14862. this.synchronizeInstances();
  14863. };
  14864. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14865. if (kind instanceof Array) {
  14866. var temp = data;
  14867. data = kind;
  14868. kind = temp;
  14869. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14870. }
  14871. if (!this._geometry) {
  14872. var vertexData = new BABYLON.VertexData();
  14873. vertexData.set(data, kind);
  14874. var scene = this.getScene();
  14875. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14876. }
  14877. else {
  14878. this._geometry.setVerticesData(kind, data, updatable, stride);
  14879. }
  14880. };
  14881. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14882. if (!this._geometry) {
  14883. return;
  14884. }
  14885. if (!makeItUnique) {
  14886. this._geometry.updateVerticesData(kind, data, updateExtends);
  14887. }
  14888. else {
  14889. this.makeGeometryUnique();
  14890. this.updateVerticesData(kind, data, updateExtends, false);
  14891. }
  14892. };
  14893. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14894. if (!this._geometry) {
  14895. return;
  14896. }
  14897. if (!makeItUnique) {
  14898. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14899. }
  14900. else {
  14901. this.makeGeometryUnique();
  14902. this.updateVerticesDataDirectly(kind, data, offset, false);
  14903. }
  14904. };
  14905. // Mesh positions update function :
  14906. // updates the mesh positions according to the positionFunction returned values.
  14907. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14908. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14909. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14910. if (computeNormals === void 0) { computeNormals = true; }
  14911. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14912. positionFunction(positions);
  14913. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14914. if (computeNormals) {
  14915. var indices = this.getIndices();
  14916. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14917. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14918. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14919. }
  14920. };
  14921. Mesh.prototype.makeGeometryUnique = function () {
  14922. if (!this._geometry) {
  14923. return;
  14924. }
  14925. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14926. geometry.applyToMesh(this);
  14927. };
  14928. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14929. if (!this._geometry) {
  14930. var vertexData = new BABYLON.VertexData();
  14931. vertexData.indices = indices;
  14932. var scene = this.getScene();
  14933. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14934. }
  14935. else {
  14936. this._geometry.setIndices(indices, totalVertices);
  14937. }
  14938. };
  14939. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14940. var engine = this.getScene().getEngine();
  14941. // Wireframe
  14942. var indexToBind;
  14943. switch (fillMode) {
  14944. case BABYLON.Material.PointFillMode:
  14945. indexToBind = null;
  14946. break;
  14947. case BABYLON.Material.WireFrameFillMode:
  14948. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14949. break;
  14950. default:
  14951. case BABYLON.Material.TriangleFillMode:
  14952. indexToBind = this._geometry.getIndexBuffer();
  14953. break;
  14954. }
  14955. // VBOs
  14956. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14957. };
  14958. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14959. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14960. return;
  14961. }
  14962. var engine = this.getScene().getEngine();
  14963. // Draw order
  14964. switch (fillMode) {
  14965. case BABYLON.Material.PointFillMode:
  14966. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14967. break;
  14968. case BABYLON.Material.WireFrameFillMode:
  14969. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14970. break;
  14971. default:
  14972. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14973. }
  14974. };
  14975. Mesh.prototype.registerBeforeRender = function (func) {
  14976. this._onBeforeRenderCallbacks.push(func);
  14977. };
  14978. Mesh.prototype.unregisterBeforeRender = function (func) {
  14979. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14980. if (index > -1) {
  14981. this._onBeforeRenderCallbacks.splice(index, 1);
  14982. }
  14983. };
  14984. Mesh.prototype.registerAfterRender = function (func) {
  14985. this._onAfterRenderCallbacks.push(func);
  14986. };
  14987. Mesh.prototype.unregisterAfterRender = function (func) {
  14988. var index = this._onAfterRenderCallbacks.indexOf(func);
  14989. if (index > -1) {
  14990. this._onAfterRenderCallbacks.splice(index, 1);
  14991. }
  14992. };
  14993. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14994. var scene = this.getScene();
  14995. this._batchCache.mustReturn = false;
  14996. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14997. this._batchCache.visibleInstances[subMeshId] = null;
  14998. if (this._visibleInstances) {
  14999. var currentRenderId = scene.getRenderId();
  15000. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15001. var selfRenderId = this._renderId;
  15002. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15003. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15004. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15005. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15006. }
  15007. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15008. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15009. this._batchCache.mustReturn = true;
  15010. return this._batchCache;
  15011. }
  15012. if (currentRenderId !== selfRenderId) {
  15013. this._batchCache.renderSelf[subMeshId] = false;
  15014. }
  15015. }
  15016. this._renderIdForInstances[subMeshId] = currentRenderId;
  15017. }
  15018. return this._batchCache;
  15019. };
  15020. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15021. var visibleInstances = batch.visibleInstances[subMesh._id];
  15022. var matricesCount = visibleInstances.length + 1;
  15023. var bufferSize = matricesCount * 16 * 4;
  15024. while (this._instancesBufferSize < bufferSize) {
  15025. this._instancesBufferSize *= 2;
  15026. }
  15027. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15028. if (this._worldMatricesInstancesBuffer) {
  15029. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15030. }
  15031. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15032. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15033. }
  15034. var offset = 0;
  15035. var instancesCount = 0;
  15036. var world = this.getWorldMatrix();
  15037. if (batch.renderSelf[subMesh._id]) {
  15038. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15039. offset += 16;
  15040. instancesCount++;
  15041. }
  15042. if (visibleInstances) {
  15043. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15044. var instance = visibleInstances[instanceIndex];
  15045. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15046. offset += 16;
  15047. instancesCount++;
  15048. }
  15049. }
  15050. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15051. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15052. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15053. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15054. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15055. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15056. this._draw(subMesh, fillMode, instancesCount);
  15057. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15058. };
  15059. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15060. var scene = this.getScene();
  15061. var engine = scene.getEngine();
  15062. if (hardwareInstancedRendering) {
  15063. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15064. }
  15065. else {
  15066. if (batch.renderSelf[subMesh._id]) {
  15067. // Draw
  15068. if (onBeforeDraw) {
  15069. onBeforeDraw(false, this.getWorldMatrix());
  15070. }
  15071. this._draw(subMesh, fillMode);
  15072. }
  15073. if (batch.visibleInstances[subMesh._id]) {
  15074. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15075. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15076. // World
  15077. var world = instance.getWorldMatrix();
  15078. if (onBeforeDraw) {
  15079. onBeforeDraw(true, world);
  15080. }
  15081. // Draw
  15082. this._draw(subMesh, fillMode);
  15083. }
  15084. }
  15085. }
  15086. };
  15087. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15088. var scene = this.getScene();
  15089. // Managing instances
  15090. var batch = this._getInstancesRenderList(subMesh._id);
  15091. if (batch.mustReturn) {
  15092. return;
  15093. }
  15094. // Checking geometry state
  15095. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15096. return;
  15097. }
  15098. var callbackIndex;
  15099. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15100. this._onBeforeRenderCallbacks[callbackIndex](this);
  15101. }
  15102. var engine = scene.getEngine();
  15103. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15104. // Material
  15105. var effectiveMaterial = subMesh.getMaterial();
  15106. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15107. return;
  15108. }
  15109. // Outline - step 1
  15110. var savedDepthWrite = engine.getDepthWrite();
  15111. if (this.renderOutline) {
  15112. engine.setDepthWrite(false);
  15113. scene.getOutlineRenderer().render(subMesh, batch);
  15114. engine.setDepthWrite(savedDepthWrite);
  15115. }
  15116. effectiveMaterial._preBind();
  15117. var effect = effectiveMaterial.getEffect();
  15118. // Bind
  15119. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15120. this._bind(subMesh, effect, fillMode);
  15121. var world = this.getWorldMatrix();
  15122. effectiveMaterial.bind(world, this);
  15123. // Alpha mode
  15124. if (enableAlphaMode) {
  15125. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15126. }
  15127. // Draw
  15128. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15129. if (isInstance) {
  15130. effectiveMaterial.bindOnlyWorldMatrix(world);
  15131. }
  15132. });
  15133. // Unbind
  15134. effectiveMaterial.unbind();
  15135. // Outline - step 2
  15136. if (this.renderOutline && savedDepthWrite) {
  15137. engine.setDepthWrite(true);
  15138. engine.setColorWrite(false);
  15139. scene.getOutlineRenderer().render(subMesh, batch);
  15140. engine.setColorWrite(true);
  15141. }
  15142. // Overlay
  15143. if (this.renderOverlay) {
  15144. var currentMode = engine.getAlphaMode();
  15145. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15146. scene.getOutlineRenderer().render(subMesh, batch, true);
  15147. engine.setAlphaMode(currentMode);
  15148. }
  15149. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15150. this._onAfterRenderCallbacks[callbackIndex](this);
  15151. }
  15152. };
  15153. Mesh.prototype.getEmittedParticleSystems = function () {
  15154. var results = new Array();
  15155. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15156. var particleSystem = this.getScene().particleSystems[index];
  15157. if (particleSystem.emitter === this) {
  15158. results.push(particleSystem);
  15159. }
  15160. }
  15161. return results;
  15162. };
  15163. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15164. var results = new Array();
  15165. var descendants = this.getDescendants();
  15166. descendants.push(this);
  15167. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15168. var particleSystem = this.getScene().particleSystems[index];
  15169. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15170. results.push(particleSystem);
  15171. }
  15172. }
  15173. return results;
  15174. };
  15175. Mesh.prototype.getChildren = function () {
  15176. var results = [];
  15177. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15178. var mesh = this.getScene().meshes[index];
  15179. if (mesh.parent === this) {
  15180. results.push(mesh);
  15181. }
  15182. }
  15183. return results;
  15184. };
  15185. Mesh.prototype._checkDelayState = function () {
  15186. var _this = this;
  15187. var that = this;
  15188. var scene = this.getScene();
  15189. if (this._geometry) {
  15190. this._geometry.load(scene);
  15191. }
  15192. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15193. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15194. scene._addPendingData(that);
  15195. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15196. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15197. if (data instanceof ArrayBuffer) {
  15198. _this._delayLoadingFunction(data, _this);
  15199. }
  15200. else {
  15201. _this._delayLoadingFunction(JSON.parse(data), _this);
  15202. }
  15203. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15204. scene._removePendingData(_this);
  15205. }, function () { }, scene.database, getBinaryData);
  15206. }
  15207. };
  15208. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15209. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15210. return false;
  15211. }
  15212. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15213. return false;
  15214. }
  15215. this._checkDelayState();
  15216. return true;
  15217. };
  15218. Mesh.prototype.setMaterialByID = function (id) {
  15219. var materials = this.getScene().materials;
  15220. var index;
  15221. for (index = 0; index < materials.length; index++) {
  15222. if (materials[index].id === id) {
  15223. this.material = materials[index];
  15224. return;
  15225. }
  15226. }
  15227. // Multi
  15228. var multiMaterials = this.getScene().multiMaterials;
  15229. for (index = 0; index < multiMaterials.length; index++) {
  15230. if (multiMaterials[index].id === id) {
  15231. this.material = multiMaterials[index];
  15232. return;
  15233. }
  15234. }
  15235. };
  15236. Mesh.prototype.getAnimatables = function () {
  15237. var results = [];
  15238. if (this.material) {
  15239. results.push(this.material);
  15240. }
  15241. if (this.skeleton) {
  15242. results.push(this.skeleton);
  15243. }
  15244. return results;
  15245. };
  15246. // Geometry
  15247. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15248. // Position
  15249. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15250. return;
  15251. }
  15252. this._resetPointsArrayCache();
  15253. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15254. var temp = [];
  15255. var index;
  15256. for (index = 0; index < data.length; index += 3) {
  15257. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15258. }
  15259. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15260. // Normals
  15261. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15262. return;
  15263. }
  15264. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15265. temp = [];
  15266. for (index = 0; index < data.length; index += 3) {
  15267. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15268. }
  15269. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15270. // flip faces?
  15271. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15272. this.flipFaces();
  15273. }
  15274. };
  15275. // Will apply current transform to mesh and reset world matrix
  15276. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15277. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15278. this.scaling.copyFromFloats(1, 1, 1);
  15279. this.position.copyFromFloats(0, 0, 0);
  15280. this.rotation.copyFromFloats(0, 0, 0);
  15281. //only if quaternion is already set
  15282. if (this.rotationQuaternion) {
  15283. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15284. }
  15285. this._worldMatrix = BABYLON.Matrix.Identity();
  15286. };
  15287. // Cache
  15288. Mesh.prototype._resetPointsArrayCache = function () {
  15289. this._positions = null;
  15290. };
  15291. Mesh.prototype._generatePointsArray = function () {
  15292. if (this._positions)
  15293. return true;
  15294. this._positions = [];
  15295. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15296. if (!data) {
  15297. return false;
  15298. }
  15299. for (var index = 0; index < data.length; index += 3) {
  15300. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15301. }
  15302. return true;
  15303. };
  15304. // Clone
  15305. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15306. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15307. };
  15308. // Dispose
  15309. Mesh.prototype.dispose = function (doNotRecurse) {
  15310. if (this._geometry) {
  15311. this._geometry.releaseForMesh(this, true);
  15312. }
  15313. // Instances
  15314. if (this._worldMatricesInstancesBuffer) {
  15315. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15316. this._worldMatricesInstancesBuffer = null;
  15317. }
  15318. while (this.instances.length) {
  15319. this.instances[0].dispose();
  15320. }
  15321. _super.prototype.dispose.call(this, doNotRecurse);
  15322. };
  15323. // Geometric tools
  15324. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15325. var _this = this;
  15326. var scene = this.getScene();
  15327. var onload = function (img) {
  15328. // Getting height map data
  15329. var canvas = document.createElement("canvas");
  15330. var context = canvas.getContext("2d");
  15331. var heightMapWidth = img.width;
  15332. var heightMapHeight = img.height;
  15333. canvas.width = heightMapWidth;
  15334. canvas.height = heightMapHeight;
  15335. context.drawImage(img, 0, 0);
  15336. // Create VertexData from map data
  15337. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15338. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15339. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15340. //execute success callback, if set
  15341. if (onSuccess) {
  15342. onSuccess(_this);
  15343. }
  15344. };
  15345. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15346. };
  15347. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15348. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15349. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15350. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15351. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15352. return;
  15353. }
  15354. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15355. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15356. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15357. var position = BABYLON.Vector3.Zero();
  15358. var normal = BABYLON.Vector3.Zero();
  15359. var uv = BABYLON.Vector2.Zero();
  15360. for (var index = 0; index < positions.length; index += 3) {
  15361. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15362. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15363. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15364. // Compute height
  15365. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15366. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15367. var pos = (u + v * heightMapWidth) * 4;
  15368. var r = buffer[pos] / 255.0;
  15369. var g = buffer[pos + 1] / 255.0;
  15370. var b = buffer[pos + 2] / 255.0;
  15371. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15372. normal.normalize();
  15373. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15374. position = position.add(normal);
  15375. position.toArray(positions, index);
  15376. }
  15377. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15378. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15379. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15380. };
  15381. Mesh.prototype.convertToFlatShadedMesh = function () {
  15382. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15383. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15384. var kinds = this.getVerticesDataKinds();
  15385. var vbs = [];
  15386. var data = [];
  15387. var newdata = [];
  15388. var updatableNormals = false;
  15389. var kindIndex;
  15390. var kind;
  15391. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15392. kind = kinds[kindIndex];
  15393. var vertexBuffer = this.getVertexBuffer(kind);
  15394. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15395. updatableNormals = vertexBuffer.isUpdatable();
  15396. kinds.splice(kindIndex, 1);
  15397. kindIndex--;
  15398. continue;
  15399. }
  15400. vbs[kind] = vertexBuffer;
  15401. data[kind] = vbs[kind].getData();
  15402. newdata[kind] = [];
  15403. }
  15404. // Save previous submeshes
  15405. var previousSubmeshes = this.subMeshes.slice(0);
  15406. var indices = this.getIndices();
  15407. var totalIndices = this.getTotalIndices();
  15408. // Generating unique vertices per face
  15409. var index;
  15410. for (index = 0; index < totalIndices; index++) {
  15411. var vertexIndex = indices[index];
  15412. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15413. kind = kinds[kindIndex];
  15414. var stride = vbs[kind].getStrideSize();
  15415. for (var offset = 0; offset < stride; offset++) {
  15416. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15417. }
  15418. }
  15419. }
  15420. // Updating faces & normal
  15421. var normals = [];
  15422. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15423. for (index = 0; index < totalIndices; index += 3) {
  15424. indices[index] = index;
  15425. indices[index + 1] = index + 1;
  15426. indices[index + 2] = index + 2;
  15427. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15428. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15429. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15430. var p1p2 = p1.subtract(p2);
  15431. var p3p2 = p3.subtract(p2);
  15432. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15433. // Store same normals for every vertex
  15434. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15435. normals.push(normal.x);
  15436. normals.push(normal.y);
  15437. normals.push(normal.z);
  15438. }
  15439. }
  15440. this.setIndices(indices);
  15441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15442. // Updating vertex buffers
  15443. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15444. kind = kinds[kindIndex];
  15445. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15446. }
  15447. // Updating submeshes
  15448. this.releaseSubMeshes();
  15449. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15450. var previousOne = previousSubmeshes[submeshIndex];
  15451. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15452. }
  15453. this.synchronizeInstances();
  15454. };
  15455. // will inverse faces orientations, and invert normals too if specified
  15456. Mesh.prototype.flipFaces = function (flipNormals) {
  15457. if (flipNormals === void 0) { flipNormals = false; }
  15458. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15459. var i;
  15460. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15461. for (i = 0; i < vertex_data.normals.length; i++) {
  15462. vertex_data.normals[i] *= -1;
  15463. }
  15464. }
  15465. var temp;
  15466. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15467. // reassign indices
  15468. temp = vertex_data.indices[i + 1];
  15469. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15470. vertex_data.indices[i + 2] = temp;
  15471. }
  15472. vertex_data.applyToMesh(this);
  15473. };
  15474. // Instances
  15475. Mesh.prototype.createInstance = function (name) {
  15476. return new BABYLON.InstancedMesh(name, this);
  15477. };
  15478. Mesh.prototype.synchronizeInstances = function () {
  15479. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15480. var instance = this.instances[instanceIndex];
  15481. instance._syncSubMeshes();
  15482. }
  15483. };
  15484. /**
  15485. * Simplify the mesh according to the given array of settings.
  15486. * Function will return immediately and will simplify async.
  15487. * @param settings a collection of simplification settings.
  15488. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15489. * @param type the type of simplification to run.
  15490. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15491. */
  15492. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15493. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15494. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15495. this.getScene().simplificationQueue.addTask({
  15496. settings: settings,
  15497. parallelProcessing: parallelProcessing,
  15498. mesh: this,
  15499. simplificationType: simplificationType,
  15500. successCallback: successCallback
  15501. });
  15502. };
  15503. /**
  15504. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15505. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15506. * This should be used together with the simplification to avoid disappearing triangles.
  15507. * @param successCallback an optional success callback to be called after the optimization finished.
  15508. */
  15509. Mesh.prototype.optimizeIndices = function (successCallback) {
  15510. var _this = this;
  15511. var indices = this.getIndices();
  15512. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15513. var vectorPositions = [];
  15514. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15515. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15516. }
  15517. var dupes = [];
  15518. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15519. var realPos = vectorPositions.length - 1 - iteration;
  15520. var testedPosition = vectorPositions[realPos];
  15521. for (var j = 0; j < realPos; ++j) {
  15522. var againstPosition = vectorPositions[j];
  15523. if (testedPosition.equals(againstPosition)) {
  15524. dupes[realPos] = j;
  15525. break;
  15526. }
  15527. }
  15528. }, function () {
  15529. for (var i = 0; i < indices.length; ++i) {
  15530. indices[i] = dupes[indices[i]] || indices[i];
  15531. }
  15532. //indices are now reordered
  15533. var originalSubMeshes = _this.subMeshes.slice(0);
  15534. _this.setIndices(indices);
  15535. _this.subMeshes = originalSubMeshes;
  15536. if (successCallback) {
  15537. successCallback(_this);
  15538. }
  15539. });
  15540. };
  15541. // Statics
  15542. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15543. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15544. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15545. if (ribbonInstance) {
  15546. // positionFunction : ribbon case
  15547. // only pathArray and sideOrientation parameters are taken into account for positions update
  15548. var positionFunction = function (positions) {
  15549. var minlg = pathArray[0].length;
  15550. var i = 0;
  15551. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15552. for (var si = 1; si <= ns; si++) {
  15553. for (var p = 0; p < pathArray.length; p++) {
  15554. var path = pathArray[p];
  15555. var l = path.length;
  15556. minlg = (minlg < l) ? minlg : l;
  15557. var j = 0;
  15558. while (j < minlg) {
  15559. positions[i] = path[j].x;
  15560. positions[i + 1] = path[j].y;
  15561. positions[i + 2] = path[j].z;
  15562. j++;
  15563. i += 3;
  15564. }
  15565. if (ribbonInstance._closePath) {
  15566. positions[i] = path[0].x;
  15567. positions[i + 1] = path[0].y;
  15568. positions[i + 2] = path[0].z;
  15569. i += 3;
  15570. }
  15571. }
  15572. }
  15573. };
  15574. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15575. positionFunction(positions);
  15576. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15577. if (!(ribbonInstance.areNormalsFrozen)) {
  15578. var indices = ribbonInstance.getIndices();
  15579. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15580. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15581. if (ribbonInstance._closePath) {
  15582. var indexFirst = 0;
  15583. var indexLast = 0;
  15584. for (var p = 0; p < pathArray.length; p++) {
  15585. indexFirst = ribbonInstance._idx[p] * 3;
  15586. if (p + 1 < pathArray.length) {
  15587. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15588. }
  15589. else {
  15590. indexLast = normals.length - 3;
  15591. }
  15592. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15593. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15594. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15595. normals[indexLast] = normals[indexFirst];
  15596. normals[indexLast + 1] = normals[indexFirst + 1];
  15597. normals[indexLast + 2] = normals[indexFirst + 2];
  15598. }
  15599. }
  15600. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15601. }
  15602. return ribbonInstance;
  15603. }
  15604. else {
  15605. var ribbon = new Mesh(name, scene);
  15606. ribbon.sideOrientation = sideOrientation;
  15607. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15608. if (closePath) {
  15609. ribbon._idx = vertexData._idx;
  15610. }
  15611. ribbon._closePath = closePath;
  15612. vertexData.applyToMesh(ribbon, updatable);
  15613. return ribbon;
  15614. }
  15615. };
  15616. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15617. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15618. var disc = new Mesh(name, scene);
  15619. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15620. vertexData.applyToMesh(disc, updatable);
  15621. return disc;
  15622. };
  15623. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15624. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15625. // Check parameters
  15626. updatable = updatable || options.updatable;
  15627. var box = new Mesh(name, scene);
  15628. var vertexData = BABYLON.VertexData.CreateBox(options, sideOrientation);
  15629. vertexData.applyToMesh(box, updatable);
  15630. return box;
  15631. };
  15632. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15633. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15634. if (diameterOrScene instanceof BABYLON.Scene) {
  15635. scene = diameterOrScene;
  15636. updatable = options.updatable;
  15637. }
  15638. else {
  15639. var segments = options;
  15640. options = {
  15641. segments: segments,
  15642. diameterX: diameterOrScene,
  15643. diameterY: diameterOrScene,
  15644. diameterZ: diameterOrScene,
  15645. sideOrientation: sideOrientation
  15646. };
  15647. }
  15648. var sphere = new Mesh(name, scene);
  15649. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15650. vertexData.applyToMesh(sphere, updatable);
  15651. return sphere;
  15652. };
  15653. // Cylinder and cone
  15654. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15655. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15656. // subdivisions is a new parameter, we need to support old signature
  15657. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15658. if (scene !== undefined) {
  15659. updatable = scene;
  15660. }
  15661. scene = subdivisions;
  15662. subdivisions = 1;
  15663. }
  15664. var cylinder = new Mesh(name, scene);
  15665. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15666. vertexData.applyToMesh(cylinder, updatable);
  15667. return cylinder;
  15668. };
  15669. // Torus (Code from SharpDX.org)
  15670. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15671. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15672. var torus = new Mesh(name, scene);
  15673. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15674. vertexData.applyToMesh(torus, updatable);
  15675. return torus;
  15676. };
  15677. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15678. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15679. var torusKnot = new Mesh(name, scene);
  15680. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15681. vertexData.applyToMesh(torusKnot, updatable);
  15682. return torusKnot;
  15683. };
  15684. // Lines
  15685. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15686. if (linesInstance === void 0) { linesInstance = null; }
  15687. if (linesInstance) {
  15688. var positionFunction = function (positions) {
  15689. var i = 0;
  15690. for (var p = 0; p < points.length; p++) {
  15691. positions[i] = points[p].x;
  15692. positions[i + 1] = points[p].y;
  15693. positions[i + 2] = points[p].z;
  15694. i += 3;
  15695. }
  15696. };
  15697. linesInstance.updateMeshPositions(positionFunction, false);
  15698. return linesInstance;
  15699. }
  15700. // lines creation
  15701. var lines = new BABYLON.LinesMesh(name, scene);
  15702. var vertexData = BABYLON.VertexData.CreateLines(points);
  15703. vertexData.applyToMesh(lines, updatable);
  15704. return lines;
  15705. };
  15706. // Dashed Lines
  15707. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15708. if (linesInstance === void 0) { linesInstance = null; }
  15709. if (linesInstance) {
  15710. var positionFunction = function (positions) {
  15711. var curvect = BABYLON.Vector3.Zero();
  15712. var nbSeg = positions.length / 6;
  15713. var lg = 0;
  15714. var nb = 0;
  15715. var shft = 0;
  15716. var dashshft = 0;
  15717. var curshft = 0;
  15718. var p = 0;
  15719. var i = 0;
  15720. var j = 0;
  15721. for (i = 0; i < points.length - 1; i++) {
  15722. points[i + 1].subtractToRef(points[i], curvect);
  15723. lg += curvect.length();
  15724. }
  15725. shft = lg / nbSeg;
  15726. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15727. for (i = 0; i < points.length - 1; i++) {
  15728. points[i + 1].subtractToRef(points[i], curvect);
  15729. nb = Math.floor(curvect.length() / shft);
  15730. curvect.normalize();
  15731. j = 0;
  15732. while (j < nb && p < positions.length) {
  15733. curshft = shft * j;
  15734. positions[p] = points[i].x + curshft * curvect.x;
  15735. positions[p + 1] = points[i].y + curshft * curvect.y;
  15736. positions[p + 2] = points[i].z + curshft * curvect.z;
  15737. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15738. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15739. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15740. p += 6;
  15741. j++;
  15742. }
  15743. }
  15744. while (p < positions.length) {
  15745. positions[p] = points[i].x;
  15746. positions[p + 1] = points[i].y;
  15747. positions[p + 2] = points[i].z;
  15748. p += 3;
  15749. }
  15750. };
  15751. linesInstance.updateMeshPositions(positionFunction, false);
  15752. return linesInstance;
  15753. }
  15754. // dashed lines creation
  15755. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15756. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15757. vertexData.applyToMesh(dashedLines, updatable);
  15758. dashedLines.dashSize = dashSize;
  15759. dashedLines.gapSize = gapSize;
  15760. return dashedLines;
  15761. };
  15762. // Extrusion
  15763. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15764. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15765. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15766. scale = scale || 1;
  15767. rotation = rotation || 0;
  15768. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15769. return extruded;
  15770. };
  15771. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15772. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15773. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15774. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15775. return extrudedCustom;
  15776. };
  15777. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15778. // extrusion geometry
  15779. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15780. var tangents = path3D.getTangents();
  15781. var normals = path3D.getNormals();
  15782. var binormals = path3D.getBinormals();
  15783. var distances = path3D.getDistances();
  15784. var angle = 0;
  15785. var returnScale = function (i, distance) { return scale; };
  15786. var returnRotation = function (i, distance) { return rotation; };
  15787. var rotate = custom ? rotateFunction : returnRotation;
  15788. var scl = custom ? scaleFunction : returnScale;
  15789. var index = 0;
  15790. for (var i = 0; i < curve.length; i++) {
  15791. var shapePath = new Array();
  15792. var angleStep = rotate(i, distances[i]);
  15793. var scaleRatio = scl(i, distances[i]);
  15794. for (var p = 0; p < shape.length; p++) {
  15795. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15796. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15797. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15798. shapePath.push(rotated);
  15799. }
  15800. shapePaths[index] = shapePath;
  15801. angle += angleStep;
  15802. index++;
  15803. }
  15804. // cap
  15805. var capPath = function (shapePath) {
  15806. var pointCap = Array();
  15807. var barycenter = BABYLON.Vector3.Zero();
  15808. var i;
  15809. for (i = 0; i < shapePath.length; i++) {
  15810. barycenter.addInPlace(shapePath[i]);
  15811. }
  15812. barycenter.scaleInPlace(1 / shapePath.length);
  15813. for (i = 0; i < shapePath.length; i++) {
  15814. pointCap.push(barycenter);
  15815. }
  15816. return pointCap;
  15817. };
  15818. switch (cap) {
  15819. case Mesh.NO_CAP:
  15820. break;
  15821. case Mesh.CAP_START:
  15822. shapePaths.unshift(capPath(shapePaths[0]));
  15823. break;
  15824. case Mesh.CAP_END:
  15825. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15826. break;
  15827. case Mesh.CAP_ALL:
  15828. shapePaths.unshift(capPath(shapePaths[0]));
  15829. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15830. break;
  15831. default:
  15832. break;
  15833. }
  15834. return shapePaths;
  15835. };
  15836. var path3D;
  15837. var pathArray;
  15838. if (instance) {
  15839. path3D = (instance.path3D).update(curve);
  15840. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15841. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15842. return instance;
  15843. }
  15844. // extruded shape creation
  15845. path3D = new BABYLON.Path3D(curve);
  15846. var newShapePaths = new Array();
  15847. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15848. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15849. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15850. extrudedGeneric.pathArray = pathArray;
  15851. extrudedGeneric.path3D = path3D;
  15852. extrudedGeneric.cap = cap;
  15853. return extrudedGeneric;
  15854. };
  15855. // Lathe
  15856. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15857. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15858. radius = radius || 1;
  15859. tessellation = tessellation || radius * 60;
  15860. var pi2 = Math.PI * 2;
  15861. var shapeLathe = new Array();
  15862. // first rotatable point
  15863. var i = 0;
  15864. while (shape[i].x === 0) {
  15865. i++;
  15866. }
  15867. var pt = shape[i];
  15868. for (i = 0; i < shape.length; i++) {
  15869. shapeLathe.push(shape[i].subtract(pt));
  15870. }
  15871. // circle path
  15872. var step = pi2 / tessellation;
  15873. var rotated;
  15874. var path = new Array();
  15875. ;
  15876. for (i = 0; i < tessellation; i++) {
  15877. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15878. path.push(rotated);
  15879. }
  15880. path.push(path[0]);
  15881. // extrusion
  15882. var scaleFunction = function () { return 1; };
  15883. var rotateFunction = function () { return 0; };
  15884. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15885. return lathe;
  15886. };
  15887. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  15888. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15889. var plane = new Mesh(name, scene);
  15890. var vertexData = BABYLON.VertexData.CreatePlane(options, sideOrientation);
  15891. vertexData.applyToMesh(plane, updatable || options.updatable);
  15892. return plane;
  15893. };
  15894. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  15895. if (heightOrScene instanceof BABYLON.Scene) {
  15896. scene = heightOrScene;
  15897. updatable = options.updatable;
  15898. }
  15899. else {
  15900. var width = options;
  15901. options = {
  15902. width: width,
  15903. height: heightOrScene,
  15904. subdivisions: subdivisions
  15905. };
  15906. }
  15907. var ground = new BABYLON.GroundMesh(name, scene);
  15908. ground._setReady(false);
  15909. ground._subdivisions = options.subdivisions || 1;
  15910. var vertexData = BABYLON.VertexData.CreateGround(options);
  15911. vertexData.applyToMesh(ground, updatable || options.updatable);
  15912. ground._setReady(true);
  15913. return ground;
  15914. };
  15915. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15916. var tiledGround = new Mesh(name, scene);
  15917. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15918. vertexData.applyToMesh(tiledGround, updatable);
  15919. return tiledGround;
  15920. };
  15921. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15922. var ground = new BABYLON.GroundMesh(name, scene);
  15923. ground._subdivisions = subdivisions;
  15924. ground._setReady(false);
  15925. var onload = function (img) {
  15926. // Getting height map data
  15927. var canvas = document.createElement("canvas");
  15928. var context = canvas.getContext("2d");
  15929. var heightMapWidth = img.width;
  15930. var heightMapHeight = img.height;
  15931. canvas.width = heightMapWidth;
  15932. canvas.height = heightMapHeight;
  15933. context.drawImage(img, 0, 0);
  15934. // Create VertexData from map data
  15935. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15936. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15937. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15938. vertexData.applyToMesh(ground, updatable);
  15939. ground._setReady(true);
  15940. //execute ready callback, if set
  15941. if (onReady) {
  15942. onReady(ground);
  15943. }
  15944. };
  15945. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15946. return ground;
  15947. };
  15948. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15949. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15950. if (tubeInstance === void 0) { tubeInstance = null; }
  15951. // tube geometry
  15952. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15953. var tangents = path3D.getTangents();
  15954. var normals = path3D.getNormals();
  15955. var distances = path3D.getDistances();
  15956. var pi2 = Math.PI * 2;
  15957. var step = pi2 / tessellation;
  15958. var returnRadius = function (i, distance) { return radius; };
  15959. var radiusFunctionFinal = radiusFunction || returnRadius;
  15960. var circlePath;
  15961. var rad;
  15962. var normal;
  15963. var rotated;
  15964. var rotationMatrix;
  15965. var index = 0;
  15966. for (var i = 0; i < path.length; i++) {
  15967. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15968. circlePath = Array(); // current circle array
  15969. normal = normals[i]; // current normal
  15970. for (var t = 0; t < tessellation; t++) {
  15971. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15972. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15973. circlePath.push(rotated);
  15974. }
  15975. circlePaths[index] = circlePath;
  15976. index++;
  15977. }
  15978. // cap
  15979. var capPath = function (nbPoints, pathIndex) {
  15980. var pointCap = Array();
  15981. for (var i = 0; i < nbPoints; i++) {
  15982. pointCap.push(path[pathIndex]);
  15983. }
  15984. return pointCap;
  15985. };
  15986. switch (cap) {
  15987. case Mesh.NO_CAP:
  15988. break;
  15989. case Mesh.CAP_START:
  15990. circlePaths.unshift(capPath(tessellation + 1, 0));
  15991. break;
  15992. case Mesh.CAP_END:
  15993. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15994. break;
  15995. case Mesh.CAP_ALL:
  15996. circlePaths.unshift(capPath(tessellation + 1, 0));
  15997. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15998. break;
  15999. default:
  16000. break;
  16001. }
  16002. return circlePaths;
  16003. };
  16004. var path3D;
  16005. var pathArray;
  16006. if (tubeInstance) {
  16007. path3D = (tubeInstance.path3D).update(path);
  16008. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  16009. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  16010. return tubeInstance;
  16011. }
  16012. // tube creation
  16013. path3D = new BABYLON.Path3D(path);
  16014. var newPathArray = new Array();
  16015. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16016. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  16017. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  16018. tube.pathArray = pathArray;
  16019. tube.path3D = path3D;
  16020. tube.tessellation = tessellation;
  16021. tube.cap = cap;
  16022. return tube;
  16023. };
  16024. // Decals
  16025. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16026. if (angle === void 0) { angle = 0; }
  16027. var indices = sourceMesh.getIndices();
  16028. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16029. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16030. // Getting correct rotation
  16031. if (!normal) {
  16032. var target = new BABYLON.Vector3(0, 0, 1);
  16033. var camera = sourceMesh.getScene().activeCamera;
  16034. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16035. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16036. }
  16037. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16038. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16039. var pitch = Math.atan2(normal.y, len);
  16040. // Matrix
  16041. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16042. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16043. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16044. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16045. var vertexData = new BABYLON.VertexData();
  16046. vertexData.indices = [];
  16047. vertexData.positions = [];
  16048. vertexData.normals = [];
  16049. vertexData.uvs = [];
  16050. var currentVertexDataIndex = 0;
  16051. var extractDecalVector3 = function (indexId) {
  16052. var vertexId = indices[indexId];
  16053. var result = new BABYLON.PositionNormalVertex();
  16054. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16055. // Send vector to decal local world
  16056. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16057. // Get normal
  16058. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16059. return result;
  16060. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16061. var clip = function (vertices, axis) {
  16062. if (vertices.length === 0) {
  16063. return vertices;
  16064. }
  16065. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16066. var clipVertices = function (v0, v1) {
  16067. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16068. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16069. };
  16070. var result = new Array();
  16071. for (var index = 0; index < vertices.length; index += 3) {
  16072. var v1Out;
  16073. var v2Out;
  16074. var v3Out;
  16075. var total = 0;
  16076. var nV1, nV2, nV3, nV4;
  16077. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16078. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16079. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16080. v1Out = d1 > 0;
  16081. v2Out = d2 > 0;
  16082. v3Out = d3 > 0;
  16083. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16084. switch (total) {
  16085. case 0:
  16086. result.push(vertices[index]);
  16087. result.push(vertices[index + 1]);
  16088. result.push(vertices[index + 2]);
  16089. break;
  16090. case 1:
  16091. if (v1Out) {
  16092. nV1 = vertices[index + 1];
  16093. nV2 = vertices[index + 2];
  16094. nV3 = clipVertices(vertices[index], nV1);
  16095. nV4 = clipVertices(vertices[index], nV2);
  16096. }
  16097. if (v2Out) {
  16098. nV1 = vertices[index];
  16099. nV2 = vertices[index + 2];
  16100. nV3 = clipVertices(vertices[index + 1], nV1);
  16101. nV4 = clipVertices(vertices[index + 1], nV2);
  16102. result.push(nV3);
  16103. result.push(nV2.clone());
  16104. result.push(nV1.clone());
  16105. result.push(nV2.clone());
  16106. result.push(nV3.clone());
  16107. result.push(nV4);
  16108. break;
  16109. }
  16110. if (v3Out) {
  16111. nV1 = vertices[index];
  16112. nV2 = vertices[index + 1];
  16113. nV3 = clipVertices(vertices[index + 2], nV1);
  16114. nV4 = clipVertices(vertices[index + 2], nV2);
  16115. }
  16116. result.push(nV1.clone());
  16117. result.push(nV2.clone());
  16118. result.push(nV3);
  16119. result.push(nV4);
  16120. result.push(nV3.clone());
  16121. result.push(nV2.clone());
  16122. break;
  16123. case 2:
  16124. if (!v1Out) {
  16125. nV1 = vertices[index].clone();
  16126. nV2 = clipVertices(nV1, vertices[index + 1]);
  16127. nV3 = clipVertices(nV1, vertices[index + 2]);
  16128. result.push(nV1);
  16129. result.push(nV2);
  16130. result.push(nV3);
  16131. }
  16132. if (!v2Out) {
  16133. nV1 = vertices[index + 1].clone();
  16134. nV2 = clipVertices(nV1, vertices[index + 2]);
  16135. nV3 = clipVertices(nV1, vertices[index]);
  16136. result.push(nV1);
  16137. result.push(nV2);
  16138. result.push(nV3);
  16139. }
  16140. if (!v3Out) {
  16141. nV1 = vertices[index + 2].clone();
  16142. nV2 = clipVertices(nV1, vertices[index]);
  16143. nV3 = clipVertices(nV1, vertices[index + 1]);
  16144. result.push(nV1);
  16145. result.push(nV2);
  16146. result.push(nV3);
  16147. }
  16148. break;
  16149. case 3:
  16150. break;
  16151. }
  16152. }
  16153. return result;
  16154. };
  16155. for (var index = 0; index < indices.length; index += 3) {
  16156. var faceVertices = new Array();
  16157. faceVertices.push(extractDecalVector3(index));
  16158. faceVertices.push(extractDecalVector3(index + 1));
  16159. faceVertices.push(extractDecalVector3(index + 2));
  16160. // Clip
  16161. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16162. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16163. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16164. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16165. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16166. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16167. if (faceVertices.length === 0) {
  16168. continue;
  16169. }
  16170. // Add UVs and get back to world
  16171. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16172. var vertex = faceVertices[vIndex];
  16173. vertexData.indices.push(currentVertexDataIndex);
  16174. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16175. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16176. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16177. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16178. currentVertexDataIndex++;
  16179. }
  16180. }
  16181. // Return mesh
  16182. var decal = new Mesh(name, sourceMesh.getScene());
  16183. vertexData.applyToMesh(decal);
  16184. decal.position = position.clone();
  16185. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16186. return decal;
  16187. };
  16188. // Skeletons
  16189. /**
  16190. * Update the vertex buffers by applying transformation from the bones
  16191. * @param {skeleton} skeleton to apply
  16192. */
  16193. Mesh.prototype.applySkeleton = function (skeleton) {
  16194. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16195. return this;
  16196. }
  16197. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16198. return this;
  16199. }
  16200. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16201. return this;
  16202. }
  16203. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16204. return this;
  16205. }
  16206. var source;
  16207. if (!this._sourcePositions) {
  16208. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16209. this._sourcePositions = new Float32Array(source);
  16210. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16211. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16212. }
  16213. }
  16214. if (!this._sourceNormals) {
  16215. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16216. this._sourceNormals = new Float32Array(source);
  16217. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16218. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16219. }
  16220. }
  16221. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16222. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16223. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16224. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16225. var skeletonMatrices = skeleton.getTransformMatrices();
  16226. var tempVector3 = BABYLON.Vector3.Zero();
  16227. var finalMatrix = new BABYLON.Matrix();
  16228. var tempMatrix = new BABYLON.Matrix();
  16229. for (var index = 0; index < positionsData.length; index += 3) {
  16230. var index4 = (index / 3) * 4;
  16231. var matricesWeight0 = matricesWeightsData[index4];
  16232. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16233. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16234. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16235. if (matricesWeight0 > 0) {
  16236. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16237. finalMatrix.addToSelf(tempMatrix);
  16238. }
  16239. if (matricesWeight1 > 0) {
  16240. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16241. finalMatrix.addToSelf(tempMatrix);
  16242. }
  16243. if (matricesWeight2 > 0) {
  16244. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16245. finalMatrix.addToSelf(tempMatrix);
  16246. }
  16247. if (matricesWeight3 > 0) {
  16248. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16249. finalMatrix.addToSelf(tempMatrix);
  16250. }
  16251. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16252. tempVector3.toArray(positionsData, index);
  16253. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16254. tempVector3.toArray(normalsData, index);
  16255. finalMatrix.reset();
  16256. }
  16257. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16258. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16259. return this;
  16260. };
  16261. // Tools
  16262. Mesh.MinMax = function (meshes) {
  16263. var minVector = null;
  16264. var maxVector = null;
  16265. for (var i in meshes) {
  16266. var mesh = meshes[i];
  16267. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16268. if (!minVector) {
  16269. minVector = boundingBox.minimumWorld;
  16270. maxVector = boundingBox.maximumWorld;
  16271. continue;
  16272. }
  16273. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16274. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16275. }
  16276. return {
  16277. min: minVector,
  16278. max: maxVector
  16279. };
  16280. };
  16281. Mesh.Center = function (meshesOrMinMaxVector) {
  16282. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16283. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16284. };
  16285. /**
  16286. * Merge the array of meshes into a single mesh for performance reasons.
  16287. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16288. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16289. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16290. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16291. */
  16292. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16293. if (disposeSource === void 0) { disposeSource = true; }
  16294. var index;
  16295. if (!allow32BitsIndices) {
  16296. var totalVertices = 0;
  16297. // Counting vertices
  16298. for (index = 0; index < meshes.length; index++) {
  16299. if (meshes[index]) {
  16300. totalVertices += meshes[index].getTotalVertices();
  16301. if (totalVertices > 65536) {
  16302. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16303. return null;
  16304. }
  16305. }
  16306. }
  16307. }
  16308. // Merge
  16309. var vertexData;
  16310. var otherVertexData;
  16311. var source;
  16312. for (index = 0; index < meshes.length; index++) {
  16313. if (meshes[index]) {
  16314. meshes[index].computeWorldMatrix(true);
  16315. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16316. otherVertexData.transform(meshes[index].getWorldMatrix());
  16317. if (vertexData) {
  16318. vertexData.merge(otherVertexData);
  16319. }
  16320. else {
  16321. vertexData = otherVertexData;
  16322. source = meshes[index];
  16323. }
  16324. }
  16325. }
  16326. if (!meshSubclass) {
  16327. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16328. }
  16329. vertexData.applyToMesh(meshSubclass);
  16330. // Setting properties
  16331. meshSubclass.material = source.material;
  16332. meshSubclass.checkCollisions = source.checkCollisions;
  16333. // Cleaning
  16334. if (disposeSource) {
  16335. for (index = 0; index < meshes.length; index++) {
  16336. if (meshes[index]) {
  16337. meshes[index].dispose();
  16338. }
  16339. }
  16340. }
  16341. return meshSubclass;
  16342. };
  16343. // Consts
  16344. Mesh._FRONTSIDE = 0;
  16345. Mesh._BACKSIDE = 1;
  16346. Mesh._DOUBLESIDE = 2;
  16347. Mesh._DEFAULTSIDE = 0;
  16348. Mesh._NO_CAP = 0;
  16349. Mesh._CAP_START = 1;
  16350. Mesh._CAP_END = 2;
  16351. Mesh._CAP_ALL = 3;
  16352. return Mesh;
  16353. })(BABYLON.AbstractMesh);
  16354. BABYLON.Mesh = Mesh;
  16355. })(BABYLON || (BABYLON = {}));
  16356. var BABYLON;
  16357. (function (BABYLON) {
  16358. var SubMesh = (function () {
  16359. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16360. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16361. this.materialIndex = materialIndex;
  16362. this.verticesStart = verticesStart;
  16363. this.verticesCount = verticesCount;
  16364. this.indexStart = indexStart;
  16365. this.indexCount = indexCount;
  16366. this._renderId = 0;
  16367. this._mesh = mesh;
  16368. this._renderingMesh = renderingMesh || mesh;
  16369. mesh.subMeshes.push(this);
  16370. this._trianglePlanes = [];
  16371. this._id = mesh.subMeshes.length - 1;
  16372. if (createBoundingBox) {
  16373. this.refreshBoundingInfo();
  16374. mesh.computeWorldMatrix(true);
  16375. }
  16376. }
  16377. SubMesh.prototype.getBoundingInfo = function () {
  16378. return this._boundingInfo;
  16379. };
  16380. SubMesh.prototype.getMesh = function () {
  16381. return this._mesh;
  16382. };
  16383. SubMesh.prototype.getRenderingMesh = function () {
  16384. return this._renderingMesh;
  16385. };
  16386. SubMesh.prototype.getMaterial = function () {
  16387. var rootMaterial = this._renderingMesh.material;
  16388. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16389. var multiMaterial = rootMaterial;
  16390. return multiMaterial.getSubMaterial(this.materialIndex);
  16391. }
  16392. if (!rootMaterial) {
  16393. return this._mesh.getScene().defaultMaterial;
  16394. }
  16395. return rootMaterial;
  16396. };
  16397. // Methods
  16398. SubMesh.prototype.refreshBoundingInfo = function () {
  16399. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16400. if (!data) {
  16401. this._boundingInfo = this._mesh._boundingInfo;
  16402. return;
  16403. }
  16404. var indices = this._renderingMesh.getIndices();
  16405. var extend;
  16406. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16407. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16408. }
  16409. else {
  16410. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16411. }
  16412. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16413. };
  16414. SubMesh.prototype._checkCollision = function (collider) {
  16415. return this._boundingInfo._checkCollision(collider);
  16416. };
  16417. SubMesh.prototype.updateBoundingInfo = function (world) {
  16418. if (!this._boundingInfo) {
  16419. this.refreshBoundingInfo();
  16420. }
  16421. this._boundingInfo._update(world);
  16422. };
  16423. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16424. return this._boundingInfo.isInFrustum(frustumPlanes);
  16425. };
  16426. SubMesh.prototype.render = function (enableAlphaMode) {
  16427. this._renderingMesh.render(this, enableAlphaMode);
  16428. };
  16429. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16430. if (!this._linesIndexBuffer) {
  16431. var linesIndices = [];
  16432. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16433. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16434. }
  16435. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16436. this.linesIndexCount = linesIndices.length;
  16437. }
  16438. return this._linesIndexBuffer;
  16439. };
  16440. SubMesh.prototype.canIntersects = function (ray) {
  16441. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16442. };
  16443. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16444. var intersectInfo = null;
  16445. // Triangles test
  16446. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16447. var p0 = positions[indices[index]];
  16448. var p1 = positions[indices[index + 1]];
  16449. var p2 = positions[indices[index + 2]];
  16450. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16451. if (currentIntersectInfo) {
  16452. if (currentIntersectInfo.distance < 0) {
  16453. continue;
  16454. }
  16455. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16456. intersectInfo = currentIntersectInfo;
  16457. intersectInfo.faceId = index / 3;
  16458. if (fastCheck) {
  16459. break;
  16460. }
  16461. }
  16462. }
  16463. }
  16464. return intersectInfo;
  16465. };
  16466. // Clone
  16467. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16468. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16469. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16470. return result;
  16471. };
  16472. // Dispose
  16473. SubMesh.prototype.dispose = function () {
  16474. if (this._linesIndexBuffer) {
  16475. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16476. this._linesIndexBuffer = null;
  16477. }
  16478. // Remove from mesh
  16479. var index = this._mesh.subMeshes.indexOf(this);
  16480. this._mesh.subMeshes.splice(index, 1);
  16481. };
  16482. // Statics
  16483. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16484. var minVertexIndex = Number.MAX_VALUE;
  16485. var maxVertexIndex = -Number.MAX_VALUE;
  16486. renderingMesh = renderingMesh || mesh;
  16487. var indices = renderingMesh.getIndices();
  16488. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16489. var vertexIndex = indices[index];
  16490. if (vertexIndex < minVertexIndex)
  16491. minVertexIndex = vertexIndex;
  16492. if (vertexIndex > maxVertexIndex)
  16493. maxVertexIndex = vertexIndex;
  16494. }
  16495. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16496. };
  16497. return SubMesh;
  16498. })();
  16499. BABYLON.SubMesh = SubMesh;
  16500. })(BABYLON || (BABYLON = {}));
  16501. var BABYLON;
  16502. (function (BABYLON) {
  16503. var BaseTexture = (function () {
  16504. function BaseTexture(scene) {
  16505. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16506. this.hasAlpha = false;
  16507. this.getAlphaFromRGB = false;
  16508. this.level = 1;
  16509. this.isCube = false;
  16510. this.isRenderTarget = false;
  16511. this.animations = new Array();
  16512. this.coordinatesIndex = 0;
  16513. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16514. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16515. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16516. this.anisotropicFilteringLevel = 4;
  16517. this._scene = scene;
  16518. this._scene.textures.push(this);
  16519. }
  16520. BaseTexture.prototype.getScene = function () {
  16521. return this._scene;
  16522. };
  16523. BaseTexture.prototype.getTextureMatrix = function () {
  16524. return null;
  16525. };
  16526. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16527. return null;
  16528. };
  16529. BaseTexture.prototype.getInternalTexture = function () {
  16530. return this._texture;
  16531. };
  16532. BaseTexture.prototype.isReady = function () {
  16533. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16534. return true;
  16535. }
  16536. if (this._texture) {
  16537. return this._texture.isReady;
  16538. }
  16539. return false;
  16540. };
  16541. BaseTexture.prototype.getSize = function () {
  16542. if (this._texture._width) {
  16543. return { width: this._texture._width, height: this._texture._height };
  16544. }
  16545. if (this._texture._size) {
  16546. return { width: this._texture._size, height: this._texture._size };
  16547. }
  16548. return { width: 0, height: 0 };
  16549. };
  16550. BaseTexture.prototype.getBaseSize = function () {
  16551. if (!this.isReady())
  16552. return { width: 0, height: 0 };
  16553. if (this._texture._size) {
  16554. return { width: this._texture._size, height: this._texture._size };
  16555. }
  16556. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16557. };
  16558. BaseTexture.prototype.scale = function (ratio) {
  16559. };
  16560. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16561. get: function () {
  16562. return false;
  16563. },
  16564. enumerable: true,
  16565. configurable: true
  16566. });
  16567. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16568. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16569. for (var index = 0; index < texturesCache.length; index++) {
  16570. var texturesCacheEntry = texturesCache[index];
  16571. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16572. texturesCache.splice(index, 1);
  16573. return;
  16574. }
  16575. }
  16576. };
  16577. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16578. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16579. for (var index = 0; index < texturesCache.length; index++) {
  16580. var texturesCacheEntry = texturesCache[index];
  16581. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16582. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16583. texturesCacheEntry.references++;
  16584. return texturesCacheEntry;
  16585. }
  16586. }
  16587. }
  16588. return null;
  16589. };
  16590. BaseTexture.prototype.delayLoad = function () {
  16591. };
  16592. BaseTexture.prototype.releaseInternalTexture = function () {
  16593. if (!this._texture) {
  16594. return;
  16595. }
  16596. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16597. this._texture.references--;
  16598. // Final reference ?
  16599. if (this._texture.references === 0) {
  16600. var index = texturesCache.indexOf(this._texture);
  16601. texturesCache.splice(index, 1);
  16602. this._scene.getEngine()._releaseTexture(this._texture);
  16603. delete this._texture;
  16604. }
  16605. };
  16606. BaseTexture.prototype.clone = function () {
  16607. return null;
  16608. };
  16609. BaseTexture.prototype.dispose = function () {
  16610. // Remove from scene
  16611. var index = this._scene.textures.indexOf(this);
  16612. if (index >= 0) {
  16613. this._scene.textures.splice(index, 1);
  16614. }
  16615. if (this._texture === undefined) {
  16616. return;
  16617. }
  16618. this.releaseInternalTexture();
  16619. // Callback
  16620. if (this.onDispose) {
  16621. this.onDispose();
  16622. }
  16623. };
  16624. return BaseTexture;
  16625. })();
  16626. BABYLON.BaseTexture = BaseTexture;
  16627. })(BABYLON || (BABYLON = {}));
  16628. var BABYLON;
  16629. (function (BABYLON) {
  16630. var Texture = (function (_super) {
  16631. __extends(Texture, _super);
  16632. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16633. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16634. if (onLoad === void 0) { onLoad = null; }
  16635. if (onError === void 0) { onError = null; }
  16636. if (buffer === void 0) { buffer = null; }
  16637. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16638. _super.call(this, scene);
  16639. this.uOffset = 0;
  16640. this.vOffset = 0;
  16641. this.uScale = 1.0;
  16642. this.vScale = 1.0;
  16643. this.uAng = 0;
  16644. this.vAng = 0;
  16645. this.wAng = 0;
  16646. this.name = url;
  16647. this.url = url;
  16648. this._noMipmap = noMipmap;
  16649. this._invertY = invertY;
  16650. this._samplingMode = samplingMode;
  16651. this._buffer = buffer;
  16652. this._deleteBuffer = deleteBuffer;
  16653. if (!url) {
  16654. return;
  16655. }
  16656. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16657. if (!this._texture) {
  16658. if (!scene.useDelayedTextureLoading) {
  16659. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16660. if (deleteBuffer) {
  16661. delete this._buffer;
  16662. }
  16663. }
  16664. else {
  16665. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16666. }
  16667. }
  16668. else {
  16669. BABYLON.Tools.SetImmediate(function () {
  16670. if (onLoad) {
  16671. onLoad();
  16672. }
  16673. });
  16674. }
  16675. }
  16676. Texture.prototype.delayLoad = function () {
  16677. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16678. return;
  16679. }
  16680. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16681. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16682. if (!this._texture) {
  16683. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16684. if (this._deleteBuffer) {
  16685. delete this._buffer;
  16686. }
  16687. }
  16688. };
  16689. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16690. if (!this._texture) {
  16691. return;
  16692. }
  16693. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16694. };
  16695. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16696. x *= this.uScale;
  16697. y *= this.vScale;
  16698. x -= 0.5 * this.uScale;
  16699. y -= 0.5 * this.vScale;
  16700. z -= 0.5;
  16701. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16702. t.x += 0.5 * this.uScale + this.uOffset;
  16703. t.y += 0.5 * this.vScale + this.vOffset;
  16704. t.z += 0.5;
  16705. };
  16706. Texture.prototype.getTextureMatrix = function () {
  16707. if (this.uOffset === this._cachedUOffset &&
  16708. this.vOffset === this._cachedVOffset &&
  16709. this.uScale === this._cachedUScale &&
  16710. this.vScale === this._cachedVScale &&
  16711. this.uAng === this._cachedUAng &&
  16712. this.vAng === this._cachedVAng &&
  16713. this.wAng === this._cachedWAng) {
  16714. return this._cachedTextureMatrix;
  16715. }
  16716. this._cachedUOffset = this.uOffset;
  16717. this._cachedVOffset = this.vOffset;
  16718. this._cachedUScale = this.uScale;
  16719. this._cachedVScale = this.vScale;
  16720. this._cachedUAng = this.uAng;
  16721. this._cachedVAng = this.vAng;
  16722. this._cachedWAng = this.wAng;
  16723. if (!this._cachedTextureMatrix) {
  16724. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16725. this._rowGenerationMatrix = new BABYLON.Matrix();
  16726. this._t0 = BABYLON.Vector3.Zero();
  16727. this._t1 = BABYLON.Vector3.Zero();
  16728. this._t2 = BABYLON.Vector3.Zero();
  16729. }
  16730. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16731. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16732. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16733. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16734. this._t1.subtractInPlace(this._t0);
  16735. this._t2.subtractInPlace(this._t0);
  16736. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16737. this._cachedTextureMatrix.m[0] = this._t1.x;
  16738. this._cachedTextureMatrix.m[1] = this._t1.y;
  16739. this._cachedTextureMatrix.m[2] = this._t1.z;
  16740. this._cachedTextureMatrix.m[4] = this._t2.x;
  16741. this._cachedTextureMatrix.m[5] = this._t2.y;
  16742. this._cachedTextureMatrix.m[6] = this._t2.z;
  16743. this._cachedTextureMatrix.m[8] = this._t0.x;
  16744. this._cachedTextureMatrix.m[9] = this._t0.y;
  16745. this._cachedTextureMatrix.m[10] = this._t0.z;
  16746. return this._cachedTextureMatrix;
  16747. };
  16748. Texture.prototype.getReflectionTextureMatrix = function () {
  16749. if (this.uOffset === this._cachedUOffset &&
  16750. this.vOffset === this._cachedVOffset &&
  16751. this.uScale === this._cachedUScale &&
  16752. this.vScale === this._cachedVScale &&
  16753. this.coordinatesMode === this._cachedCoordinatesMode) {
  16754. return this._cachedTextureMatrix;
  16755. }
  16756. if (!this._cachedTextureMatrix) {
  16757. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16758. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16759. }
  16760. this._cachedCoordinatesMode = this.coordinatesMode;
  16761. switch (this.coordinatesMode) {
  16762. case Texture.SPHERICAL_MODE:
  16763. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16764. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16765. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16766. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16767. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16768. break;
  16769. case Texture.PLANAR_MODE:
  16770. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16771. this._cachedTextureMatrix[0] = this.uScale;
  16772. this._cachedTextureMatrix[5] = this.vScale;
  16773. this._cachedTextureMatrix[12] = this.uOffset;
  16774. this._cachedTextureMatrix[13] = this.vOffset;
  16775. break;
  16776. case Texture.PROJECTION_MODE:
  16777. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16778. this._projectionModeMatrix.m[0] = 0.5;
  16779. this._projectionModeMatrix.m[5] = -0.5;
  16780. this._projectionModeMatrix.m[10] = 0.0;
  16781. this._projectionModeMatrix.m[12] = 0.5;
  16782. this._projectionModeMatrix.m[13] = 0.5;
  16783. this._projectionModeMatrix.m[14] = 1.0;
  16784. this._projectionModeMatrix.m[15] = 1.0;
  16785. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16786. break;
  16787. default:
  16788. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16789. break;
  16790. }
  16791. return this._cachedTextureMatrix;
  16792. };
  16793. Texture.prototype.clone = function () {
  16794. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16795. // Base texture
  16796. newTexture.hasAlpha = this.hasAlpha;
  16797. newTexture.level = this.level;
  16798. newTexture.wrapU = this.wrapU;
  16799. newTexture.wrapV = this.wrapV;
  16800. newTexture.coordinatesIndex = this.coordinatesIndex;
  16801. newTexture.coordinatesMode = this.coordinatesMode;
  16802. // Texture
  16803. newTexture.uOffset = this.uOffset;
  16804. newTexture.vOffset = this.vOffset;
  16805. newTexture.uScale = this.uScale;
  16806. newTexture.vScale = this.vScale;
  16807. newTexture.uAng = this.uAng;
  16808. newTexture.vAng = this.vAng;
  16809. newTexture.wAng = this.wAng;
  16810. return newTexture;
  16811. };
  16812. // Statics
  16813. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16814. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16815. if (onLoad === void 0) { onLoad = null; }
  16816. if (onError === void 0) { onError = null; }
  16817. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16818. };
  16819. // Constants
  16820. Texture.NEAREST_SAMPLINGMODE = 1;
  16821. Texture.BILINEAR_SAMPLINGMODE = 2;
  16822. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16823. Texture.EXPLICIT_MODE = 0;
  16824. Texture.SPHERICAL_MODE = 1;
  16825. Texture.PLANAR_MODE = 2;
  16826. Texture.CUBIC_MODE = 3;
  16827. Texture.PROJECTION_MODE = 4;
  16828. Texture.SKYBOX_MODE = 5;
  16829. Texture.CLAMP_ADDRESSMODE = 0;
  16830. Texture.WRAP_ADDRESSMODE = 1;
  16831. Texture.MIRROR_ADDRESSMODE = 2;
  16832. return Texture;
  16833. })(BABYLON.BaseTexture);
  16834. BABYLON.Texture = Texture;
  16835. })(BABYLON || (BABYLON = {}));
  16836. var BABYLON;
  16837. (function (BABYLON) {
  16838. var CubeTexture = (function (_super) {
  16839. __extends(CubeTexture, _super);
  16840. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16841. _super.call(this, scene);
  16842. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16843. this.name = rootUrl;
  16844. this.url = rootUrl;
  16845. this._noMipmap = noMipmap;
  16846. this.hasAlpha = false;
  16847. this._texture = this._getFromCache(rootUrl, noMipmap);
  16848. if (!extensions) {
  16849. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16850. }
  16851. this._extensions = extensions;
  16852. if (!this._texture) {
  16853. if (!scene.useDelayedTextureLoading) {
  16854. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16855. }
  16856. else {
  16857. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16858. }
  16859. }
  16860. this.isCube = true;
  16861. this._textureMatrix = BABYLON.Matrix.Identity();
  16862. }
  16863. CubeTexture.prototype.clone = function () {
  16864. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16865. // Base texture
  16866. newTexture.level = this.level;
  16867. newTexture.wrapU = this.wrapU;
  16868. newTexture.wrapV = this.wrapV;
  16869. newTexture.coordinatesIndex = this.coordinatesIndex;
  16870. newTexture.coordinatesMode = this.coordinatesMode;
  16871. return newTexture;
  16872. };
  16873. // Methods
  16874. CubeTexture.prototype.delayLoad = function () {
  16875. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16876. return;
  16877. }
  16878. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16879. this._texture = this._getFromCache(this.url, this._noMipmap);
  16880. if (!this._texture) {
  16881. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16882. }
  16883. };
  16884. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16885. return this._textureMatrix;
  16886. };
  16887. return CubeTexture;
  16888. })(BABYLON.BaseTexture);
  16889. BABYLON.CubeTexture = CubeTexture;
  16890. })(BABYLON || (BABYLON = {}));
  16891. var BABYLON;
  16892. (function (BABYLON) {
  16893. var RenderTargetTexture = (function (_super) {
  16894. __extends(RenderTargetTexture, _super);
  16895. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16896. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16897. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16898. _super.call(this, null, scene, !generateMipMaps);
  16899. this.renderList = new Array();
  16900. this.renderParticles = true;
  16901. this.renderSprites = false;
  16902. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16903. this._currentRefreshId = -1;
  16904. this._refreshRate = 1;
  16905. this.name = name;
  16906. this.isRenderTarget = true;
  16907. this._size = size;
  16908. this._generateMipMaps = generateMipMaps;
  16909. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16910. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16911. // Rendering groups
  16912. this._renderingManager = new BABYLON.RenderingManager(scene);
  16913. }
  16914. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16915. this._currentRefreshId = -1;
  16916. };
  16917. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16918. get: function () {
  16919. return this._refreshRate;
  16920. },
  16921. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16922. set: function (value) {
  16923. this._refreshRate = value;
  16924. this.resetRefreshCounter();
  16925. },
  16926. enumerable: true,
  16927. configurable: true
  16928. });
  16929. RenderTargetTexture.prototype._shouldRender = function () {
  16930. if (this._currentRefreshId === -1) {
  16931. this._currentRefreshId = 1;
  16932. return true;
  16933. }
  16934. if (this.refreshRate === this._currentRefreshId) {
  16935. this._currentRefreshId = 1;
  16936. return true;
  16937. }
  16938. this._currentRefreshId++;
  16939. return false;
  16940. };
  16941. RenderTargetTexture.prototype.isReady = function () {
  16942. if (!this.getScene().renderTargetsEnabled) {
  16943. return false;
  16944. }
  16945. return _super.prototype.isReady.call(this);
  16946. };
  16947. RenderTargetTexture.prototype.getRenderSize = function () {
  16948. return this._size;
  16949. };
  16950. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16951. get: function () {
  16952. return true;
  16953. },
  16954. enumerable: true,
  16955. configurable: true
  16956. });
  16957. RenderTargetTexture.prototype.scale = function (ratio) {
  16958. var newSize = this._size * ratio;
  16959. this.resize(newSize, this._generateMipMaps);
  16960. };
  16961. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16962. this.releaseInternalTexture();
  16963. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16964. };
  16965. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16966. var scene = this.getScene();
  16967. var engine = scene.getEngine();
  16968. if (this._waitingRenderList) {
  16969. this.renderList = [];
  16970. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16971. var id = this._waitingRenderList[index];
  16972. this.renderList.push(scene.getMeshByID(id));
  16973. }
  16974. delete this._waitingRenderList;
  16975. }
  16976. if (this.renderList && this.renderList.length === 0) {
  16977. return;
  16978. }
  16979. // Bind
  16980. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16981. engine.bindFramebuffer(this._texture);
  16982. }
  16983. this._renderingManager.reset();
  16984. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16985. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16986. var mesh = currentRenderList[meshIndex];
  16987. if (mesh) {
  16988. if (!mesh.isReady()) {
  16989. // Reset _currentRefreshId
  16990. this.resetRefreshCounter();
  16991. continue;
  16992. }
  16993. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16994. mesh._activate(scene.getRenderId());
  16995. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16996. var subMesh = mesh.subMeshes[subIndex];
  16997. scene._activeIndices += subMesh.indexCount;
  16998. this._renderingManager.dispatch(subMesh);
  16999. }
  17000. }
  17001. }
  17002. }
  17003. if (this.onBeforeRender) {
  17004. this.onBeforeRender();
  17005. }
  17006. // Clear
  17007. if (this.onClear) {
  17008. this.onClear(engine);
  17009. }
  17010. else {
  17011. engine.clear(scene.clearColor, true, true);
  17012. }
  17013. if (!this._doNotChangeAspectRatio) {
  17014. scene.updateTransformMatrix(true);
  17015. }
  17016. // Render
  17017. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17018. if (useCameraPostProcess) {
  17019. scene.postProcessManager._finalizeFrame(false, this._texture);
  17020. }
  17021. if (!this._doNotChangeAspectRatio) {
  17022. scene.updateTransformMatrix(true);
  17023. }
  17024. if (this.onAfterRender) {
  17025. this.onAfterRender();
  17026. }
  17027. // Dump ?
  17028. if (dumpForDebug) {
  17029. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17030. }
  17031. // Unbind
  17032. engine.unBindFramebuffer(this._texture);
  17033. if (this.onAfterUnbind) {
  17034. this.onAfterUnbind();
  17035. }
  17036. };
  17037. RenderTargetTexture.prototype.clone = function () {
  17038. var textureSize = this.getSize();
  17039. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17040. // Base texture
  17041. newTexture.hasAlpha = this.hasAlpha;
  17042. newTexture.level = this.level;
  17043. // RenderTarget Texture
  17044. newTexture.coordinatesMode = this.coordinatesMode;
  17045. newTexture.renderList = this.renderList.slice(0);
  17046. return newTexture;
  17047. };
  17048. return RenderTargetTexture;
  17049. })(BABYLON.Texture);
  17050. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17051. })(BABYLON || (BABYLON = {}));
  17052. var BABYLON;
  17053. (function (BABYLON) {
  17054. var ProceduralTexture = (function (_super) {
  17055. __extends(ProceduralTexture, _super);
  17056. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17057. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17058. _super.call(this, null, scene, !generateMipMaps);
  17059. this.isEnabled = true;
  17060. this._currentRefreshId = -1;
  17061. this._refreshRate = 1;
  17062. this._vertexDeclaration = [2];
  17063. this._vertexStrideSize = 2 * 4;
  17064. this._uniforms = new Array();
  17065. this._samplers = new Array();
  17066. this._textures = new Array();
  17067. this._floats = new Array();
  17068. this._floatsArrays = {};
  17069. this._colors3 = new Array();
  17070. this._colors4 = new Array();
  17071. this._vectors2 = new Array();
  17072. this._vectors3 = new Array();
  17073. this._matrices = new Array();
  17074. this._fallbackTextureUsed = false;
  17075. scene._proceduralTextures.push(this);
  17076. this.name = name;
  17077. this.isRenderTarget = true;
  17078. this._size = size;
  17079. this._generateMipMaps = generateMipMaps;
  17080. this.setFragment(fragment);
  17081. this._fallbackTexture = fallbackTexture;
  17082. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17083. // VBO
  17084. var vertices = [];
  17085. vertices.push(1, 1);
  17086. vertices.push(-1, 1);
  17087. vertices.push(-1, -1);
  17088. vertices.push(1, -1);
  17089. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17090. // Indices
  17091. var indices = [];
  17092. indices.push(0);
  17093. indices.push(1);
  17094. indices.push(2);
  17095. indices.push(0);
  17096. indices.push(2);
  17097. indices.push(3);
  17098. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17099. }
  17100. ProceduralTexture.prototype.reset = function () {
  17101. if (this._effect === undefined) {
  17102. return;
  17103. }
  17104. var engine = this.getScene().getEngine();
  17105. engine._releaseEffect(this._effect);
  17106. };
  17107. ProceduralTexture.prototype.isReady = function () {
  17108. var _this = this;
  17109. var engine = this.getScene().getEngine();
  17110. var shaders;
  17111. if (!this._fragment) {
  17112. return false;
  17113. }
  17114. if (this._fallbackTextureUsed) {
  17115. return true;
  17116. }
  17117. if (this._fragment.fragmentElement !== undefined) {
  17118. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17119. }
  17120. else {
  17121. shaders = { vertex: "procedural", fragment: this._fragment };
  17122. }
  17123. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17124. _this.releaseInternalTexture();
  17125. if (_this._fallbackTexture) {
  17126. _this._texture = _this._fallbackTexture._texture;
  17127. _this._texture.references++;
  17128. }
  17129. _this._fallbackTextureUsed = true;
  17130. });
  17131. return this._effect.isReady();
  17132. };
  17133. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17134. this._currentRefreshId = -1;
  17135. };
  17136. ProceduralTexture.prototype.setFragment = function (fragment) {
  17137. this._fragment = fragment;
  17138. };
  17139. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17140. get: function () {
  17141. return this._refreshRate;
  17142. },
  17143. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17144. set: function (value) {
  17145. this._refreshRate = value;
  17146. this.resetRefreshCounter();
  17147. },
  17148. enumerable: true,
  17149. configurable: true
  17150. });
  17151. ProceduralTexture.prototype._shouldRender = function () {
  17152. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17153. return false;
  17154. }
  17155. if (this._fallbackTextureUsed) {
  17156. return false;
  17157. }
  17158. if (this._currentRefreshId === -1) {
  17159. this._currentRefreshId = 1;
  17160. return true;
  17161. }
  17162. if (this.refreshRate === this._currentRefreshId) {
  17163. this._currentRefreshId = 1;
  17164. return true;
  17165. }
  17166. this._currentRefreshId++;
  17167. return false;
  17168. };
  17169. ProceduralTexture.prototype.getRenderSize = function () {
  17170. return this._size;
  17171. };
  17172. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17173. if (this._fallbackTextureUsed) {
  17174. return;
  17175. }
  17176. this.releaseInternalTexture();
  17177. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17178. };
  17179. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17180. if (this._uniforms.indexOf(uniformName) === -1) {
  17181. this._uniforms.push(uniformName);
  17182. }
  17183. };
  17184. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17185. if (this._samplers.indexOf(name) === -1) {
  17186. this._samplers.push(name);
  17187. }
  17188. this._textures[name] = texture;
  17189. return this;
  17190. };
  17191. ProceduralTexture.prototype.setFloat = function (name, value) {
  17192. this._checkUniform(name);
  17193. this._floats[name] = value;
  17194. return this;
  17195. };
  17196. ProceduralTexture.prototype.setFloats = function (name, value) {
  17197. this._checkUniform(name);
  17198. this._floatsArrays[name] = value;
  17199. return this;
  17200. };
  17201. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17202. this._checkUniform(name);
  17203. this._colors3[name] = value;
  17204. return this;
  17205. };
  17206. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17207. this._checkUniform(name);
  17208. this._colors4[name] = value;
  17209. return this;
  17210. };
  17211. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17212. this._checkUniform(name);
  17213. this._vectors2[name] = value;
  17214. return this;
  17215. };
  17216. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17217. this._checkUniform(name);
  17218. this._vectors3[name] = value;
  17219. return this;
  17220. };
  17221. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17222. this._checkUniform(name);
  17223. this._matrices[name] = value;
  17224. return this;
  17225. };
  17226. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17227. var scene = this.getScene();
  17228. var engine = scene.getEngine();
  17229. engine.bindFramebuffer(this._texture);
  17230. // Clear
  17231. engine.clear(scene.clearColor, true, true);
  17232. // Render
  17233. engine.enableEffect(this._effect);
  17234. engine.setState(false);
  17235. // Texture
  17236. for (var name in this._textures) {
  17237. this._effect.setTexture(name, this._textures[name]);
  17238. }
  17239. // Float
  17240. for (name in this._floats) {
  17241. this._effect.setFloat(name, this._floats[name]);
  17242. }
  17243. // Floats
  17244. for (name in this._floatsArrays) {
  17245. this._effect.setArray(name, this._floatsArrays[name]);
  17246. }
  17247. // Color3
  17248. for (name in this._colors3) {
  17249. this._effect.setColor3(name, this._colors3[name]);
  17250. }
  17251. // Color4
  17252. for (name in this._colors4) {
  17253. var color = this._colors4[name];
  17254. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17255. }
  17256. // Vector2
  17257. for (name in this._vectors2) {
  17258. this._effect.setVector2(name, this._vectors2[name]);
  17259. }
  17260. // Vector3
  17261. for (name in this._vectors3) {
  17262. this._effect.setVector3(name, this._vectors3[name]);
  17263. }
  17264. // Matrix
  17265. for (name in this._matrices) {
  17266. this._effect.setMatrix(name, this._matrices[name]);
  17267. }
  17268. // VBOs
  17269. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17270. // Draw order
  17271. engine.draw(true, 0, 6);
  17272. // Unbind
  17273. engine.unBindFramebuffer(this._texture);
  17274. };
  17275. ProceduralTexture.prototype.clone = function () {
  17276. var textureSize = this.getSize();
  17277. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17278. // Base texture
  17279. newTexture.hasAlpha = this.hasAlpha;
  17280. newTexture.level = this.level;
  17281. // RenderTarget Texture
  17282. newTexture.coordinatesMode = this.coordinatesMode;
  17283. return newTexture;
  17284. };
  17285. ProceduralTexture.prototype.dispose = function () {
  17286. var index = this.getScene()._proceduralTextures.indexOf(this);
  17287. if (index >= 0) {
  17288. this.getScene()._proceduralTextures.splice(index, 1);
  17289. }
  17290. _super.prototype.dispose.call(this);
  17291. };
  17292. return ProceduralTexture;
  17293. })(BABYLON.Texture);
  17294. BABYLON.ProceduralTexture = ProceduralTexture;
  17295. })(BABYLON || (BABYLON = {}));
  17296. var BABYLON;
  17297. (function (BABYLON) {
  17298. var MirrorTexture = (function (_super) {
  17299. __extends(MirrorTexture, _super);
  17300. function MirrorTexture(name, size, scene, generateMipMaps) {
  17301. var _this = this;
  17302. _super.call(this, name, size, scene, generateMipMaps, true);
  17303. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17304. this._transformMatrix = BABYLON.Matrix.Zero();
  17305. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17306. this.onBeforeRender = function () {
  17307. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17308. _this._savedViewMatrix = scene.getViewMatrix();
  17309. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17310. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17311. scene.clipPlane = _this.mirrorPlane;
  17312. scene.getEngine().cullBackFaces = false;
  17313. };
  17314. this.onAfterRender = function () {
  17315. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17316. scene.getEngine().cullBackFaces = true;
  17317. delete scene.clipPlane;
  17318. };
  17319. }
  17320. MirrorTexture.prototype.clone = function () {
  17321. var textureSize = this.getSize();
  17322. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17323. // Base texture
  17324. newTexture.hasAlpha = this.hasAlpha;
  17325. newTexture.level = this.level;
  17326. // Mirror Texture
  17327. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17328. newTexture.renderList = this.renderList.slice(0);
  17329. return newTexture;
  17330. };
  17331. return MirrorTexture;
  17332. })(BABYLON.RenderTargetTexture);
  17333. BABYLON.MirrorTexture = MirrorTexture;
  17334. })(BABYLON || (BABYLON = {}));
  17335. var BABYLON;
  17336. (function (BABYLON) {
  17337. var DynamicTexture = (function (_super) {
  17338. __extends(DynamicTexture, _super);
  17339. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17340. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17341. _super.call(this, null, scene, !generateMipMaps);
  17342. this.name = name;
  17343. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17344. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17345. this._generateMipMaps = generateMipMaps;
  17346. if (options.getContext) {
  17347. this._canvas = options;
  17348. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17349. }
  17350. else {
  17351. this._canvas = document.createElement("canvas");
  17352. if (options.width) {
  17353. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17354. }
  17355. else {
  17356. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17357. }
  17358. }
  17359. var textureSize = this.getSize();
  17360. this._canvas.width = textureSize.width;
  17361. this._canvas.height = textureSize.height;
  17362. this._context = this._canvas.getContext("2d");
  17363. }
  17364. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17365. get: function () {
  17366. return true;
  17367. },
  17368. enumerable: true,
  17369. configurable: true
  17370. });
  17371. DynamicTexture.prototype.scale = function (ratio) {
  17372. var textureSize = this.getSize();
  17373. textureSize.width *= ratio;
  17374. textureSize.height *= ratio;
  17375. this._canvas.width = textureSize.width;
  17376. this._canvas.height = textureSize.height;
  17377. this.releaseInternalTexture();
  17378. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17379. };
  17380. DynamicTexture.prototype.getContext = function () {
  17381. return this._context;
  17382. };
  17383. DynamicTexture.prototype.clear = function () {
  17384. var size = this.getSize();
  17385. this._context.fillRect(0, 0, size.width, size.height);
  17386. };
  17387. DynamicTexture.prototype.update = function (invertY) {
  17388. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17389. };
  17390. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17391. if (update === void 0) { update = true; }
  17392. var size = this.getSize();
  17393. if (clearColor) {
  17394. this._context.fillStyle = clearColor;
  17395. this._context.fillRect(0, 0, size.width, size.height);
  17396. }
  17397. this._context.font = font;
  17398. if (x === null) {
  17399. var textSize = this._context.measureText(text);
  17400. x = (size.width - textSize.width) / 2;
  17401. }
  17402. this._context.fillStyle = color;
  17403. this._context.fillText(text, x, y);
  17404. if (update) {
  17405. this.update(invertY);
  17406. }
  17407. };
  17408. DynamicTexture.prototype.clone = function () {
  17409. var textureSize = this.getSize();
  17410. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17411. // Base texture
  17412. newTexture.hasAlpha = this.hasAlpha;
  17413. newTexture.level = this.level;
  17414. // Dynamic Texture
  17415. newTexture.wrapU = this.wrapU;
  17416. newTexture.wrapV = this.wrapV;
  17417. return newTexture;
  17418. };
  17419. return DynamicTexture;
  17420. })(BABYLON.Texture);
  17421. BABYLON.DynamicTexture = DynamicTexture;
  17422. })(BABYLON || (BABYLON = {}));
  17423. var BABYLON;
  17424. (function (BABYLON) {
  17425. var VideoTexture = (function (_super) {
  17426. __extends(VideoTexture, _super);
  17427. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17428. var _this = this;
  17429. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17430. if (invertY === void 0) { invertY = false; }
  17431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17432. _super.call(this, null, scene, !generateMipMaps, invertY);
  17433. this._autoLaunch = true;
  17434. this.name = name;
  17435. this.video = document.createElement("video");
  17436. this.video.autoplay = false;
  17437. this.video.loop = true;
  17438. this.video.addEventListener("canplaythrough", function () {
  17439. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17440. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17441. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17442. }
  17443. else {
  17444. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17445. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17446. generateMipMaps = false;
  17447. }
  17448. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17449. _this._texture.isReady = true;
  17450. });
  17451. urls.forEach(function (url) {
  17452. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17453. var source = document.createElement("source");
  17454. source.src = url;
  17455. _this.video.appendChild(source);
  17456. });
  17457. this._lastUpdate = BABYLON.Tools.Now;
  17458. }
  17459. VideoTexture.prototype.update = function () {
  17460. if (this._autoLaunch) {
  17461. this._autoLaunch = false;
  17462. this.video.play();
  17463. }
  17464. var now = BABYLON.Tools.Now;
  17465. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17466. return false;
  17467. }
  17468. this._lastUpdate = now;
  17469. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17470. return true;
  17471. };
  17472. return VideoTexture;
  17473. })(BABYLON.Texture);
  17474. BABYLON.VideoTexture = VideoTexture;
  17475. })(BABYLON || (BABYLON = {}));
  17476. var BABYLON;
  17477. (function (BABYLON) {
  17478. var CustomProceduralTexture = (function (_super) {
  17479. __extends(CustomProceduralTexture, _super);
  17480. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17481. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17482. this._animate = true;
  17483. this._time = 0;
  17484. this._texturePath = texturePath;
  17485. //Try to load json
  17486. this.loadJson(texturePath);
  17487. this.refreshRate = 1;
  17488. }
  17489. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17490. var _this = this;
  17491. var that = this;
  17492. function noConfigFile() {
  17493. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17494. try {
  17495. that.setFragment(that._texturePath);
  17496. }
  17497. catch (ex) {
  17498. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17499. }
  17500. }
  17501. var configFileUrl = jsonUrl + "/config.json";
  17502. var xhr = new XMLHttpRequest();
  17503. xhr.open("GET", configFileUrl, true);
  17504. xhr.addEventListener("load", function () {
  17505. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17506. try {
  17507. _this._config = JSON.parse(xhr.response);
  17508. _this.updateShaderUniforms();
  17509. _this.updateTextures();
  17510. _this.setFragment(_this._texturePath + "/custom");
  17511. _this._animate = _this._config.animate;
  17512. _this.refreshRate = _this._config.refreshrate;
  17513. }
  17514. catch (ex) {
  17515. noConfigFile();
  17516. }
  17517. }
  17518. else {
  17519. noConfigFile();
  17520. }
  17521. }, false);
  17522. xhr.addEventListener("error", function () {
  17523. noConfigFile();
  17524. }, false);
  17525. try {
  17526. xhr.send();
  17527. }
  17528. catch (ex) {
  17529. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17530. }
  17531. };
  17532. CustomProceduralTexture.prototype.isReady = function () {
  17533. if (!_super.prototype.isReady.call(this)) {
  17534. return false;
  17535. }
  17536. for (var name in this._textures) {
  17537. var texture = this._textures[name];
  17538. if (!texture.isReady()) {
  17539. return false;
  17540. }
  17541. }
  17542. return true;
  17543. };
  17544. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17545. if (this._animate) {
  17546. this._time += this.getScene().getAnimationRatio() * 0.03;
  17547. this.updateShaderUniforms();
  17548. }
  17549. _super.prototype.render.call(this, useCameraPostProcess);
  17550. };
  17551. CustomProceduralTexture.prototype.updateTextures = function () {
  17552. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17553. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17554. }
  17555. };
  17556. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17557. if (this._config) {
  17558. for (var j = 0; j < this._config.uniforms.length; j++) {
  17559. var uniform = this._config.uniforms[j];
  17560. switch (uniform.type) {
  17561. case "float":
  17562. this.setFloat(uniform.name, uniform.value);
  17563. break;
  17564. case "color3":
  17565. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17566. break;
  17567. case "color4":
  17568. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17569. break;
  17570. case "vector2":
  17571. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17572. break;
  17573. case "vector3":
  17574. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17575. break;
  17576. }
  17577. }
  17578. }
  17579. this.setFloat("time", this._time);
  17580. };
  17581. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17582. get: function () {
  17583. return this._animate;
  17584. },
  17585. set: function (value) {
  17586. this._animate = value;
  17587. },
  17588. enumerable: true,
  17589. configurable: true
  17590. });
  17591. return CustomProceduralTexture;
  17592. })(BABYLON.ProceduralTexture);
  17593. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17594. })(BABYLON || (BABYLON = {}));
  17595. var BABYLON;
  17596. (function (BABYLON) {
  17597. var WoodProceduralTexture = (function (_super) {
  17598. __extends(WoodProceduralTexture, _super);
  17599. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17600. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17601. this._ampScale = 100.0;
  17602. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17603. this.updateShaderUniforms();
  17604. this.refreshRate = 0;
  17605. }
  17606. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17607. this.setFloat("ampScale", this._ampScale);
  17608. this.setColor3("woodColor", this._woodColor);
  17609. };
  17610. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17611. get: function () {
  17612. return this._ampScale;
  17613. },
  17614. set: function (value) {
  17615. this._ampScale = value;
  17616. this.updateShaderUniforms();
  17617. },
  17618. enumerable: true,
  17619. configurable: true
  17620. });
  17621. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17622. get: function () {
  17623. return this._woodColor;
  17624. },
  17625. set: function (value) {
  17626. this._woodColor = value;
  17627. this.updateShaderUniforms();
  17628. },
  17629. enumerable: true,
  17630. configurable: true
  17631. });
  17632. return WoodProceduralTexture;
  17633. })(BABYLON.ProceduralTexture);
  17634. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17635. var FireProceduralTexture = (function (_super) {
  17636. __extends(FireProceduralTexture, _super);
  17637. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17638. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17639. this._time = 0.0;
  17640. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17641. this._autoGenerateTime = true;
  17642. this._alphaThreshold = 0.5;
  17643. this._fireColors = FireProceduralTexture.RedFireColors;
  17644. this.updateShaderUniforms();
  17645. this.refreshRate = 1;
  17646. }
  17647. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17648. this.setFloat("time", this._time);
  17649. this.setVector2("speed", this._speed);
  17650. this.setColor3("c1", this._fireColors[0]);
  17651. this.setColor3("c2", this._fireColors[1]);
  17652. this.setColor3("c3", this._fireColors[2]);
  17653. this.setColor3("c4", this._fireColors[3]);
  17654. this.setColor3("c5", this._fireColors[4]);
  17655. this.setColor3("c6", this._fireColors[5]);
  17656. this.setFloat("alphaThreshold", this._alphaThreshold);
  17657. };
  17658. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17659. if (this._autoGenerateTime) {
  17660. this._time += this.getScene().getAnimationRatio() * 0.03;
  17661. this.updateShaderUniforms();
  17662. }
  17663. _super.prototype.render.call(this, useCameraPostProcess);
  17664. };
  17665. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17666. get: function () {
  17667. return [
  17668. new BABYLON.Color3(0.5, 0.0, 1.0),
  17669. new BABYLON.Color3(0.9, 0.0, 1.0),
  17670. new BABYLON.Color3(0.2, 0.0, 1.0),
  17671. new BABYLON.Color3(1.0, 0.9, 1.0),
  17672. new BABYLON.Color3(0.1, 0.1, 1.0),
  17673. new BABYLON.Color3(0.9, 0.9, 1.0)
  17674. ];
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17680. get: function () {
  17681. return [
  17682. new BABYLON.Color3(0.5, 1.0, 0.0),
  17683. new BABYLON.Color3(0.5, 1.0, 0.0),
  17684. new BABYLON.Color3(0.3, 0.4, 0.0),
  17685. new BABYLON.Color3(0.5, 1.0, 0.0),
  17686. new BABYLON.Color3(0.2, 0.0, 0.0),
  17687. new BABYLON.Color3(0.5, 1.0, 0.0)
  17688. ];
  17689. },
  17690. enumerable: true,
  17691. configurable: true
  17692. });
  17693. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17694. get: function () {
  17695. return [
  17696. new BABYLON.Color3(0.5, 0.0, 0.1),
  17697. new BABYLON.Color3(0.9, 0.0, 0.0),
  17698. new BABYLON.Color3(0.2, 0.0, 0.0),
  17699. new BABYLON.Color3(1.0, 0.9, 0.0),
  17700. new BABYLON.Color3(0.1, 0.1, 0.1),
  17701. new BABYLON.Color3(0.9, 0.9, 0.9)
  17702. ];
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17708. get: function () {
  17709. return [
  17710. new BABYLON.Color3(0.1, 0.0, 0.5),
  17711. new BABYLON.Color3(0.0, 0.0, 0.5),
  17712. new BABYLON.Color3(0.1, 0.0, 0.2),
  17713. new BABYLON.Color3(0.0, 0.0, 1.0),
  17714. new BABYLON.Color3(0.1, 0.2, 0.3),
  17715. new BABYLON.Color3(0.0, 0.2, 0.9)
  17716. ];
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17722. get: function () {
  17723. return this._fireColors;
  17724. },
  17725. set: function (value) {
  17726. this._fireColors = value;
  17727. this.updateShaderUniforms();
  17728. },
  17729. enumerable: true,
  17730. configurable: true
  17731. });
  17732. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17733. get: function () {
  17734. return this._time;
  17735. },
  17736. set: function (value) {
  17737. this._time = value;
  17738. this.updateShaderUniforms();
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17744. get: function () {
  17745. return this._speed;
  17746. },
  17747. set: function (value) {
  17748. this._speed = value;
  17749. this.updateShaderUniforms();
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17755. get: function () {
  17756. return this._alphaThreshold;
  17757. },
  17758. set: function (value) {
  17759. this._alphaThreshold = value;
  17760. this.updateShaderUniforms();
  17761. },
  17762. enumerable: true,
  17763. configurable: true
  17764. });
  17765. return FireProceduralTexture;
  17766. })(BABYLON.ProceduralTexture);
  17767. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17768. var CloudProceduralTexture = (function (_super) {
  17769. __extends(CloudProceduralTexture, _super);
  17770. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17771. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17772. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17773. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17774. this.updateShaderUniforms();
  17775. this.refreshRate = 0;
  17776. }
  17777. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17778. this.setColor4("skyColor", this._skyColor);
  17779. this.setColor4("cloudColor", this._cloudColor);
  17780. };
  17781. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17782. get: function () {
  17783. return this._skyColor;
  17784. },
  17785. set: function (value) {
  17786. this._skyColor = value;
  17787. this.updateShaderUniforms();
  17788. },
  17789. enumerable: true,
  17790. configurable: true
  17791. });
  17792. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17793. get: function () {
  17794. return this._cloudColor;
  17795. },
  17796. set: function (value) {
  17797. this._cloudColor = value;
  17798. this.updateShaderUniforms();
  17799. },
  17800. enumerable: true,
  17801. configurable: true
  17802. });
  17803. return CloudProceduralTexture;
  17804. })(BABYLON.ProceduralTexture);
  17805. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17806. var GrassProceduralTexture = (function (_super) {
  17807. __extends(GrassProceduralTexture, _super);
  17808. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17809. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17810. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17811. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17812. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17813. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17814. this._grassColors = [
  17815. new BABYLON.Color3(0.29, 0.38, 0.02),
  17816. new BABYLON.Color3(0.36, 0.49, 0.09),
  17817. new BABYLON.Color3(0.51, 0.6, 0.28)
  17818. ];
  17819. this.updateShaderUniforms();
  17820. this.refreshRate = 0;
  17821. }
  17822. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17823. this.setColor3("herb1Color", this._grassColors[0]);
  17824. this.setColor3("herb2Color", this._grassColors[1]);
  17825. this.setColor3("herb3Color", this._grassColors[2]);
  17826. this.setColor3("groundColor", this._groundColor);
  17827. };
  17828. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17829. get: function () {
  17830. return this._grassColors;
  17831. },
  17832. set: function (value) {
  17833. this._grassColors = value;
  17834. this.updateShaderUniforms();
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17840. get: function () {
  17841. return this._groundColor;
  17842. },
  17843. set: function (value) {
  17844. this.groundColor = value;
  17845. this.updateShaderUniforms();
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. return GrassProceduralTexture;
  17851. })(BABYLON.ProceduralTexture);
  17852. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17853. var RoadProceduralTexture = (function (_super) {
  17854. __extends(RoadProceduralTexture, _super);
  17855. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17856. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17857. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17858. this.updateShaderUniforms();
  17859. this.refreshRate = 0;
  17860. }
  17861. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17862. this.setColor3("roadColor", this._roadColor);
  17863. };
  17864. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17865. get: function () {
  17866. return this._roadColor;
  17867. },
  17868. set: function (value) {
  17869. this._roadColor = value;
  17870. this.updateShaderUniforms();
  17871. },
  17872. enumerable: true,
  17873. configurable: true
  17874. });
  17875. return RoadProceduralTexture;
  17876. })(BABYLON.ProceduralTexture);
  17877. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17878. var BrickProceduralTexture = (function (_super) {
  17879. __extends(BrickProceduralTexture, _super);
  17880. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17881. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17882. this._numberOfBricksHeight = 15;
  17883. this._numberOfBricksWidth = 5;
  17884. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17885. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17886. this.updateShaderUniforms();
  17887. this.refreshRate = 0;
  17888. }
  17889. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17890. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17891. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17892. this.setColor3("brickColor", this._brickColor);
  17893. this.setColor3("jointColor", this._jointColor);
  17894. };
  17895. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17896. get: function () {
  17897. return this._numberOfBricksHeight;
  17898. },
  17899. set: function (value) {
  17900. this._numberOfBricksHeight = value;
  17901. this.updateShaderUniforms();
  17902. },
  17903. enumerable: true,
  17904. configurable: true
  17905. });
  17906. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17907. get: function () {
  17908. return this._numberOfBricksWidth;
  17909. },
  17910. set: function (value) {
  17911. this._numberOfBricksWidth = value;
  17912. this.updateShaderUniforms();
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17918. get: function () {
  17919. return this._jointColor;
  17920. },
  17921. set: function (value) {
  17922. this._jointColor = value;
  17923. this.updateShaderUniforms();
  17924. },
  17925. enumerable: true,
  17926. configurable: true
  17927. });
  17928. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17929. get: function () {
  17930. return this._brickColor;
  17931. },
  17932. set: function (value) {
  17933. this._brickColor = value;
  17934. this.updateShaderUniforms();
  17935. },
  17936. enumerable: true,
  17937. configurable: true
  17938. });
  17939. return BrickProceduralTexture;
  17940. })(BABYLON.ProceduralTexture);
  17941. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17942. var MarbleProceduralTexture = (function (_super) {
  17943. __extends(MarbleProceduralTexture, _super);
  17944. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17945. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17946. this._numberOfTilesHeight = 3;
  17947. this._numberOfTilesWidth = 3;
  17948. this._amplitude = 9.0;
  17949. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17950. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17951. this.updateShaderUniforms();
  17952. this.refreshRate = 0;
  17953. }
  17954. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17955. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17956. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17957. this.setFloat("amplitude", this._amplitude);
  17958. this.setColor3("marbleColor", this._marbleColor);
  17959. this.setColor3("jointColor", this._jointColor);
  17960. };
  17961. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17962. get: function () {
  17963. return this._numberOfTilesHeight;
  17964. },
  17965. set: function (value) {
  17966. this._numberOfTilesHeight = value;
  17967. this.updateShaderUniforms();
  17968. },
  17969. enumerable: true,
  17970. configurable: true
  17971. });
  17972. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17973. get: function () {
  17974. return this._numberOfTilesWidth;
  17975. },
  17976. set: function (value) {
  17977. this._numberOfTilesWidth = value;
  17978. this.updateShaderUniforms();
  17979. },
  17980. enumerable: true,
  17981. configurable: true
  17982. });
  17983. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17984. get: function () {
  17985. return this._jointColor;
  17986. },
  17987. set: function (value) {
  17988. this._jointColor = value;
  17989. this.updateShaderUniforms();
  17990. },
  17991. enumerable: true,
  17992. configurable: true
  17993. });
  17994. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17995. get: function () {
  17996. return this._marbleColor;
  17997. },
  17998. set: function (value) {
  17999. this._marbleColor = value;
  18000. this.updateShaderUniforms();
  18001. },
  18002. enumerable: true,
  18003. configurable: true
  18004. });
  18005. return MarbleProceduralTexture;
  18006. })(BABYLON.ProceduralTexture);
  18007. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18008. })(BABYLON || (BABYLON = {}));
  18009. var BABYLON;
  18010. (function (BABYLON) {
  18011. var EffectFallbacks = (function () {
  18012. function EffectFallbacks() {
  18013. this._defines = {};
  18014. this._currentRank = 32;
  18015. this._maxRank = -1;
  18016. }
  18017. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18018. if (!this._defines[rank]) {
  18019. if (rank < this._currentRank) {
  18020. this._currentRank = rank;
  18021. }
  18022. if (rank > this._maxRank) {
  18023. this._maxRank = rank;
  18024. }
  18025. this._defines[rank] = new Array();
  18026. }
  18027. this._defines[rank].push(define);
  18028. };
  18029. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18030. get: function () {
  18031. return this._currentRank <= this._maxRank;
  18032. },
  18033. enumerable: true,
  18034. configurable: true
  18035. });
  18036. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18037. var currentFallbacks = this._defines[this._currentRank];
  18038. for (var index = 0; index < currentFallbacks.length; index++) {
  18039. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18040. }
  18041. this._currentRank++;
  18042. return currentDefines;
  18043. };
  18044. return EffectFallbacks;
  18045. })();
  18046. BABYLON.EffectFallbacks = EffectFallbacks;
  18047. var Effect = (function () {
  18048. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18049. var _this = this;
  18050. this._isReady = false;
  18051. this._compilationError = "";
  18052. this._valueCache = [];
  18053. this._engine = engine;
  18054. this.name = baseName;
  18055. this.defines = defines;
  18056. this._uniformsNames = uniformsNames.concat(samplers);
  18057. this._samplers = samplers;
  18058. this._attributesNames = attributesNames;
  18059. this.onError = onError;
  18060. this.onCompiled = onCompiled;
  18061. var vertexSource;
  18062. var fragmentSource;
  18063. if (baseName.vertexElement) {
  18064. vertexSource = document.getElementById(baseName.vertexElement);
  18065. if (!vertexSource) {
  18066. vertexSource = baseName.vertexElement;
  18067. }
  18068. }
  18069. else {
  18070. vertexSource = baseName.vertex || baseName;
  18071. }
  18072. if (baseName.fragmentElement) {
  18073. fragmentSource = document.getElementById(baseName.fragmentElement);
  18074. if (!fragmentSource) {
  18075. fragmentSource = baseName.fragmentElement;
  18076. }
  18077. }
  18078. else {
  18079. fragmentSource = baseName.fragment || baseName;
  18080. }
  18081. this._loadVertexShader(vertexSource, function (vertexCode) {
  18082. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18083. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18084. });
  18085. });
  18086. }
  18087. // Properties
  18088. Effect.prototype.isReady = function () {
  18089. return this._isReady;
  18090. };
  18091. Effect.prototype.getProgram = function () {
  18092. return this._program;
  18093. };
  18094. Effect.prototype.getAttributesNames = function () {
  18095. return this._attributesNames;
  18096. };
  18097. Effect.prototype.getAttributeLocation = function (index) {
  18098. return this._attributes[index];
  18099. };
  18100. Effect.prototype.getAttributeLocationByName = function (name) {
  18101. var index = this._attributesNames.indexOf(name);
  18102. return this._attributes[index];
  18103. };
  18104. Effect.prototype.getAttributesCount = function () {
  18105. return this._attributes.length;
  18106. };
  18107. Effect.prototype.getUniformIndex = function (uniformName) {
  18108. return this._uniformsNames.indexOf(uniformName);
  18109. };
  18110. Effect.prototype.getUniform = function (uniformName) {
  18111. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18112. };
  18113. Effect.prototype.getSamplers = function () {
  18114. return this._samplers;
  18115. };
  18116. Effect.prototype.getCompilationError = function () {
  18117. return this._compilationError;
  18118. };
  18119. // Methods
  18120. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18121. // DOM element ?
  18122. if (vertex instanceof HTMLElement) {
  18123. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18124. callback(vertexCode);
  18125. return;
  18126. }
  18127. // Is in local store ?
  18128. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18129. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18130. return;
  18131. }
  18132. var vertexShaderUrl;
  18133. if (vertex[0] === "." || vertex[0] === "/") {
  18134. vertexShaderUrl = vertex;
  18135. }
  18136. else {
  18137. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18138. }
  18139. // Vertex shader
  18140. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18141. };
  18142. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18143. // DOM element ?
  18144. if (fragment instanceof HTMLElement) {
  18145. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18146. callback(fragmentCode);
  18147. return;
  18148. }
  18149. // Is in local store ?
  18150. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18151. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18152. return;
  18153. }
  18154. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18155. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18156. return;
  18157. }
  18158. var fragmentShaderUrl;
  18159. if (fragment[0] === "." || fragment[0] === "/") {
  18160. fragmentShaderUrl = fragment;
  18161. }
  18162. else {
  18163. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18164. }
  18165. // Fragment shader
  18166. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18167. };
  18168. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18169. try {
  18170. var engine = this._engine;
  18171. if (!engine.getCaps().highPrecisionShaderSupported) {
  18172. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18173. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18174. }
  18175. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18176. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18177. this._attributes = engine.getAttributes(this._program, attributesNames);
  18178. for (var index = 0; index < this._samplers.length; index++) {
  18179. var sampler = this.getUniform(this._samplers[index]);
  18180. if (sampler == null) {
  18181. this._samplers.splice(index, 1);
  18182. index--;
  18183. }
  18184. }
  18185. engine.bindSamplers(this);
  18186. this._isReady = true;
  18187. if (this.onCompiled) {
  18188. this.onCompiled(this);
  18189. }
  18190. }
  18191. catch (e) {
  18192. // Is it a problem with precision?
  18193. if (e.message.indexOf("highp") !== -1) {
  18194. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18195. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18196. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18197. return;
  18198. }
  18199. // Let's go through fallbacks then
  18200. if (fallbacks && fallbacks.isMoreFallbacks) {
  18201. defines = fallbacks.reduce(defines);
  18202. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18203. }
  18204. else {
  18205. BABYLON.Tools.Error("Unable to compile effect: ");
  18206. if (this.name.vertexElement) {
  18207. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18208. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18209. }
  18210. else if (this.name.vertex) {
  18211. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18212. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18213. }
  18214. else {
  18215. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18216. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18217. }
  18218. BABYLON.Tools.Error("Defines: " + defines);
  18219. BABYLON.Tools.Error("Error: " + e.message);
  18220. this._compilationError = e.message;
  18221. if (this.onError) {
  18222. this.onError(this, this._compilationError);
  18223. }
  18224. }
  18225. }
  18226. };
  18227. Effect.prototype._bindTexture = function (channel, texture) {
  18228. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18229. };
  18230. Effect.prototype.setTexture = function (channel, texture) {
  18231. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18232. };
  18233. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18234. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18235. };
  18236. //public _cacheMatrix(uniformName, matrix) {
  18237. // if (!this._valueCache[uniformName]) {
  18238. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18239. // }
  18240. // for (var index = 0; index < 16; index++) {
  18241. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18242. // }
  18243. //};
  18244. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18245. if (!this._valueCache[uniformName]) {
  18246. this._valueCache[uniformName] = [x, y];
  18247. return;
  18248. }
  18249. this._valueCache[uniformName][0] = x;
  18250. this._valueCache[uniformName][1] = y;
  18251. };
  18252. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18253. if (!this._valueCache[uniformName]) {
  18254. this._valueCache[uniformName] = [x, y, z];
  18255. return;
  18256. }
  18257. this._valueCache[uniformName][0] = x;
  18258. this._valueCache[uniformName][1] = y;
  18259. this._valueCache[uniformName][2] = z;
  18260. };
  18261. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18262. if (!this._valueCache[uniformName]) {
  18263. this._valueCache[uniformName] = [x, y, z, w];
  18264. return;
  18265. }
  18266. this._valueCache[uniformName][0] = x;
  18267. this._valueCache[uniformName][1] = y;
  18268. this._valueCache[uniformName][2] = z;
  18269. this._valueCache[uniformName][3] = w;
  18270. };
  18271. Effect.prototype.setArray = function (uniformName, array) {
  18272. this._engine.setArray(this.getUniform(uniformName), array);
  18273. return this;
  18274. };
  18275. Effect.prototype.setArray2 = function (uniformName, array) {
  18276. this._engine.setArray2(this.getUniform(uniformName), array);
  18277. return this;
  18278. };
  18279. Effect.prototype.setArray3 = function (uniformName, array) {
  18280. this._engine.setArray3(this.getUniform(uniformName), array);
  18281. return this;
  18282. };
  18283. Effect.prototype.setArray4 = function (uniformName, array) {
  18284. this._engine.setArray4(this.getUniform(uniformName), array);
  18285. return this;
  18286. };
  18287. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18288. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18289. return this;
  18290. };
  18291. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18292. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18293. // return;
  18294. //this._cacheMatrix(uniformName, matrix);
  18295. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18296. return this;
  18297. };
  18298. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18299. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18300. return this;
  18301. };
  18302. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18303. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18304. return this;
  18305. };
  18306. Effect.prototype.setFloat = function (uniformName, value) {
  18307. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18308. return this;
  18309. this._valueCache[uniformName] = value;
  18310. this._engine.setFloat(this.getUniform(uniformName), value);
  18311. return this;
  18312. };
  18313. Effect.prototype.setBool = function (uniformName, bool) {
  18314. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18315. return this;
  18316. this._valueCache[uniformName] = bool;
  18317. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18318. return this;
  18319. };
  18320. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18321. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18322. return this;
  18323. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18324. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18325. return this;
  18326. };
  18327. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18328. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18329. return this;
  18330. this._cacheFloat2(uniformName, x, y);
  18331. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18332. return this;
  18333. };
  18334. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18335. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18336. return this;
  18337. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18338. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18339. return this;
  18340. };
  18341. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18342. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18343. return this;
  18344. this._cacheFloat3(uniformName, x, y, z);
  18345. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18346. return this;
  18347. };
  18348. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18349. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  18350. return this;
  18351. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18352. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18353. return this;
  18354. };
  18355. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18356. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18357. return this;
  18358. this._cacheFloat4(uniformName, x, y, z, w);
  18359. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18360. return this;
  18361. };
  18362. Effect.prototype.setColor3 = function (uniformName, color3) {
  18363. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18364. return this;
  18365. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18366. this._engine.setColor3(this.getUniform(uniformName), color3);
  18367. return this;
  18368. };
  18369. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18370. 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)
  18371. return this;
  18372. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18373. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18374. return this;
  18375. };
  18376. // Statics
  18377. Effect.ShadersStore = {};
  18378. return Effect;
  18379. })();
  18380. BABYLON.Effect = Effect;
  18381. })(BABYLON || (BABYLON = {}));
  18382. var BABYLON;
  18383. (function (BABYLON) {
  18384. var Material = (function () {
  18385. function Material(name, scene, doNotAdd) {
  18386. this.name = name;
  18387. this.checkReadyOnEveryCall = true;
  18388. this.checkReadyOnlyOnce = false;
  18389. this.state = "";
  18390. this.alpha = 1.0;
  18391. this.backFaceCulling = true;
  18392. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18393. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18394. this.disableDepthWrite = false;
  18395. this._wasPreviouslyReady = false;
  18396. this._fillMode = Material.TriangleFillMode;
  18397. this.pointSize = 1.0;
  18398. this.zOffset = 0;
  18399. this.id = name;
  18400. this._scene = scene;
  18401. if (!doNotAdd) {
  18402. scene.materials.push(this);
  18403. }
  18404. }
  18405. Object.defineProperty(Material, "TriangleFillMode", {
  18406. get: function () {
  18407. return Material._TriangleFillMode;
  18408. },
  18409. enumerable: true,
  18410. configurable: true
  18411. });
  18412. Object.defineProperty(Material, "WireFrameFillMode", {
  18413. get: function () {
  18414. return Material._WireFrameFillMode;
  18415. },
  18416. enumerable: true,
  18417. configurable: true
  18418. });
  18419. Object.defineProperty(Material, "PointFillMode", {
  18420. get: function () {
  18421. return Material._PointFillMode;
  18422. },
  18423. enumerable: true,
  18424. configurable: true
  18425. });
  18426. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18427. get: function () {
  18428. return Material._ClockWiseSideOrientation;
  18429. },
  18430. enumerable: true,
  18431. configurable: true
  18432. });
  18433. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18434. get: function () {
  18435. return Material._CounterClockWiseSideOrientation;
  18436. },
  18437. enumerable: true,
  18438. configurable: true
  18439. });
  18440. Object.defineProperty(Material.prototype, "wireframe", {
  18441. get: function () {
  18442. return this._fillMode === Material.WireFrameFillMode;
  18443. },
  18444. set: function (value) {
  18445. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18446. },
  18447. enumerable: true,
  18448. configurable: true
  18449. });
  18450. Object.defineProperty(Material.prototype, "pointsCloud", {
  18451. get: function () {
  18452. return this._fillMode === Material.PointFillMode;
  18453. },
  18454. set: function (value) {
  18455. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18456. },
  18457. enumerable: true,
  18458. configurable: true
  18459. });
  18460. Object.defineProperty(Material.prototype, "fillMode", {
  18461. get: function () {
  18462. return this._fillMode;
  18463. },
  18464. set: function (value) {
  18465. this._fillMode = value;
  18466. },
  18467. enumerable: true,
  18468. configurable: true
  18469. });
  18470. Material.prototype.isReady = function (mesh, useInstances) {
  18471. return true;
  18472. };
  18473. Material.prototype.getEffect = function () {
  18474. return this._effect;
  18475. };
  18476. Material.prototype.getScene = function () {
  18477. return this._scene;
  18478. };
  18479. Material.prototype.needAlphaBlending = function () {
  18480. return (this.alpha < 1.0);
  18481. };
  18482. Material.prototype.needAlphaTesting = function () {
  18483. return false;
  18484. };
  18485. Material.prototype.getAlphaTestTexture = function () {
  18486. return null;
  18487. };
  18488. Material.prototype.trackCreation = function (onCompiled, onError) {
  18489. };
  18490. Material.prototype._preBind = function () {
  18491. var engine = this._scene.getEngine();
  18492. engine.enableEffect(this._effect);
  18493. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18494. };
  18495. Material.prototype.bind = function (world, mesh) {
  18496. this._scene._cachedMaterial = this;
  18497. if (this.onBind) {
  18498. this.onBind(this, mesh);
  18499. }
  18500. if (this.disableDepthWrite) {
  18501. var engine = this._scene.getEngine();
  18502. this._cachedDepthWriteState = engine.getDepthWrite();
  18503. engine.setDepthWrite(false);
  18504. }
  18505. };
  18506. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18507. };
  18508. Material.prototype.unbind = function () {
  18509. if (this.disableDepthWrite) {
  18510. var engine = this._scene.getEngine();
  18511. engine.setDepthWrite(this._cachedDepthWriteState);
  18512. }
  18513. };
  18514. Material.prototype.clone = function (name) {
  18515. return null;
  18516. };
  18517. Material.prototype.dispose = function (forceDisposeEffect) {
  18518. // Remove from scene
  18519. var index = this._scene.materials.indexOf(this);
  18520. this._scene.materials.splice(index, 1);
  18521. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18522. if (forceDisposeEffect && this._effect) {
  18523. this._scene.getEngine()._releaseEffect(this._effect);
  18524. this._effect = null;
  18525. }
  18526. // Callback
  18527. if (this.onDispose) {
  18528. this.onDispose();
  18529. }
  18530. };
  18531. Material._TriangleFillMode = 0;
  18532. Material._WireFrameFillMode = 1;
  18533. Material._PointFillMode = 2;
  18534. Material._ClockWiseSideOrientation = 0;
  18535. Material._CounterClockWiseSideOrientation = 1;
  18536. return Material;
  18537. })();
  18538. BABYLON.Material = Material;
  18539. })(BABYLON || (BABYLON = {}));
  18540. var BABYLON;
  18541. (function (BABYLON) {
  18542. var maxSimultaneousLights = 4;
  18543. var FresnelParameters = (function () {
  18544. function FresnelParameters() {
  18545. this.isEnabled = true;
  18546. this.leftColor = BABYLON.Color3.White();
  18547. this.rightColor = BABYLON.Color3.Black();
  18548. this.bias = 0;
  18549. this.power = 1;
  18550. }
  18551. return FresnelParameters;
  18552. })();
  18553. BABYLON.FresnelParameters = FresnelParameters;
  18554. var StandardMaterialDefines = (function () {
  18555. function StandardMaterialDefines() {
  18556. this.DIFFUSE = false;
  18557. this.AMBIENT = false;
  18558. this.OPACITY = false;
  18559. this.OPACITYRGB = false;
  18560. this.REFLECTION = false;
  18561. this.EMISSIVE = false;
  18562. this.SPECULAR = false;
  18563. this.BUMP = false;
  18564. this.SPECULAROVERALPHA = false;
  18565. this.CLIPPLANE = false;
  18566. this.ALPHATEST = false;
  18567. this.ALPHAFROMDIFFUSE = false;
  18568. this.POINTSIZE = false;
  18569. this.FOG = false;
  18570. this.LIGHT0 = false;
  18571. this.LIGHT1 = false;
  18572. this.LIGHT2 = false;
  18573. this.LIGHT3 = false;
  18574. this.SPOTLIGHT0 = false;
  18575. this.SPOTLIGHT1 = false;
  18576. this.SPOTLIGHT2 = false;
  18577. this.SPOTLIGHT3 = false;
  18578. this.HEMILIGHT0 = false;
  18579. this.HEMILIGHT1 = false;
  18580. this.HEMILIGHT2 = false;
  18581. this.HEMILIGHT3 = false;
  18582. this.POINTDIRLIGHT0 = false;
  18583. this.POINTDIRLIGHT1 = false;
  18584. this.POINTDIRLIGHT2 = false;
  18585. this.POINTDIRLIGHT3 = false;
  18586. this.SPECULARTERM = false;
  18587. this.SHADOW0 = false;
  18588. this.SHADOW1 = false;
  18589. this.SHADOW2 = false;
  18590. this.SHADOW3 = false;
  18591. this.SHADOWS = false;
  18592. this.SHADOWVSM0 = false;
  18593. this.SHADOWVSM1 = false;
  18594. this.SHADOWVSM2 = false;
  18595. this.SHADOWVSM3 = false;
  18596. this.SHADOWPCF0 = false;
  18597. this.SHADOWPCF1 = false;
  18598. this.SHADOWPCF2 = false;
  18599. this.SHADOWPCF3 = false;
  18600. this.DIFFUSEFRESNEL = false;
  18601. this.OPACITYFRESNEL = false;
  18602. this.REFLECTIONFRESNEL = false;
  18603. this.EMISSIVEFRESNEL = false;
  18604. this.FRESNEL = false;
  18605. this.NORMAL = false;
  18606. this.UV1 = false;
  18607. this.UV2 = false;
  18608. this.VERTEXCOLOR = false;
  18609. this.VERTEXALPHA = false;
  18610. this.BONES = false;
  18611. this.BONES4 = false;
  18612. this.BonesPerMesh = 0;
  18613. this.INSTANCES = false;
  18614. this.GLOSSINESS = false;
  18615. this.ROUGHNESS = false;
  18616. this.EMISSIVEASILLUMINATION = false;
  18617. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18618. this.LIGHTMAP = false;
  18619. this._keys = Object.keys(this);
  18620. }
  18621. StandardMaterialDefines.prototype.isEqual = function (other) {
  18622. for (var index = 0; index < this._keys.length; index++) {
  18623. var prop = this._keys[index];
  18624. if (this[prop] !== other[prop]) {
  18625. return false;
  18626. }
  18627. }
  18628. return true;
  18629. };
  18630. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18631. for (var index = 0; index < this._keys.length; index++) {
  18632. var prop = this._keys[index];
  18633. other[prop] = this[prop];
  18634. }
  18635. };
  18636. StandardMaterialDefines.prototype.reset = function () {
  18637. for (var index = 0; index < this._keys.length; index++) {
  18638. var prop = this._keys[index];
  18639. if (prop === "BonesPerMesh") {
  18640. this[prop] = 0;
  18641. continue;
  18642. }
  18643. this[prop] = false;
  18644. }
  18645. };
  18646. StandardMaterialDefines.prototype.toString = function () {
  18647. var result = "";
  18648. for (var index = 0; index < this._keys.length; index++) {
  18649. var prop = this._keys[index];
  18650. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18651. result += "#define BonesPerMesh " + this[prop] + "\n";
  18652. continue;
  18653. }
  18654. if (this[prop]) {
  18655. result += "#define " + prop + "\n";
  18656. }
  18657. }
  18658. return result;
  18659. };
  18660. return StandardMaterialDefines;
  18661. })();
  18662. var StandardMaterial = (function (_super) {
  18663. __extends(StandardMaterial, _super);
  18664. function StandardMaterial(name, scene) {
  18665. var _this = this;
  18666. _super.call(this, name, scene);
  18667. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18668. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18669. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18670. this.specularPower = 64;
  18671. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18672. this.useAlphaFromDiffuseTexture = false;
  18673. this.useEmissiveAsIllumination = false;
  18674. this.useReflectionFresnelFromSpecular = false;
  18675. this.useSpecularOverAlpha = true;
  18676. this.fogEnabled = true;
  18677. this.roughness = 0;
  18678. this.lightmapThreshold = 0;
  18679. this.useGlossinessFromSpecularMapAlpha = false;
  18680. this._renderTargets = new BABYLON.SmartArray(16);
  18681. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18682. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18683. this._scaledDiffuse = new BABYLON.Color3();
  18684. this._scaledSpecular = new BABYLON.Color3();
  18685. this._defines = new StandardMaterialDefines();
  18686. this._cachedDefines = new StandardMaterialDefines();
  18687. this._cachedDefines.BonesPerMesh = -1;
  18688. this.getRenderTargetTextures = function () {
  18689. _this._renderTargets.reset();
  18690. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18691. _this._renderTargets.push(_this.reflectionTexture);
  18692. }
  18693. return _this._renderTargets;
  18694. };
  18695. }
  18696. StandardMaterial.prototype.needAlphaBlending = function () {
  18697. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18698. };
  18699. StandardMaterial.prototype.needAlphaTesting = function () {
  18700. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18701. };
  18702. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18703. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18704. };
  18705. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18706. return this.diffuseTexture;
  18707. };
  18708. // Methods
  18709. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18710. if (this.checkReadyOnlyOnce) {
  18711. if (this._wasPreviouslyReady) {
  18712. return true;
  18713. }
  18714. }
  18715. var scene = this.getScene();
  18716. if (!this.checkReadyOnEveryCall) {
  18717. if (this._renderId === scene.getRenderId()) {
  18718. return true;
  18719. }
  18720. }
  18721. var engine = scene.getEngine();
  18722. var needNormals = false;
  18723. var needUVs = false;
  18724. this._defines.reset();
  18725. // Textures
  18726. if (scene.texturesEnabled) {
  18727. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18728. if (!this.diffuseTexture.isReady()) {
  18729. return false;
  18730. }
  18731. else {
  18732. needUVs = true;
  18733. this._defines.DIFFUSE = true;
  18734. }
  18735. }
  18736. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18737. if (!this.ambientTexture.isReady()) {
  18738. return false;
  18739. }
  18740. else {
  18741. needUVs = true;
  18742. this._defines.AMBIENT = true;
  18743. }
  18744. }
  18745. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18746. if (!this.opacityTexture.isReady()) {
  18747. return false;
  18748. }
  18749. else {
  18750. needUVs = true;
  18751. this._defines.OPACITY = true;
  18752. if (this.opacityTexture.getAlphaFromRGB) {
  18753. this._defines.OPACITYRGB = true;
  18754. }
  18755. }
  18756. }
  18757. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18758. if (!this.reflectionTexture.isReady()) {
  18759. return false;
  18760. }
  18761. else {
  18762. needNormals = true;
  18763. needUVs = true;
  18764. this._defines.REFLECTION = true;
  18765. if (this.roughness > 0) {
  18766. this._defines.ROUGHNESS = true;
  18767. }
  18768. }
  18769. }
  18770. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18771. if (!this.emissiveTexture.isReady()) {
  18772. return false;
  18773. }
  18774. else {
  18775. needUVs = true;
  18776. this._defines.EMISSIVE = true;
  18777. }
  18778. }
  18779. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18780. if (!this.lightmapTexture.isReady()) {
  18781. return false;
  18782. }
  18783. else {
  18784. needUVs = true;
  18785. this._defines.LIGHTMAP = true;
  18786. }
  18787. }
  18788. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18789. if (!this.specularTexture.isReady()) {
  18790. return false;
  18791. }
  18792. else {
  18793. needUVs = true;
  18794. this._defines.SPECULAR = true;
  18795. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18796. }
  18797. }
  18798. }
  18799. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18800. if (!this.bumpTexture.isReady()) {
  18801. return false;
  18802. }
  18803. else {
  18804. needUVs = true;
  18805. this._defines.BUMP = true;
  18806. }
  18807. }
  18808. // Effect
  18809. if (scene.clipPlane) {
  18810. this._defines.CLIPPLANE = true;
  18811. }
  18812. if (engine.getAlphaTesting()) {
  18813. this._defines.ALPHATEST = true;
  18814. }
  18815. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18816. this._defines.ALPHAFROMDIFFUSE = true;
  18817. }
  18818. if (this.useEmissiveAsIllumination) {
  18819. this._defines.EMISSIVEASILLUMINATION = true;
  18820. }
  18821. if (this.useReflectionFresnelFromSpecular) {
  18822. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18823. }
  18824. // Point size
  18825. if (this.pointsCloud || scene.forcePointsCloud) {
  18826. this._defines.POINTSIZE = true;
  18827. }
  18828. // Fog
  18829. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18830. this._defines.FOG = true;
  18831. }
  18832. var lightIndex = 0;
  18833. if (scene.lightsEnabled) {
  18834. for (var index = 0; index < scene.lights.length; index++) {
  18835. var light = scene.lights[index];
  18836. if (!light.isEnabled()) {
  18837. continue;
  18838. }
  18839. // Excluded check
  18840. if (light._excludedMeshesIds.length > 0) {
  18841. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18842. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18843. if (excludedMesh) {
  18844. light.excludedMeshes.push(excludedMesh);
  18845. }
  18846. }
  18847. light._excludedMeshesIds = [];
  18848. }
  18849. // Included check
  18850. if (light._includedOnlyMeshesIds.length > 0) {
  18851. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18852. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18853. if (includedOnlyMesh) {
  18854. light.includedOnlyMeshes.push(includedOnlyMesh);
  18855. }
  18856. }
  18857. light._includedOnlyMeshesIds = [];
  18858. }
  18859. if (!light.canAffectMesh(mesh)) {
  18860. continue;
  18861. }
  18862. needNormals = true;
  18863. this._defines["LIGHT" + lightIndex] = true;
  18864. var type;
  18865. if (light instanceof BABYLON.SpotLight) {
  18866. type = "SPOTLIGHT" + lightIndex;
  18867. }
  18868. else if (light instanceof BABYLON.HemisphericLight) {
  18869. type = "HEMILIGHT" + lightIndex;
  18870. }
  18871. else {
  18872. type = "POINTDIRLIGHT" + lightIndex;
  18873. }
  18874. this._defines[type] = true;
  18875. // Specular
  18876. if (!light.specular.equalsFloats(0, 0, 0)) {
  18877. this._defines.SPECULARTERM = true;
  18878. }
  18879. // Shadows
  18880. if (scene.shadowsEnabled) {
  18881. var shadowGenerator = light.getShadowGenerator();
  18882. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18883. this._defines["SHADOW" + lightIndex] = true;
  18884. this._defines.SHADOWS = true;
  18885. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18886. this._defines["SHADOWVSM" + lightIndex] = true;
  18887. }
  18888. if (shadowGenerator.usePoissonSampling) {
  18889. this._defines["SHADOWPCF" + lightIndex] = true;
  18890. }
  18891. }
  18892. }
  18893. lightIndex++;
  18894. if (lightIndex === maxSimultaneousLights)
  18895. break;
  18896. }
  18897. }
  18898. if (StandardMaterial.FresnelEnabled) {
  18899. // Fresnel
  18900. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18901. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18902. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18903. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18904. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18905. this._defines.DIFFUSEFRESNEL = true;
  18906. }
  18907. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18908. this._defines.OPACITYFRESNEL = true;
  18909. }
  18910. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18911. this._defines.REFLECTIONFRESNEL = true;
  18912. }
  18913. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18914. this._defines.EMISSIVEFRESNEL = true;
  18915. }
  18916. needNormals = true;
  18917. this._defines.FRESNEL = true;
  18918. }
  18919. }
  18920. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18921. this._defines.SPECULAROVERALPHA = true;
  18922. }
  18923. // Attribs
  18924. if (mesh) {
  18925. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18926. this._defines.NORMAL = true;
  18927. }
  18928. if (needUVs) {
  18929. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18930. this._defines.UV1 = true;
  18931. }
  18932. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18933. this._defines.UV2 = true;
  18934. }
  18935. }
  18936. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18937. this._defines.VERTEXCOLOR = true;
  18938. if (mesh.hasVertexAlpha) {
  18939. this._defines.VERTEXALPHA = true;
  18940. }
  18941. }
  18942. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18943. this._defines.BONES = true;
  18944. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18945. this._defines.BONES4 = true;
  18946. }
  18947. // Instances
  18948. if (useInstances) {
  18949. this._defines.INSTANCES = true;
  18950. }
  18951. }
  18952. // Get correct effect
  18953. if (!this._defines.isEqual(this._cachedDefines)) {
  18954. this._defines.cloneTo(this._cachedDefines);
  18955. scene.resetCachedMaterial();
  18956. // Fallbacks
  18957. var fallbacks = new BABYLON.EffectFallbacks();
  18958. if (this._defines.REFLECTION) {
  18959. fallbacks.addFallback(0, "REFLECTION");
  18960. }
  18961. if (this._defines.SPECULAR) {
  18962. fallbacks.addFallback(0, "SPECULAR");
  18963. }
  18964. if (this._defines.BUMP) {
  18965. fallbacks.addFallback(0, "BUMP");
  18966. }
  18967. if (this._defines.SPECULAROVERALPHA) {
  18968. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18969. }
  18970. if (this._defines.FOG) {
  18971. fallbacks.addFallback(1, "FOG");
  18972. }
  18973. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18974. if (!this._defines["LIGHT" + lightIndex]) {
  18975. continue;
  18976. }
  18977. if (lightIndex > 0) {
  18978. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18979. }
  18980. if (this._defines["SHADOW" + lightIndex]) {
  18981. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18982. }
  18983. if (this._defines["SHADOWPCF" + lightIndex]) {
  18984. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18985. }
  18986. if (this._defines["SHADOWVSM" + lightIndex]) {
  18987. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18988. }
  18989. }
  18990. if (this._defines.SPECULARTERM) {
  18991. fallbacks.addFallback(0, "SPECULARTERM");
  18992. }
  18993. if (this._defines.DIFFUSEFRESNEL) {
  18994. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18995. }
  18996. if (this._defines.OPACITYFRESNEL) {
  18997. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18998. }
  18999. if (this._defines.REFLECTIONFRESNEL) {
  19000. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19001. }
  19002. if (this._defines.EMISSIVEFRESNEL) {
  19003. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19004. }
  19005. if (this._defines.FRESNEL) {
  19006. fallbacks.addFallback(4, "FRESNEL");
  19007. }
  19008. if (this._defines.BONES4) {
  19009. fallbacks.addFallback(0, "BONES4");
  19010. }
  19011. //Attributes
  19012. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19013. if (this._defines.NORMAL) {
  19014. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19015. }
  19016. if (this._defines.UV1) {
  19017. attribs.push(BABYLON.VertexBuffer.UVKind);
  19018. }
  19019. if (this._defines.UV2) {
  19020. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19021. }
  19022. if (this._defines.VERTEXCOLOR) {
  19023. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19024. }
  19025. if (this._defines.BONES) {
  19026. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19027. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19028. }
  19029. if (this._defines.INSTANCES) {
  19030. attribs.push("world0");
  19031. attribs.push("world1");
  19032. attribs.push("world2");
  19033. attribs.push("world3");
  19034. }
  19035. // Legacy browser patch
  19036. var shaderName = "default";
  19037. if (!scene.getEngine().getCaps().standardDerivatives) {
  19038. shaderName = "legacydefault";
  19039. }
  19040. var join = this._defines.toString();
  19041. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19042. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19043. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19044. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19045. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19046. "vFogInfos", "vFogColor", "pointSize",
  19047. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19048. "mBones",
  19049. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19050. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19051. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19052. "roughness"
  19053. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19054. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19055. ], join, fallbacks, this.onCompiled, this.onError);
  19056. }
  19057. if (!this._effect.isReady()) {
  19058. return false;
  19059. }
  19060. this._renderId = scene.getRenderId();
  19061. this._wasPreviouslyReady = true;
  19062. return true;
  19063. };
  19064. StandardMaterial.prototype.unbind = function () {
  19065. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19066. this._effect.setTexture("reflection2DSampler", null);
  19067. }
  19068. _super.prototype.unbind.call(this);
  19069. };
  19070. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19071. this._effect.setMatrix("world", world);
  19072. };
  19073. StandardMaterial.prototype.bind = function (world, mesh) {
  19074. var scene = this.getScene();
  19075. // Matrices
  19076. this.bindOnlyWorldMatrix(world);
  19077. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19078. // Bones
  19079. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19080. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19081. }
  19082. if (scene.getCachedMaterial() !== this) {
  19083. if (StandardMaterial.FresnelEnabled) {
  19084. // Fresnel
  19085. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19086. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19087. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19088. }
  19089. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19090. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19091. }
  19092. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19093. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19094. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19095. }
  19096. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19097. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19098. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19099. }
  19100. }
  19101. // Textures
  19102. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19103. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19104. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19105. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19106. }
  19107. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19108. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19109. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19110. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19111. }
  19112. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19113. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19114. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19115. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19116. }
  19117. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19118. if (this.reflectionTexture.isCube) {
  19119. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19120. if (this._defines.ROUGHNESS) {
  19121. this._effect.setFloat("roughness", this.roughness);
  19122. }
  19123. }
  19124. else {
  19125. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19126. }
  19127. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19128. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19129. }
  19130. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19131. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19132. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19133. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19134. }
  19135. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19136. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19137. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  19138. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19139. }
  19140. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19141. this._effect.setTexture("specularSampler", this.specularTexture);
  19142. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19143. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19144. }
  19145. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19146. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19147. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19148. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19149. }
  19150. // Clip plane
  19151. if (scene.clipPlane) {
  19152. var clipPlane = scene.clipPlane;
  19153. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19154. }
  19155. // Point size
  19156. if (this.pointsCloud) {
  19157. this._effect.setFloat("pointSize", this.pointSize);
  19158. }
  19159. // Colors
  19160. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19161. // Scaling down color according to emissive
  19162. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19163. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19164. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19165. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19166. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19167. if (this._defines.SPECULARTERM) {
  19168. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19169. }
  19170. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19171. }
  19172. // Scaling down color according to emissive
  19173. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19174. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19175. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19176. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19177. if (scene.lightsEnabled) {
  19178. var lightIndex = 0;
  19179. for (var index = 0; index < scene.lights.length; index++) {
  19180. var light = scene.lights[index];
  19181. if (!light.isEnabled()) {
  19182. continue;
  19183. }
  19184. if (!light.canAffectMesh(mesh)) {
  19185. continue;
  19186. }
  19187. if (light instanceof BABYLON.PointLight) {
  19188. // Point Light
  19189. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19190. }
  19191. else if (light instanceof BABYLON.DirectionalLight) {
  19192. // Directional Light
  19193. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19194. }
  19195. else if (light instanceof BABYLON.SpotLight) {
  19196. // Spot Light
  19197. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19198. }
  19199. else if (light instanceof BABYLON.HemisphericLight) {
  19200. // Hemispheric Light
  19201. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19202. }
  19203. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19204. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19205. if (this._defines.SPECULARTERM) {
  19206. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19207. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19208. }
  19209. // Shadows
  19210. if (scene.shadowsEnabled) {
  19211. var shadowGenerator = light.getShadowGenerator();
  19212. if (mesh.receiveShadows && shadowGenerator) {
  19213. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19214. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19215. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19216. }
  19217. }
  19218. lightIndex++;
  19219. if (lightIndex === maxSimultaneousLights)
  19220. break;
  19221. }
  19222. }
  19223. // View
  19224. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19225. this._effect.setMatrix("view", scene.getViewMatrix());
  19226. }
  19227. // Fog
  19228. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19229. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19230. this._effect.setColor3("vFogColor", scene.fogColor);
  19231. }
  19232. _super.prototype.bind.call(this, world, mesh);
  19233. };
  19234. StandardMaterial.prototype.getAnimatables = function () {
  19235. var results = [];
  19236. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19237. results.push(this.diffuseTexture);
  19238. }
  19239. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19240. results.push(this.ambientTexture);
  19241. }
  19242. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19243. results.push(this.opacityTexture);
  19244. }
  19245. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19246. results.push(this.reflectionTexture);
  19247. }
  19248. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19249. results.push(this.emissiveTexture);
  19250. }
  19251. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19252. results.push(this.specularTexture);
  19253. }
  19254. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19255. results.push(this.bumpTexture);
  19256. }
  19257. return results;
  19258. };
  19259. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19260. if (this.diffuseTexture) {
  19261. this.diffuseTexture.dispose();
  19262. }
  19263. if (this.ambientTexture) {
  19264. this.ambientTexture.dispose();
  19265. }
  19266. if (this.opacityTexture) {
  19267. this.opacityTexture.dispose();
  19268. }
  19269. if (this.reflectionTexture) {
  19270. this.reflectionTexture.dispose();
  19271. }
  19272. if (this.emissiveTexture) {
  19273. this.emissiveTexture.dispose();
  19274. }
  19275. if (this.specularTexture) {
  19276. this.specularTexture.dispose();
  19277. }
  19278. if (this.bumpTexture) {
  19279. this.bumpTexture.dispose();
  19280. }
  19281. _super.prototype.dispose.call(this, forceDisposeEffect);
  19282. };
  19283. StandardMaterial.prototype.clone = function (name) {
  19284. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19285. // Base material
  19286. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19287. newStandardMaterial.alpha = this.alpha;
  19288. newStandardMaterial.fillMode = this.fillMode;
  19289. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19290. // Standard material
  19291. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19292. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19293. }
  19294. if (this.ambientTexture && this.ambientTexture.clone) {
  19295. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19296. }
  19297. if (this.opacityTexture && this.opacityTexture.clone) {
  19298. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19299. }
  19300. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19301. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19302. }
  19303. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19304. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19305. }
  19306. if (this.specularTexture && this.specularTexture.clone) {
  19307. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19308. }
  19309. if (this.bumpTexture && this.bumpTexture.clone) {
  19310. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19311. }
  19312. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19313. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19314. newStandardMaterial.specularColor = this.specularColor.clone();
  19315. newStandardMaterial.specularPower = this.specularPower;
  19316. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19317. return newStandardMaterial;
  19318. };
  19319. // Statics
  19320. // Flags used to enable or disable a type of texture for all Standard Materials
  19321. StandardMaterial.DiffuseTextureEnabled = true;
  19322. StandardMaterial.AmbientTextureEnabled = true;
  19323. StandardMaterial.OpacityTextureEnabled = true;
  19324. StandardMaterial.ReflectionTextureEnabled = true;
  19325. StandardMaterial.EmissiveTextureEnabled = true;
  19326. StandardMaterial.SpecularTextureEnabled = true;
  19327. StandardMaterial.BumpTextureEnabled = true;
  19328. StandardMaterial.FresnelEnabled = true;
  19329. StandardMaterial.LightmapEnabled = true;
  19330. return StandardMaterial;
  19331. })(BABYLON.Material);
  19332. BABYLON.StandardMaterial = StandardMaterial;
  19333. })(BABYLON || (BABYLON = {}));
  19334. var BABYLON;
  19335. (function (BABYLON) {
  19336. var MultiMaterial = (function (_super) {
  19337. __extends(MultiMaterial, _super);
  19338. function MultiMaterial(name, scene) {
  19339. _super.call(this, name, scene, true);
  19340. this.subMaterials = new Array();
  19341. scene.multiMaterials.push(this);
  19342. }
  19343. // Properties
  19344. MultiMaterial.prototype.getSubMaterial = function (index) {
  19345. if (index < 0 || index >= this.subMaterials.length) {
  19346. return this.getScene().defaultMaterial;
  19347. }
  19348. return this.subMaterials[index];
  19349. };
  19350. // Methods
  19351. MultiMaterial.prototype.isReady = function (mesh) {
  19352. for (var index = 0; index < this.subMaterials.length; index++) {
  19353. var subMaterial = this.subMaterials[index];
  19354. if (subMaterial) {
  19355. if (!this.subMaterials[index].isReady(mesh)) {
  19356. return false;
  19357. }
  19358. }
  19359. }
  19360. return true;
  19361. };
  19362. MultiMaterial.prototype.clone = function (name) {
  19363. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19364. for (var index = 0; index < this.subMaterials.length; index++) {
  19365. var subMaterial = this.subMaterials[index];
  19366. newMultiMaterial.subMaterials.push(subMaterial);
  19367. }
  19368. return newMultiMaterial;
  19369. };
  19370. return MultiMaterial;
  19371. })(BABYLON.Material);
  19372. BABYLON.MultiMaterial = MultiMaterial;
  19373. })(BABYLON || (BABYLON = {}));
  19374. var BABYLON;
  19375. (function (BABYLON) {
  19376. var SceneLoader = (function () {
  19377. function SceneLoader() {
  19378. }
  19379. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19380. get: function () {
  19381. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19382. },
  19383. set: function (value) {
  19384. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19390. get: function () {
  19391. return SceneLoader._ShowLoadingScreen;
  19392. },
  19393. set: function (value) {
  19394. SceneLoader._ShowLoadingScreen = value;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19400. var dotPosition = sceneFilename.lastIndexOf(".");
  19401. var queryStringPosition = sceneFilename.indexOf("?");
  19402. if (queryStringPosition === -1) {
  19403. queryStringPosition = sceneFilename.length;
  19404. }
  19405. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19406. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19407. var plugin = this._registeredPlugins[index];
  19408. if (plugin.extensions.indexOf(extension) !== -1) {
  19409. return plugin;
  19410. }
  19411. }
  19412. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19413. };
  19414. // Public functions
  19415. SceneLoader.RegisterPlugin = function (plugin) {
  19416. plugin.extensions = plugin.extensions.toLowerCase();
  19417. SceneLoader._registeredPlugins.push(plugin);
  19418. };
  19419. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19420. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19421. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19422. return;
  19423. }
  19424. var loadingToken = {};
  19425. scene._addPendingData(loadingToken);
  19426. var manifestChecked = function (success) {
  19427. scene.database = database;
  19428. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19429. var importMeshFromData = function (data) {
  19430. var meshes = [];
  19431. var particleSystems = [];
  19432. var skeletons = [];
  19433. try {
  19434. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19435. if (onerror) {
  19436. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19437. }
  19438. scene._removePendingData(loadingToken);
  19439. return;
  19440. }
  19441. }
  19442. catch (e) {
  19443. if (onerror) {
  19444. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19445. }
  19446. scene._removePendingData(loadingToken);
  19447. return;
  19448. }
  19449. if (onsuccess) {
  19450. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19451. onsuccess(meshes, particleSystems, skeletons);
  19452. scene._removePendingData(loadingToken);
  19453. }
  19454. };
  19455. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19456. // Direct load
  19457. importMeshFromData(sceneFilename.substr(5));
  19458. return;
  19459. }
  19460. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19461. importMeshFromData(data);
  19462. }, progressCallBack, database);
  19463. };
  19464. if (scene.getEngine().enableOfflineSupport) {
  19465. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19466. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19467. }
  19468. else {
  19469. manifestChecked(true);
  19470. }
  19471. };
  19472. /**
  19473. * Load a scene
  19474. * @param rootUrl a string that defines the root url for scene and resources
  19475. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19476. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19477. */
  19478. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19479. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19480. };
  19481. /**
  19482. * Append a scene
  19483. * @param rootUrl a string that defines the root url for scene and resources
  19484. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19485. * @param scene is the instance of BABYLON.Scene to append to
  19486. */
  19487. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19488. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19489. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19490. return;
  19491. }
  19492. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19493. var database;
  19494. var loadingToken = {};
  19495. scene._addPendingData(loadingToken);
  19496. if (SceneLoader.ShowLoadingScreen) {
  19497. scene.getEngine().displayLoadingUI();
  19498. }
  19499. var loadSceneFromData = function (data) {
  19500. scene.database = database;
  19501. if (!plugin.load(scene, data, rootUrl)) {
  19502. if (onerror) {
  19503. onerror(scene);
  19504. }
  19505. scene._removePendingData(loadingToken);
  19506. scene.getEngine().hideLoadingUI();
  19507. return;
  19508. }
  19509. if (onsuccess) {
  19510. onsuccess(scene);
  19511. }
  19512. scene._removePendingData(loadingToken);
  19513. if (SceneLoader.ShowLoadingScreen) {
  19514. scene.executeWhenReady(function () {
  19515. scene.getEngine().hideLoadingUI();
  19516. });
  19517. }
  19518. };
  19519. var manifestChecked = function (success) {
  19520. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19521. };
  19522. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19523. // Direct load
  19524. loadSceneFromData(sceneFilename.substr(5));
  19525. return;
  19526. }
  19527. if (rootUrl.indexOf("file:") === -1) {
  19528. if (scene.getEngine().enableOfflineSupport) {
  19529. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19530. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19531. }
  19532. else {
  19533. manifestChecked(true);
  19534. }
  19535. }
  19536. else {
  19537. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19538. }
  19539. };
  19540. // Flags
  19541. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19542. SceneLoader._ShowLoadingScreen = true;
  19543. // Members
  19544. SceneLoader._registeredPlugins = new Array();
  19545. return SceneLoader;
  19546. })();
  19547. BABYLON.SceneLoader = SceneLoader;
  19548. ;
  19549. })(BABYLON || (BABYLON = {}));
  19550. var BABYLON;
  19551. (function (BABYLON) {
  19552. var Internals;
  19553. (function (Internals) {
  19554. var checkColors4 = function (colors, count) {
  19555. // Check if color3 was used
  19556. if (colors.length === count * 3) {
  19557. var colors4 = [];
  19558. for (var index = 0; index < colors.length; index += 3) {
  19559. var newIndex = (index / 3) * 4;
  19560. colors4[newIndex] = colors[index];
  19561. colors4[newIndex + 1] = colors[index + 1];
  19562. colors4[newIndex + 2] = colors[index + 2];
  19563. colors4[newIndex + 3] = 1.0;
  19564. }
  19565. return colors4;
  19566. }
  19567. return colors;
  19568. };
  19569. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19570. var texture = null;
  19571. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19572. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19573. texture.name = parsedTexture.name;
  19574. texture.hasAlpha = parsedTexture.hasAlpha;
  19575. texture.level = parsedTexture.level;
  19576. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19577. }
  19578. return texture;
  19579. };
  19580. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19581. if (parsedTexture.isCube) {
  19582. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19583. }
  19584. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19585. return null;
  19586. }
  19587. var texture;
  19588. if (parsedTexture.mirrorPlane) {
  19589. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19590. texture._waitingRenderList = parsedTexture.renderList;
  19591. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19592. }
  19593. else if (parsedTexture.isRenderTarget) {
  19594. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19595. texture._waitingRenderList = parsedTexture.renderList;
  19596. }
  19597. else {
  19598. if (parsedTexture.base64String) {
  19599. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19600. }
  19601. else {
  19602. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19603. }
  19604. }
  19605. texture.name = parsedTexture.name;
  19606. texture.hasAlpha = parsedTexture.hasAlpha;
  19607. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19608. texture.level = parsedTexture.level;
  19609. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19610. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19611. texture.uOffset = parsedTexture.uOffset;
  19612. texture.vOffset = parsedTexture.vOffset;
  19613. texture.uScale = parsedTexture.uScale;
  19614. texture.vScale = parsedTexture.vScale;
  19615. texture.uAng = parsedTexture.uAng;
  19616. texture.vAng = parsedTexture.vAng;
  19617. texture.wAng = parsedTexture.wAng;
  19618. texture.wrapU = parsedTexture.wrapU;
  19619. texture.wrapV = parsedTexture.wrapV;
  19620. // Animations
  19621. if (parsedTexture.animations) {
  19622. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19623. var parsedAnimation = parsedTexture.animations[animationIndex];
  19624. texture.animations.push(parseAnimation(parsedAnimation));
  19625. }
  19626. }
  19627. return texture;
  19628. };
  19629. var parseSkeleton = function (parsedSkeleton, scene) {
  19630. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19631. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19632. var parsedBone = parsedSkeleton.bones[index];
  19633. var parentBone = null;
  19634. if (parsedBone.parentBoneIndex > -1) {
  19635. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19636. }
  19637. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19638. if (parsedBone.animation) {
  19639. bone.animations.push(parseAnimation(parsedBone.animation));
  19640. }
  19641. }
  19642. return skeleton;
  19643. };
  19644. var parseFresnelParameters = function (parsedFresnelParameters) {
  19645. var fresnelParameters = new BABYLON.FresnelParameters();
  19646. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19647. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19648. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19649. fresnelParameters.bias = parsedFresnelParameters.bias;
  19650. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19651. return fresnelParameters;
  19652. };
  19653. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19654. var material;
  19655. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19656. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19657. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19658. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19659. material.specularPower = parsedMaterial.specularPower;
  19660. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19661. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19662. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19663. material.alpha = parsedMaterial.alpha;
  19664. material.id = parsedMaterial.id;
  19665. if (parsedMaterial.disableDepthWrite) {
  19666. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19667. }
  19668. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19669. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19670. material.wireframe = parsedMaterial.wireframe;
  19671. if (parsedMaterial.diffuseTexture) {
  19672. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19673. }
  19674. if (parsedMaterial.diffuseFresnelParameters) {
  19675. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19676. }
  19677. if (parsedMaterial.ambientTexture) {
  19678. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19679. }
  19680. if (parsedMaterial.opacityTexture) {
  19681. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19682. }
  19683. if (parsedMaterial.opacityFresnelParameters) {
  19684. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19685. }
  19686. if (parsedMaterial.reflectionTexture) {
  19687. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19688. }
  19689. if (parsedMaterial.reflectionFresnelParameters) {
  19690. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19691. }
  19692. if (parsedMaterial.emissiveTexture) {
  19693. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19694. }
  19695. if (parsedMaterial.lightmapTexture) {
  19696. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19697. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19698. }
  19699. if (parsedMaterial.emissiveFresnelParameters) {
  19700. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19701. }
  19702. if (parsedMaterial.specularTexture) {
  19703. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19704. }
  19705. if (parsedMaterial.bumpTexture) {
  19706. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19707. }
  19708. if (parsedMaterial.checkReadyOnlyOnce) {
  19709. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19710. }
  19711. return material;
  19712. };
  19713. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19714. for (var index = 0; index < parsedData.materials.length; index++) {
  19715. var parsedMaterial = parsedData.materials[index];
  19716. if (parsedMaterial.id === id) {
  19717. return parseMaterial(parsedMaterial, scene, rootUrl);
  19718. }
  19719. }
  19720. return null;
  19721. };
  19722. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19723. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19724. multiMaterial.id = parsedMultiMaterial.id;
  19725. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19726. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19727. var subMatId = parsedMultiMaterial.materials[matIndex];
  19728. if (subMatId) {
  19729. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19730. }
  19731. else {
  19732. multiMaterial.subMaterials.push(null);
  19733. }
  19734. }
  19735. return multiMaterial;
  19736. };
  19737. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19738. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19739. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19740. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19741. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19742. var parsedFlare = parsedLensFlareSystem.flares[index];
  19743. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19744. }
  19745. return lensFlareSystem;
  19746. };
  19747. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19748. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19749. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19750. if (parsedParticleSystem.textureName) {
  19751. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19752. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19753. }
  19754. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19755. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19756. particleSystem.minSize = parsedParticleSystem.minSize;
  19757. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19758. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19759. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19760. particleSystem.emitter = emitter;
  19761. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19762. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19763. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19764. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19765. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19766. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19767. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19768. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19769. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19770. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19771. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19772. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19773. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19774. particleSystem.start();
  19775. return particleSystem;
  19776. };
  19777. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19778. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19779. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19780. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19781. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19782. shadowGenerator.getShadowMap().renderList.push(mesh);
  19783. }
  19784. if (parsedShadowGenerator.usePoissonSampling) {
  19785. shadowGenerator.usePoissonSampling = true;
  19786. }
  19787. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19788. shadowGenerator.useVarianceShadowMap = true;
  19789. }
  19790. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19791. shadowGenerator.useBlurVarianceShadowMap = true;
  19792. if (parsedShadowGenerator.blurScale) {
  19793. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19794. }
  19795. if (parsedShadowGenerator.blurBoxOffset) {
  19796. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19797. }
  19798. }
  19799. if (parsedShadowGenerator.bias !== undefined) {
  19800. shadowGenerator.bias = parsedShadowGenerator.bias;
  19801. }
  19802. return shadowGenerator;
  19803. };
  19804. var parseAnimation = function (parsedAnimation) {
  19805. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19806. var dataType = parsedAnimation.dataType;
  19807. var keys = [];
  19808. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19809. var key = parsedAnimation.keys[index];
  19810. var data;
  19811. switch (dataType) {
  19812. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19813. data = key.values[0];
  19814. break;
  19815. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19816. data = BABYLON.Quaternion.FromArray(key.values);
  19817. break;
  19818. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19819. data = BABYLON.Matrix.FromArray(key.values);
  19820. break;
  19821. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19822. default:
  19823. data = BABYLON.Vector3.FromArray(key.values);
  19824. break;
  19825. }
  19826. keys.push({
  19827. frame: key.frame,
  19828. value: data
  19829. });
  19830. }
  19831. animation.setKeys(keys);
  19832. return animation;
  19833. };
  19834. var parseLight = function (parsedLight, scene) {
  19835. var light;
  19836. switch (parsedLight.type) {
  19837. case 0:
  19838. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19839. break;
  19840. case 1:
  19841. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19842. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19843. break;
  19844. case 2:
  19845. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19846. break;
  19847. case 3:
  19848. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19849. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19850. break;
  19851. }
  19852. light.id = parsedLight.id;
  19853. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19854. if (parsedLight.intensity !== undefined) {
  19855. light.intensity = parsedLight.intensity;
  19856. }
  19857. if (parsedLight.range) {
  19858. light.range = parsedLight.range;
  19859. }
  19860. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19861. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19862. if (parsedLight.excludedMeshesIds) {
  19863. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19864. }
  19865. // Parent
  19866. if (parsedLight.parentId) {
  19867. light._waitingParentId = parsedLight.parentId;
  19868. }
  19869. if (parsedLight.includedOnlyMeshesIds) {
  19870. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19871. }
  19872. // Animations
  19873. if (parsedLight.animations) {
  19874. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19875. var parsedAnimation = parsedLight.animations[animationIndex];
  19876. light.animations.push(parseAnimation(parsedAnimation));
  19877. }
  19878. }
  19879. if (parsedLight.autoAnimate) {
  19880. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19881. }
  19882. };
  19883. var parseCamera = function (parsedCamera, scene) {
  19884. var camera;
  19885. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19886. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19887. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19888. var alpha = parsedCamera.alpha;
  19889. var beta = parsedCamera.beta;
  19890. var radius = parsedCamera.radius;
  19891. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19892. var interaxial_distance = parsedCamera.interaxial_distance;
  19893. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19894. }
  19895. else {
  19896. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19897. }
  19898. }
  19899. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19900. interaxial_distance = parsedCamera.interaxial_distance;
  19901. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19902. }
  19903. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19904. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19905. }
  19906. else if (parsedCamera.type === "FollowCamera") {
  19907. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19908. camera.heightOffset = parsedCamera.heightOffset;
  19909. camera.radius = parsedCamera.radius;
  19910. camera.rotationOffset = parsedCamera.rotationOffset;
  19911. if (lockedTargetMesh)
  19912. camera.target = lockedTargetMesh;
  19913. }
  19914. else if (parsedCamera.type === "GamepadCamera") {
  19915. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19916. }
  19917. else if (parsedCamera.type === "TouchCamera") {
  19918. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19919. }
  19920. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19921. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19922. }
  19923. else if (parsedCamera.type === "WebVRFreeCamera") {
  19924. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19925. }
  19926. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19927. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19928. }
  19929. else {
  19930. // Free Camera is the default value
  19931. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19932. }
  19933. // apply 3d rig, when found
  19934. if (parsedCamera.cameraRigMode) {
  19935. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19936. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19937. }
  19938. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19939. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19940. camera.lockedTarget = lockedTargetMesh;
  19941. }
  19942. camera.id = parsedCamera.id;
  19943. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19944. // Parent
  19945. if (parsedCamera.parentId) {
  19946. camera._waitingParentId = parsedCamera.parentId;
  19947. }
  19948. // Target
  19949. if (parsedCamera.target) {
  19950. if (camera.setTarget) {
  19951. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19952. }
  19953. else {
  19954. //For ArcRotate
  19955. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19956. }
  19957. }
  19958. else {
  19959. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19960. }
  19961. camera.fov = parsedCamera.fov;
  19962. camera.minZ = parsedCamera.minZ;
  19963. camera.maxZ = parsedCamera.maxZ;
  19964. camera.speed = parsedCamera.speed;
  19965. camera.inertia = parsedCamera.inertia;
  19966. camera.checkCollisions = parsedCamera.checkCollisions;
  19967. camera.applyGravity = parsedCamera.applyGravity;
  19968. if (parsedCamera.ellipsoid) {
  19969. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19970. }
  19971. // Animations
  19972. if (parsedCamera.animations) {
  19973. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19974. var parsedAnimation = parsedCamera.animations[animationIndex];
  19975. camera.animations.push(parseAnimation(parsedAnimation));
  19976. }
  19977. }
  19978. if (parsedCamera.autoAnimate) {
  19979. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19980. }
  19981. // Layer Mask
  19982. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19983. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19984. }
  19985. else {
  19986. camera.layerMask = 0x0FFFFFFF;
  19987. }
  19988. return camera;
  19989. };
  19990. var parseGeometry = function (parsedGeometry, scene) {
  19991. var id = parsedGeometry.id;
  19992. return scene.getGeometryByID(id);
  19993. };
  19994. var parseBox = function (parsedBox, scene) {
  19995. if (parseGeometry(parsedBox, scene)) {
  19996. return null; // null since geometry could be something else than a box...
  19997. }
  19998. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19999. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20000. scene.pushGeometry(box, true);
  20001. return box;
  20002. };
  20003. var parseSphere = function (parsedSphere, scene) {
  20004. if (parseGeometry(parsedSphere, scene)) {
  20005. return null; // null since geometry could be something else than a sphere...
  20006. }
  20007. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20008. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20009. scene.pushGeometry(sphere, true);
  20010. return sphere;
  20011. };
  20012. var parseCylinder = function (parsedCylinder, scene) {
  20013. if (parseGeometry(parsedCylinder, scene)) {
  20014. return null; // null since geometry could be something else than a cylinder...
  20015. }
  20016. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20017. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20018. scene.pushGeometry(cylinder, true);
  20019. return cylinder;
  20020. };
  20021. var parseTorus = function (parsedTorus, scene) {
  20022. if (parseGeometry(parsedTorus, scene)) {
  20023. return null; // null since geometry could be something else than a torus...
  20024. }
  20025. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20026. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20027. scene.pushGeometry(torus, true);
  20028. return torus;
  20029. };
  20030. var parseGround = function (parsedGround, scene) {
  20031. if (parseGeometry(parsedGround, scene)) {
  20032. return null; // null since geometry could be something else than a ground...
  20033. }
  20034. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20035. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20036. scene.pushGeometry(ground, true);
  20037. return ground;
  20038. };
  20039. var parsePlane = function (parsedPlane, scene) {
  20040. if (parseGeometry(parsedPlane, scene)) {
  20041. return null; // null since geometry could be something else than a plane...
  20042. }
  20043. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20044. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20045. scene.pushGeometry(plane, true);
  20046. return plane;
  20047. };
  20048. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20049. if (parseGeometry(parsedTorusKnot, scene)) {
  20050. return null; // null since geometry could be something else than a torusKnot...
  20051. }
  20052. 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);
  20053. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20054. scene.pushGeometry(torusKnot, true);
  20055. return torusKnot;
  20056. };
  20057. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20058. if (parseGeometry(parsedVertexData, scene)) {
  20059. return null; // null since geometry could be a primitive
  20060. }
  20061. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20062. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20063. if (parsedVertexData.delayLoadingFile) {
  20064. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20065. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20066. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20067. geometry._delayInfo = [];
  20068. if (parsedVertexData.hasUVs) {
  20069. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20070. }
  20071. if (parsedVertexData.hasUVs2) {
  20072. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20073. }
  20074. if (parsedVertexData.hasUVs3) {
  20075. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20076. }
  20077. if (parsedVertexData.hasUVs4) {
  20078. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20079. }
  20080. if (parsedVertexData.hasUVs5) {
  20081. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20082. }
  20083. if (parsedVertexData.hasUVs6) {
  20084. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20085. }
  20086. if (parsedVertexData.hasColors) {
  20087. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20088. }
  20089. if (parsedVertexData.hasMatricesIndices) {
  20090. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20091. }
  20092. if (parsedVertexData.hasMatricesWeights) {
  20093. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20094. }
  20095. geometry._delayLoadingFunction = importVertexData;
  20096. }
  20097. else {
  20098. importVertexData(parsedVertexData, geometry);
  20099. }
  20100. scene.pushGeometry(geometry, true);
  20101. return geometry;
  20102. };
  20103. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20104. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20105. mesh.id = parsedMesh.id;
  20106. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20107. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20108. if (parsedMesh.rotationQuaternion) {
  20109. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20110. }
  20111. else if (parsedMesh.rotation) {
  20112. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20113. }
  20114. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20115. if (parsedMesh.localMatrix) {
  20116. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20117. }
  20118. else if (parsedMesh.pivotMatrix) {
  20119. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20120. }
  20121. mesh.setEnabled(parsedMesh.isEnabled);
  20122. mesh.isVisible = parsedMesh.isVisible;
  20123. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20124. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20125. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20126. if (parsedMesh.applyFog !== undefined) {
  20127. mesh.applyFog = parsedMesh.applyFog;
  20128. }
  20129. if (parsedMesh.pickable !== undefined) {
  20130. mesh.isPickable = parsedMesh.pickable;
  20131. }
  20132. if (parsedMesh.alphaIndex !== undefined) {
  20133. mesh.alphaIndex = parsedMesh.alphaIndex;
  20134. }
  20135. mesh.receiveShadows = parsedMesh.receiveShadows;
  20136. mesh.billboardMode = parsedMesh.billboardMode;
  20137. if (parsedMesh.visibility !== undefined) {
  20138. mesh.visibility = parsedMesh.visibility;
  20139. }
  20140. mesh.checkCollisions = parsedMesh.checkCollisions;
  20141. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20142. // freezeWorldMatrix
  20143. if (parsedMesh.freezeWorldMatrix) {
  20144. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20145. }
  20146. // Parent
  20147. if (parsedMesh.parentId) {
  20148. mesh._waitingParentId = parsedMesh.parentId;
  20149. }
  20150. // Actions
  20151. if (parsedMesh.actions !== undefined) {
  20152. mesh._waitingActions = parsedMesh.actions;
  20153. }
  20154. // Geometry
  20155. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20156. if (parsedMesh.delayLoadingFile) {
  20157. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20158. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20159. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20160. if (parsedMesh._binaryInfo) {
  20161. mesh._binaryInfo = parsedMesh._binaryInfo;
  20162. }
  20163. mesh._delayInfo = [];
  20164. if (parsedMesh.hasUVs) {
  20165. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20166. }
  20167. if (parsedMesh.hasUVs2) {
  20168. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20169. }
  20170. if (parsedMesh.hasUVs3) {
  20171. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20172. }
  20173. if (parsedMesh.hasUVs4) {
  20174. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20175. }
  20176. if (parsedMesh.hasUVs5) {
  20177. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20178. }
  20179. if (parsedMesh.hasUVs6) {
  20180. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20181. }
  20182. if (parsedMesh.hasColors) {
  20183. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20184. }
  20185. if (parsedMesh.hasMatricesIndices) {
  20186. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20187. }
  20188. if (parsedMesh.hasMatricesWeights) {
  20189. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20190. }
  20191. mesh._delayLoadingFunction = importGeometry;
  20192. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20193. mesh._checkDelayState();
  20194. }
  20195. }
  20196. else {
  20197. importGeometry(parsedMesh, mesh);
  20198. }
  20199. // Material
  20200. if (parsedMesh.materialId) {
  20201. mesh.setMaterialByID(parsedMesh.materialId);
  20202. }
  20203. else {
  20204. mesh.material = null;
  20205. }
  20206. // Skeleton
  20207. if (parsedMesh.skeletonId > -1) {
  20208. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20209. }
  20210. // Physics
  20211. if (parsedMesh.physicsImpostor) {
  20212. if (!scene.isPhysicsEnabled()) {
  20213. scene.enablePhysics();
  20214. }
  20215. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20216. }
  20217. // Animations
  20218. if (parsedMesh.animations) {
  20219. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20220. var parsedAnimation = parsedMesh.animations[animationIndex];
  20221. mesh.animations.push(parseAnimation(parsedAnimation));
  20222. }
  20223. }
  20224. if (parsedMesh.autoAnimate) {
  20225. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20226. }
  20227. // Layer Mask
  20228. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20229. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20230. }
  20231. else {
  20232. mesh.layerMask = 0x0FFFFFFF;
  20233. }
  20234. // Instances
  20235. if (parsedMesh.instances) {
  20236. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20237. var parsedInstance = parsedMesh.instances[index];
  20238. var instance = mesh.createInstance(parsedInstance.name);
  20239. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20240. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20241. if (parsedInstance.rotationQuaternion) {
  20242. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20243. }
  20244. else if (parsedInstance.rotation) {
  20245. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20246. }
  20247. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20248. instance.checkCollisions = mesh.checkCollisions;
  20249. if (parsedMesh.animations) {
  20250. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20251. parsedAnimation = parsedMesh.animations[animationIndex];
  20252. instance.animations.push(parseAnimation(parsedAnimation));
  20253. }
  20254. }
  20255. }
  20256. }
  20257. return mesh;
  20258. };
  20259. var parseActions = function (parsedActions, object, scene) {
  20260. var actionManager = new BABYLON.ActionManager(scene);
  20261. if (object === null)
  20262. scene.actionManager = actionManager;
  20263. else
  20264. object.actionManager = actionManager;
  20265. // instanciate a new object
  20266. var instanciate = function (name, params) {
  20267. var newInstance = Object.create(BABYLON[name].prototype);
  20268. newInstance.constructor.apply(newInstance, params);
  20269. return newInstance;
  20270. };
  20271. var parseParameter = function (name, value, target, propertyPath) {
  20272. if (propertyPath === null) {
  20273. // String, boolean or float
  20274. var floatValue = parseFloat(value);
  20275. if (value === "true" || value === "false")
  20276. return value === "true";
  20277. else
  20278. return isNaN(floatValue) ? value : floatValue;
  20279. }
  20280. var effectiveTarget = propertyPath.split(".");
  20281. var values = value.split(",");
  20282. // Get effective Target
  20283. for (var i = 0; i < effectiveTarget.length; i++) {
  20284. target = target[effectiveTarget[i]];
  20285. }
  20286. // Return appropriate value with its type
  20287. if (typeof (target) === "boolean")
  20288. return values[0] === "true";
  20289. if (typeof (target) === "string")
  20290. return values[0];
  20291. // Parameters with multiple values such as Vector3 etc.
  20292. var split = new Array();
  20293. for (var i = 0; i < values.length; i++)
  20294. split.push(parseFloat(values[i]));
  20295. if (target instanceof BABYLON.Vector3)
  20296. return BABYLON.Vector3.FromArray(split);
  20297. if (target instanceof BABYLON.Vector4)
  20298. return BABYLON.Vector4.FromArray(split);
  20299. if (target instanceof BABYLON.Color3)
  20300. return BABYLON.Color3.FromArray(split);
  20301. if (target instanceof BABYLON.Color4)
  20302. return BABYLON.Color4.FromArray(split);
  20303. return parseFloat(values[0]);
  20304. };
  20305. // traverse graph per trigger
  20306. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20307. if (combineArray === void 0) { combineArray = null; }
  20308. if (parsedAction.detached)
  20309. return;
  20310. var parameters = new Array();
  20311. var target = null;
  20312. var propertyPath = null;
  20313. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20314. // Parameters
  20315. if (parsedAction.type === 2)
  20316. parameters.push(actionManager);
  20317. else
  20318. parameters.push(trigger);
  20319. if (combine) {
  20320. var actions = new Array();
  20321. for (var j = 0; j < parsedAction.combine.length; j++) {
  20322. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20323. }
  20324. parameters.push(actions);
  20325. }
  20326. else {
  20327. for (var i = 0; i < parsedAction.properties.length; i++) {
  20328. var value = parsedAction.properties[i].value;
  20329. var name = parsedAction.properties[i].name;
  20330. var targetType = parsedAction.properties[i].targetType;
  20331. if (name === "target")
  20332. if (targetType !== null && targetType === "SceneProperties")
  20333. value = target = scene;
  20334. else
  20335. value = target = scene.getNodeByName(value);
  20336. else if (name === "parent")
  20337. value = scene.getNodeByName(value);
  20338. else if (name === "sound")
  20339. value = scene.getSoundByName(value);
  20340. else if (name !== "propertyPath") {
  20341. if (parsedAction.type === 2 && name === "operator")
  20342. value = BABYLON.ValueCondition[value];
  20343. else
  20344. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20345. }
  20346. else {
  20347. propertyPath = value;
  20348. }
  20349. parameters.push(value);
  20350. }
  20351. }
  20352. if (combineArray === null) {
  20353. parameters.push(condition);
  20354. }
  20355. else {
  20356. parameters.push(null);
  20357. }
  20358. // If interpolate value action
  20359. if (parsedAction.name === "InterpolateValueAction") {
  20360. var param = parameters[parameters.length - 2];
  20361. parameters[parameters.length - 1] = param;
  20362. parameters[parameters.length - 2] = condition;
  20363. }
  20364. // Action or condition(s) and not CombineAction
  20365. var newAction = instanciate(parsedAction.name, parameters);
  20366. if (combineArray === null) {
  20367. if (newAction instanceof BABYLON.Condition) {
  20368. condition = newAction;
  20369. newAction = action;
  20370. }
  20371. else {
  20372. condition = null;
  20373. if (action)
  20374. action.then(newAction);
  20375. else
  20376. actionManager.registerAction(newAction);
  20377. }
  20378. }
  20379. else {
  20380. combineArray.push(newAction);
  20381. }
  20382. for (var i = 0; i < parsedAction.children.length; i++)
  20383. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20384. };
  20385. // triggers
  20386. for (var i = 0; i < parsedActions.children.length; i++) {
  20387. var triggerParams;
  20388. var trigger = parsedActions.children[i];
  20389. if (trigger.properties.length > 0) {
  20390. var param = trigger.properties[0].value;
  20391. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20392. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20393. }
  20394. else
  20395. triggerParams = BABYLON.ActionManager[trigger.name];
  20396. for (var j = 0; j < trigger.children.length; j++) {
  20397. if (!trigger.detached)
  20398. traverse(trigger.children[j], triggerParams, null, null);
  20399. }
  20400. }
  20401. };
  20402. var parseSound = function (parsedSound, scene, rootUrl) {
  20403. var soundName = parsedSound.name;
  20404. var soundUrl = rootUrl + soundName;
  20405. var options = {
  20406. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20407. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20408. rolloffFactor: parsedSound.rolloffFactor,
  20409. refDistance: parsedSound.refDistance,
  20410. distanceModel: parsedSound.distanceModel,
  20411. playbackRate: parsedSound.playbackRate
  20412. };
  20413. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20414. scene._addPendingData(newSound);
  20415. if (parsedSound.position) {
  20416. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20417. newSound.setPosition(soundPosition);
  20418. }
  20419. if (parsedSound.isDirectional) {
  20420. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20421. if (parsedSound.localDirectionToMesh) {
  20422. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20423. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20424. }
  20425. }
  20426. if (parsedSound.connectedMeshId) {
  20427. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20428. if (connectedMesh) {
  20429. newSound.attachToMesh(connectedMesh);
  20430. }
  20431. }
  20432. };
  20433. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20434. names = (names instanceof Array) ? names : [names];
  20435. for (var i in names) {
  20436. if (mesh.name === names[i]) {
  20437. hierarchyIds.push(mesh.id);
  20438. return true;
  20439. }
  20440. }
  20441. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20442. hierarchyIds.push(mesh.id);
  20443. return true;
  20444. }
  20445. return false;
  20446. };
  20447. var importVertexData = function (parsedVertexData, geometry) {
  20448. var vertexData = new BABYLON.VertexData();
  20449. // positions
  20450. var positions = parsedVertexData.positions;
  20451. if (positions) {
  20452. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20453. }
  20454. // normals
  20455. var normals = parsedVertexData.normals;
  20456. if (normals) {
  20457. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20458. }
  20459. // uvs
  20460. var uvs = parsedVertexData.uvs;
  20461. if (uvs) {
  20462. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20463. }
  20464. // uv2s
  20465. var uv2s = parsedVertexData.uv2s;
  20466. if (uv2s) {
  20467. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20468. }
  20469. // uv3s
  20470. var uv3s = parsedVertexData.uv3s;
  20471. if (uv3s) {
  20472. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20473. }
  20474. // uv4s
  20475. var uv4s = parsedVertexData.uv4s;
  20476. if (uv4s) {
  20477. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20478. }
  20479. // uv5s
  20480. var uv5s = parsedVertexData.uv5s;
  20481. if (uv5s) {
  20482. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20483. }
  20484. // uv6s
  20485. var uv6s = parsedVertexData.uv6s;
  20486. if (uv6s) {
  20487. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20488. }
  20489. // colors
  20490. var colors = parsedVertexData.colors;
  20491. if (colors) {
  20492. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20493. }
  20494. // matricesIndices
  20495. var matricesIndices = parsedVertexData.matricesIndices;
  20496. if (matricesIndices) {
  20497. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20498. }
  20499. // matricesWeights
  20500. var matricesWeights = parsedVertexData.matricesWeights;
  20501. if (matricesWeights) {
  20502. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20503. }
  20504. // indices
  20505. var indices = parsedVertexData.indices;
  20506. if (indices) {
  20507. vertexData.indices = indices;
  20508. }
  20509. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20510. };
  20511. var importGeometry = function (parsedGeometry, mesh) {
  20512. var scene = mesh.getScene();
  20513. // Geometry
  20514. var geometryId = parsedGeometry.geometryId;
  20515. if (geometryId) {
  20516. var geometry = scene.getGeometryByID(geometryId);
  20517. if (geometry) {
  20518. geometry.applyToMesh(mesh);
  20519. }
  20520. }
  20521. else if (parsedGeometry instanceof ArrayBuffer) {
  20522. var binaryInfo = mesh._binaryInfo;
  20523. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20524. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20525. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20526. }
  20527. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20528. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20529. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20530. }
  20531. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20532. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20533. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20534. }
  20535. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20536. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20537. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20538. }
  20539. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20540. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20541. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20542. }
  20543. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20544. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20545. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20546. }
  20547. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20548. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20549. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20550. }
  20551. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20552. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20553. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20554. }
  20555. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20556. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20557. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20558. }
  20559. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20560. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20561. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20562. }
  20563. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20564. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20565. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20566. }
  20567. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20568. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20569. mesh.setIndices(indicesData);
  20570. }
  20571. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20572. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20573. mesh.subMeshes = [];
  20574. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20575. var materialIndex = subMeshesData[(i * 5) + 0];
  20576. var verticesStart = subMeshesData[(i * 5) + 1];
  20577. var verticesCount = subMeshesData[(i * 5) + 2];
  20578. var indexStart = subMeshesData[(i * 5) + 3];
  20579. var indexCount = subMeshesData[(i * 5) + 4];
  20580. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20581. }
  20582. }
  20583. }
  20584. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20585. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20586. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20587. if (parsedGeometry.uvs) {
  20588. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20589. }
  20590. if (parsedGeometry.uvs2) {
  20591. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20592. }
  20593. if (parsedGeometry.uvs3) {
  20594. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20595. }
  20596. if (parsedGeometry.uvs4) {
  20597. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20598. }
  20599. if (parsedGeometry.uvs5) {
  20600. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20601. }
  20602. if (parsedGeometry.uvs6) {
  20603. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20604. }
  20605. if (parsedGeometry.colors) {
  20606. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20607. }
  20608. if (parsedGeometry.matricesIndices) {
  20609. if (!parsedGeometry.matricesIndices._isExpanded) {
  20610. var floatIndices = [];
  20611. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20612. var matricesIndex = parsedGeometry.matricesIndices[i];
  20613. floatIndices.push(matricesIndex & 0x000000FF);
  20614. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20615. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20616. floatIndices.push(matricesIndex >> 24);
  20617. }
  20618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20619. }
  20620. else {
  20621. delete parsedGeometry.matricesIndices._isExpanded;
  20622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20623. }
  20624. }
  20625. if (parsedGeometry.matricesWeights) {
  20626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20627. }
  20628. mesh.setIndices(parsedGeometry.indices);
  20629. }
  20630. // SubMeshes
  20631. if (parsedGeometry.subMeshes) {
  20632. mesh.subMeshes = [];
  20633. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20634. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20635. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20636. }
  20637. }
  20638. // Flat shading
  20639. if (mesh._shouldGenerateFlatShading) {
  20640. mesh.convertToFlatShadedMesh();
  20641. delete mesh._shouldGenerateFlatShading;
  20642. }
  20643. // Update
  20644. mesh.computeWorldMatrix(true);
  20645. // Octree
  20646. if (scene._selectionOctree) {
  20647. scene._selectionOctree.addMesh(mesh);
  20648. }
  20649. };
  20650. BABYLON.SceneLoader.RegisterPlugin({
  20651. extensions: ".babylon",
  20652. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20653. var parsedData = JSON.parse(data);
  20654. var loadedSkeletonsIds = [];
  20655. var loadedMaterialsIds = [];
  20656. var hierarchyIds = [];
  20657. for (var index = 0; index < parsedData.meshes.length; index++) {
  20658. var parsedMesh = parsedData.meshes[index];
  20659. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20660. if (meshesNames instanceof Array) {
  20661. // Remove found mesh name from list.
  20662. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20663. }
  20664. //Geometry?
  20665. if (parsedMesh.geometryId) {
  20666. //does the file contain geometries?
  20667. if (parsedData.geometries) {
  20668. //find the correct geometry and add it to the scene
  20669. var found = false;
  20670. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20671. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20672. return;
  20673. }
  20674. else {
  20675. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20676. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20677. switch (geometryType) {
  20678. case "boxes":
  20679. parseBox(parsedGeometryData, scene);
  20680. break;
  20681. case "spheres":
  20682. parseSphere(parsedGeometryData, scene);
  20683. break;
  20684. case "cylinders":
  20685. parseCylinder(parsedGeometryData, scene);
  20686. break;
  20687. case "toruses":
  20688. parseTorus(parsedGeometryData, scene);
  20689. break;
  20690. case "grounds":
  20691. parseGround(parsedGeometryData, scene);
  20692. break;
  20693. case "planes":
  20694. parsePlane(parsedGeometryData, scene);
  20695. break;
  20696. case "torusKnots":
  20697. parseTorusKnot(parsedGeometryData, scene);
  20698. break;
  20699. case "vertexData":
  20700. parseVertexData(parsedGeometryData, scene, rootUrl);
  20701. break;
  20702. }
  20703. found = true;
  20704. }
  20705. });
  20706. }
  20707. });
  20708. if (!found) {
  20709. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20710. }
  20711. }
  20712. }
  20713. // Material ?
  20714. if (parsedMesh.materialId) {
  20715. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20716. if (!materialFound && parsedData.multiMaterials) {
  20717. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20718. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20719. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20720. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20721. var subMatId = parsedMultiMaterial.materials[matIndex];
  20722. loadedMaterialsIds.push(subMatId);
  20723. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20724. }
  20725. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20726. parseMultiMaterial(parsedMultiMaterial, scene);
  20727. materialFound = true;
  20728. break;
  20729. }
  20730. }
  20731. }
  20732. if (!materialFound) {
  20733. loadedMaterialsIds.push(parsedMesh.materialId);
  20734. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20735. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20736. }
  20737. }
  20738. }
  20739. // Skeleton ?
  20740. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20741. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20742. if (!skeletonAlreadyLoaded) {
  20743. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20744. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20745. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20746. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20747. loadedSkeletonsIds.push(parsedSkeleton.id);
  20748. }
  20749. }
  20750. }
  20751. }
  20752. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20753. meshes.push(mesh);
  20754. }
  20755. }
  20756. // Connecting parents
  20757. for (index = 0; index < scene.meshes.length; index++) {
  20758. var currentMesh = scene.meshes[index];
  20759. if (currentMesh._waitingParentId) {
  20760. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20761. currentMesh._waitingParentId = undefined;
  20762. }
  20763. }
  20764. // freeze world matrix application
  20765. for (index = 0; index < scene.meshes.length; index++) {
  20766. var currentMesh = scene.meshes[index];
  20767. if (currentMesh._waitingFreezeWorldMatrix) {
  20768. currentMesh.freezeWorldMatrix();
  20769. currentMesh._waitingFreezeWorldMatrix = undefined;
  20770. }
  20771. }
  20772. // Particles
  20773. if (parsedData.particleSystems) {
  20774. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20775. var parsedParticleSystem = parsedData.particleSystems[index];
  20776. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20777. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20778. }
  20779. }
  20780. }
  20781. return true;
  20782. },
  20783. load: function (scene, data, rootUrl) {
  20784. var parsedData = JSON.parse(data);
  20785. // Scene
  20786. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20787. scene.autoClear = parsedData.autoClear;
  20788. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20789. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20790. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20791. // Fog
  20792. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20793. scene.fogMode = parsedData.fogMode;
  20794. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20795. scene.fogStart = parsedData.fogStart;
  20796. scene.fogEnd = parsedData.fogEnd;
  20797. scene.fogDensity = parsedData.fogDensity;
  20798. }
  20799. // Lights
  20800. for (var index = 0; index < parsedData.lights.length; index++) {
  20801. var parsedLight = parsedData.lights[index];
  20802. parseLight(parsedLight, scene);
  20803. }
  20804. // Materials
  20805. if (parsedData.materials) {
  20806. for (index = 0; index < parsedData.materials.length; index++) {
  20807. var parsedMaterial = parsedData.materials[index];
  20808. parseMaterial(parsedMaterial, scene, rootUrl);
  20809. }
  20810. }
  20811. if (parsedData.multiMaterials) {
  20812. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20813. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20814. parseMultiMaterial(parsedMultiMaterial, scene);
  20815. }
  20816. }
  20817. // Skeletons
  20818. if (parsedData.skeletons) {
  20819. for (index = 0; index < parsedData.skeletons.length; index++) {
  20820. var parsedSkeleton = parsedData.skeletons[index];
  20821. parseSkeleton(parsedSkeleton, scene);
  20822. }
  20823. }
  20824. // Geometries
  20825. var geometries = parsedData.geometries;
  20826. if (geometries) {
  20827. // Boxes
  20828. var boxes = geometries.boxes;
  20829. if (boxes) {
  20830. for (index = 0; index < boxes.length; index++) {
  20831. var parsedBox = boxes[index];
  20832. parseBox(parsedBox, scene);
  20833. }
  20834. }
  20835. // Spheres
  20836. var spheres = geometries.spheres;
  20837. if (spheres) {
  20838. for (index = 0; index < spheres.length; index++) {
  20839. var parsedSphere = spheres[index];
  20840. parseSphere(parsedSphere, scene);
  20841. }
  20842. }
  20843. // Cylinders
  20844. var cylinders = geometries.cylinders;
  20845. if (cylinders) {
  20846. for (index = 0; index < cylinders.length; index++) {
  20847. var parsedCylinder = cylinders[index];
  20848. parseCylinder(parsedCylinder, scene);
  20849. }
  20850. }
  20851. // Toruses
  20852. var toruses = geometries.toruses;
  20853. if (toruses) {
  20854. for (index = 0; index < toruses.length; index++) {
  20855. var parsedTorus = toruses[index];
  20856. parseTorus(parsedTorus, scene);
  20857. }
  20858. }
  20859. // Grounds
  20860. var grounds = geometries.grounds;
  20861. if (grounds) {
  20862. for (index = 0; index < grounds.length; index++) {
  20863. var parsedGround = grounds[index];
  20864. parseGround(parsedGround, scene);
  20865. }
  20866. }
  20867. // Planes
  20868. var planes = geometries.planes;
  20869. if (planes) {
  20870. for (index = 0; index < planes.length; index++) {
  20871. var parsedPlane = planes[index];
  20872. parsePlane(parsedPlane, scene);
  20873. }
  20874. }
  20875. // TorusKnots
  20876. var torusKnots = geometries.torusKnots;
  20877. if (torusKnots) {
  20878. for (index = 0; index < torusKnots.length; index++) {
  20879. var parsedTorusKnot = torusKnots[index];
  20880. parseTorusKnot(parsedTorusKnot, scene);
  20881. }
  20882. }
  20883. // VertexData
  20884. var vertexData = geometries.vertexData;
  20885. if (vertexData) {
  20886. for (index = 0; index < vertexData.length; index++) {
  20887. var parsedVertexData = vertexData[index];
  20888. parseVertexData(parsedVertexData, scene, rootUrl);
  20889. }
  20890. }
  20891. }
  20892. // Meshes
  20893. for (index = 0; index < parsedData.meshes.length; index++) {
  20894. var parsedMesh = parsedData.meshes[index];
  20895. parseMesh(parsedMesh, scene, rootUrl);
  20896. }
  20897. // Cameras
  20898. for (index = 0; index < parsedData.cameras.length; index++) {
  20899. var parsedCamera = parsedData.cameras[index];
  20900. parseCamera(parsedCamera, scene);
  20901. }
  20902. if (parsedData.activeCameraID) {
  20903. scene.setActiveCameraByID(parsedData.activeCameraID);
  20904. }
  20905. // Browsing all the graph to connect the dots
  20906. for (index = 0; index < scene.cameras.length; index++) {
  20907. var camera = scene.cameras[index];
  20908. if (camera._waitingParentId) {
  20909. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20910. camera._waitingParentId = undefined;
  20911. }
  20912. }
  20913. for (index = 0; index < scene.lights.length; index++) {
  20914. var light = scene.lights[index];
  20915. if (light._waitingParentId) {
  20916. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20917. light._waitingParentId = undefined;
  20918. }
  20919. }
  20920. // Sounds
  20921. if (parsedData.sounds) {
  20922. for (index = 0; index < parsedData.sounds.length; index++) {
  20923. var parsedSound = parsedData.sounds[index];
  20924. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20925. parseSound(parsedSound, scene, rootUrl);
  20926. }
  20927. else {
  20928. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20929. }
  20930. }
  20931. }
  20932. // Connect parents & children and parse actions
  20933. for (index = 0; index < scene.meshes.length; index++) {
  20934. var mesh = scene.meshes[index];
  20935. if (mesh._waitingParentId) {
  20936. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20937. mesh._waitingParentId = undefined;
  20938. }
  20939. if (mesh._waitingActions) {
  20940. parseActions(mesh._waitingActions, mesh, scene);
  20941. mesh._waitingActions = undefined;
  20942. }
  20943. }
  20944. // freeze world matrix application
  20945. for (index = 0; index < scene.meshes.length; index++) {
  20946. var currentMesh = scene.meshes[index];
  20947. if (currentMesh._waitingFreezeWorldMatrix) {
  20948. currentMesh.freezeWorldMatrix();
  20949. currentMesh._waitingFreezeWorldMatrix = undefined;
  20950. }
  20951. }
  20952. // Particles Systems
  20953. if (parsedData.particleSystems) {
  20954. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20955. var parsedParticleSystem = parsedData.particleSystems[index];
  20956. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20957. }
  20958. }
  20959. // Lens flares
  20960. if (parsedData.lensFlareSystems) {
  20961. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20962. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20963. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20964. }
  20965. }
  20966. // Shadows
  20967. if (parsedData.shadowGenerators) {
  20968. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20969. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20970. parseShadowGenerator(parsedShadowGenerator, scene);
  20971. }
  20972. }
  20973. // Actions (scene)
  20974. if (parsedData.actions) {
  20975. parseActions(parsedData.actions, null, scene);
  20976. }
  20977. // Finish
  20978. return true;
  20979. }
  20980. });
  20981. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20982. })(BABYLON || (BABYLON = {}));
  20983. var BABYLON;
  20984. (function (BABYLON) {
  20985. var SpriteManager = (function () {
  20986. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20988. this.name = name;
  20989. this.cellSize = cellSize;
  20990. this.sprites = new Array();
  20991. this.renderingGroupId = 0;
  20992. this.layerMask = 0x0FFFFFFF;
  20993. this.fogEnabled = true;
  20994. this._vertexDeclaration = [4, 4, 4, 4];
  20995. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20996. this._capacity = capacity;
  20997. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20998. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20999. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21000. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21001. this._scene = scene;
  21002. this._scene.spriteManagers.push(this);
  21003. // VBO
  21004. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21005. var indices = [];
  21006. var index = 0;
  21007. for (var count = 0; count < capacity; count++) {
  21008. indices.push(index);
  21009. indices.push(index + 1);
  21010. indices.push(index + 2);
  21011. indices.push(index);
  21012. indices.push(index + 2);
  21013. indices.push(index + 3);
  21014. index += 4;
  21015. }
  21016. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21017. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21018. // Effects
  21019. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21020. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21021. }
  21022. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21023. var arrayOffset = index * 16;
  21024. if (offsetX === 0)
  21025. offsetX = this._epsilon;
  21026. else if (offsetX === 1)
  21027. offsetX = 1 - this._epsilon;
  21028. if (offsetY === 0)
  21029. offsetY = this._epsilon;
  21030. else if (offsetY === 1)
  21031. offsetY = 1 - this._epsilon;
  21032. this._vertices[arrayOffset] = sprite.position.x;
  21033. this._vertices[arrayOffset + 1] = sprite.position.y;
  21034. this._vertices[arrayOffset + 2] = sprite.position.z;
  21035. this._vertices[arrayOffset + 3] = sprite.angle;
  21036. this._vertices[arrayOffset + 4] = sprite.width;
  21037. this._vertices[arrayOffset + 5] = sprite.height;
  21038. this._vertices[arrayOffset + 6] = offsetX;
  21039. this._vertices[arrayOffset + 7] = offsetY;
  21040. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21041. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21042. var offset = (sprite.cellIndex / rowSize) >> 0;
  21043. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21044. this._vertices[arrayOffset + 11] = offset;
  21045. // Color
  21046. this._vertices[arrayOffset + 12] = sprite.color.r;
  21047. this._vertices[arrayOffset + 13] = sprite.color.g;
  21048. this._vertices[arrayOffset + 14] = sprite.color.b;
  21049. this._vertices[arrayOffset + 15] = sprite.color.a;
  21050. };
  21051. SpriteManager.prototype.render = function () {
  21052. // Check
  21053. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21054. return;
  21055. var engine = this._scene.getEngine();
  21056. var baseSize = this._spriteTexture.getBaseSize();
  21057. // Sprites
  21058. var deltaTime = engine.getDeltaTime();
  21059. var max = Math.min(this._capacity, this.sprites.length);
  21060. var rowSize = baseSize.width / this.cellSize;
  21061. var offset = 0;
  21062. for (var index = 0; index < max; index++) {
  21063. var sprite = this.sprites[index];
  21064. if (!sprite) {
  21065. continue;
  21066. }
  21067. sprite._animate(deltaTime);
  21068. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21069. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21070. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21071. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21072. }
  21073. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21074. // Render
  21075. var effect = this._effectBase;
  21076. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21077. effect = this._effectFog;
  21078. }
  21079. engine.enableEffect(effect);
  21080. var viewMatrix = this._scene.getViewMatrix();
  21081. effect.setTexture("diffuseSampler", this._spriteTexture);
  21082. effect.setMatrix("view", viewMatrix);
  21083. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21084. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21085. // Fog
  21086. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21087. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21088. effect.setColor3("vFogColor", this._scene.fogColor);
  21089. }
  21090. // VBOs
  21091. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21092. // Draw order
  21093. engine.setDepthFunctionToLessOrEqual();
  21094. effect.setBool("alphaTest", true);
  21095. engine.setColorWrite(false);
  21096. engine.draw(true, 0, max * 6);
  21097. engine.setColorWrite(true);
  21098. effect.setBool("alphaTest", false);
  21099. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21100. engine.draw(true, 0, max * 6);
  21101. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21102. };
  21103. SpriteManager.prototype.dispose = function () {
  21104. if (this._vertexBuffer) {
  21105. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21106. this._vertexBuffer = null;
  21107. }
  21108. if (this._indexBuffer) {
  21109. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21110. this._indexBuffer = null;
  21111. }
  21112. if (this._spriteTexture) {
  21113. this._spriteTexture.dispose();
  21114. this._spriteTexture = null;
  21115. }
  21116. // Remove from scene
  21117. var index = this._scene.spriteManagers.indexOf(this);
  21118. this._scene.spriteManagers.splice(index, 1);
  21119. // Callback
  21120. if (this.onDispose) {
  21121. this.onDispose();
  21122. }
  21123. };
  21124. return SpriteManager;
  21125. })();
  21126. BABYLON.SpriteManager = SpriteManager;
  21127. })(BABYLON || (BABYLON = {}));
  21128. var BABYLON;
  21129. (function (BABYLON) {
  21130. var Sprite = (function () {
  21131. function Sprite(name, manager) {
  21132. this.name = name;
  21133. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21134. this.width = 1.0;
  21135. this.height = 1.0;
  21136. this.angle = 0;
  21137. this.cellIndex = 0;
  21138. this.invertU = 0;
  21139. this.invertV = 0;
  21140. this.animations = new Array();
  21141. this._animationStarted = false;
  21142. this._loopAnimation = false;
  21143. this._fromIndex = 0;
  21144. this._toIndex = 0;
  21145. this._delay = 0;
  21146. this._direction = 1;
  21147. this._frameCount = 0;
  21148. this._time = 0;
  21149. this._manager = manager;
  21150. this._manager.sprites.push(this);
  21151. this.position = BABYLON.Vector3.Zero();
  21152. }
  21153. Object.defineProperty(Sprite.prototype, "size", {
  21154. get: function () {
  21155. return this.width;
  21156. },
  21157. set: function (value) {
  21158. this.width = value;
  21159. this.height = value;
  21160. },
  21161. enumerable: true,
  21162. configurable: true
  21163. });
  21164. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21165. this._fromIndex = from;
  21166. this._toIndex = to;
  21167. this._loopAnimation = loop;
  21168. this._delay = delay;
  21169. this._animationStarted = true;
  21170. this._direction = from < to ? 1 : -1;
  21171. this.cellIndex = from;
  21172. this._time = 0;
  21173. };
  21174. Sprite.prototype.stopAnimation = function () {
  21175. this._animationStarted = false;
  21176. };
  21177. Sprite.prototype._animate = function (deltaTime) {
  21178. if (!this._animationStarted)
  21179. return;
  21180. this._time += deltaTime;
  21181. if (this._time > this._delay) {
  21182. this._time = this._time % this._delay;
  21183. this.cellIndex += this._direction;
  21184. if (this.cellIndex == this._toIndex) {
  21185. if (this._loopAnimation) {
  21186. this.cellIndex = this._fromIndex;
  21187. }
  21188. else {
  21189. this._animationStarted = false;
  21190. if (this.disposeWhenFinishedAnimating) {
  21191. this.dispose();
  21192. }
  21193. }
  21194. }
  21195. }
  21196. };
  21197. Sprite.prototype.dispose = function () {
  21198. for (var i = 0; i < this._manager.sprites.length; i++) {
  21199. if (this._manager.sprites[i] == this) {
  21200. this._manager.sprites.splice(i, 1);
  21201. }
  21202. }
  21203. };
  21204. return Sprite;
  21205. })();
  21206. BABYLON.Sprite = Sprite;
  21207. })(BABYLON || (BABYLON = {}));
  21208. var BABYLON;
  21209. (function (BABYLON) {
  21210. var Layer = (function () {
  21211. function Layer(name, imgUrl, scene, isBackground, color) {
  21212. this.name = name;
  21213. this._vertexDeclaration = [2];
  21214. this._vertexStrideSize = 2 * 4;
  21215. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21216. this.isBackground = isBackground === undefined ? true : isBackground;
  21217. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21218. this._scene = scene;
  21219. this._scene.layers.push(this);
  21220. // VBO
  21221. var vertices = [];
  21222. vertices.push(1, 1);
  21223. vertices.push(-1, 1);
  21224. vertices.push(-1, -1);
  21225. vertices.push(1, -1);
  21226. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21227. // Indices
  21228. var indices = [];
  21229. indices.push(0);
  21230. indices.push(1);
  21231. indices.push(2);
  21232. indices.push(0);
  21233. indices.push(2);
  21234. indices.push(3);
  21235. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21236. // Effects
  21237. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21238. }
  21239. Layer.prototype.render = function () {
  21240. // Check
  21241. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21242. return;
  21243. var engine = this._scene.getEngine();
  21244. // Render
  21245. engine.enableEffect(this._effect);
  21246. engine.setState(false);
  21247. // Texture
  21248. this._effect.setTexture("textureSampler", this.texture);
  21249. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21250. // Color
  21251. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21252. // VBOs
  21253. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21254. // Draw order
  21255. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21256. engine.draw(true, 0, 6);
  21257. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21258. };
  21259. Layer.prototype.dispose = function () {
  21260. if (this._vertexBuffer) {
  21261. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21262. this._vertexBuffer = null;
  21263. }
  21264. if (this._indexBuffer) {
  21265. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21266. this._indexBuffer = null;
  21267. }
  21268. if (this.texture) {
  21269. this.texture.dispose();
  21270. this.texture = null;
  21271. }
  21272. // Remove from scene
  21273. var index = this._scene.layers.indexOf(this);
  21274. this._scene.layers.splice(index, 1);
  21275. // Callback
  21276. if (this.onDispose) {
  21277. this.onDispose();
  21278. }
  21279. };
  21280. return Layer;
  21281. })();
  21282. BABYLON.Layer = Layer;
  21283. })(BABYLON || (BABYLON = {}));
  21284. var BABYLON;
  21285. (function (BABYLON) {
  21286. var Particle = (function () {
  21287. function Particle() {
  21288. this.position = BABYLON.Vector3.Zero();
  21289. this.direction = BABYLON.Vector3.Zero();
  21290. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21291. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21292. this.lifeTime = 1.0;
  21293. this.age = 0;
  21294. this.size = 0;
  21295. this.angle = 0;
  21296. this.angularSpeed = 0;
  21297. }
  21298. Particle.prototype.copyTo = function (other) {
  21299. other.position.copyFrom(this.position);
  21300. other.direction.copyFrom(this.direction);
  21301. other.color.copyFrom(this.color);
  21302. other.colorStep.copyFrom(this.colorStep);
  21303. other.lifeTime = this.lifeTime;
  21304. other.age = this.age;
  21305. other.size = this.size;
  21306. other.angle = this.angle;
  21307. other.angularSpeed = this.angularSpeed;
  21308. };
  21309. return Particle;
  21310. })();
  21311. BABYLON.Particle = Particle;
  21312. })(BABYLON || (BABYLON = {}));
  21313. var BABYLON;
  21314. (function (BABYLON) {
  21315. var randomNumber = function (min, max) {
  21316. if (min === max) {
  21317. return (min);
  21318. }
  21319. var random = Math.random();
  21320. return ((random * (max - min)) + min);
  21321. };
  21322. var ParticleSystem = (function () {
  21323. function ParticleSystem(name, capacity, scene, customEffect) {
  21324. var _this = this;
  21325. this.name = name;
  21326. this.renderingGroupId = 0;
  21327. this.emitter = null;
  21328. this.emitRate = 10;
  21329. this.manualEmitCount = -1;
  21330. this.updateSpeed = 0.01;
  21331. this.targetStopDuration = 0;
  21332. this.disposeOnStop = false;
  21333. this.minEmitPower = 1;
  21334. this.maxEmitPower = 1;
  21335. this.minLifeTime = 1;
  21336. this.maxLifeTime = 1;
  21337. this.minSize = 1;
  21338. this.maxSize = 1;
  21339. this.minAngularSpeed = 0;
  21340. this.maxAngularSpeed = 0;
  21341. this.layerMask = 0x0FFFFFFF;
  21342. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21343. this.forceDepthWrite = false;
  21344. this.gravity = BABYLON.Vector3.Zero();
  21345. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21346. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21347. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21348. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21349. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21350. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21351. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21352. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21353. this.particles = new Array();
  21354. this._vertexDeclaration = [3, 4, 4];
  21355. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21356. this._stockParticles = new Array();
  21357. this._newPartsExcess = 0;
  21358. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21359. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21360. this._scaledDirection = BABYLON.Vector3.Zero();
  21361. this._scaledGravity = BABYLON.Vector3.Zero();
  21362. this._currentRenderId = -1;
  21363. this._started = false;
  21364. this._stopped = false;
  21365. this._actualFrame = 0;
  21366. this.id = name;
  21367. this._capacity = capacity;
  21368. this._scene = scene;
  21369. this._customEffect = customEffect;
  21370. scene.particleSystems.push(this);
  21371. // VBO
  21372. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21373. var indices = [];
  21374. var index = 0;
  21375. for (var count = 0; count < capacity; count++) {
  21376. indices.push(index);
  21377. indices.push(index + 1);
  21378. indices.push(index + 2);
  21379. indices.push(index);
  21380. indices.push(index + 2);
  21381. indices.push(index + 3);
  21382. index += 4;
  21383. }
  21384. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21385. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21386. // Default behaviors
  21387. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21388. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21389. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21390. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21391. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21392. };
  21393. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21394. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21395. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21396. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21397. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21398. };
  21399. this.updateFunction = function (particles) {
  21400. for (var index = 0; index < particles.length; index++) {
  21401. var particle = particles[index];
  21402. particle.age += _this._scaledUpdateSpeed;
  21403. if (particle.age >= particle.lifeTime) {
  21404. _this.recycleParticle(particle);
  21405. index--;
  21406. continue;
  21407. }
  21408. else {
  21409. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21410. particle.color.addInPlace(_this._scaledColorStep);
  21411. if (particle.color.a < 0)
  21412. particle.color.a = 0;
  21413. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21414. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21415. particle.position.addInPlace(_this._scaledDirection);
  21416. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21417. particle.direction.addInPlace(_this._scaledGravity);
  21418. }
  21419. }
  21420. };
  21421. }
  21422. ParticleSystem.prototype.recycleParticle = function (particle) {
  21423. var lastParticle = this.particles.pop();
  21424. if (lastParticle !== particle) {
  21425. lastParticle.copyTo(particle);
  21426. this._stockParticles.push(lastParticle);
  21427. }
  21428. };
  21429. ParticleSystem.prototype.getCapacity = function () {
  21430. return this._capacity;
  21431. };
  21432. ParticleSystem.prototype.isAlive = function () {
  21433. return this._alive;
  21434. };
  21435. ParticleSystem.prototype.isStarted = function () {
  21436. return this._started;
  21437. };
  21438. ParticleSystem.prototype.start = function () {
  21439. this._started = true;
  21440. this._stopped = false;
  21441. this._actualFrame = 0;
  21442. };
  21443. ParticleSystem.prototype.stop = function () {
  21444. this._stopped = true;
  21445. };
  21446. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21447. var offset = index * 11;
  21448. this._vertices[offset] = particle.position.x;
  21449. this._vertices[offset + 1] = particle.position.y;
  21450. this._vertices[offset + 2] = particle.position.z;
  21451. this._vertices[offset + 3] = particle.color.r;
  21452. this._vertices[offset + 4] = particle.color.g;
  21453. this._vertices[offset + 5] = particle.color.b;
  21454. this._vertices[offset + 6] = particle.color.a;
  21455. this._vertices[offset + 7] = particle.angle;
  21456. this._vertices[offset + 8] = particle.size;
  21457. this._vertices[offset + 9] = offsetX;
  21458. this._vertices[offset + 10] = offsetY;
  21459. };
  21460. ParticleSystem.prototype._update = function (newParticles) {
  21461. // Update current
  21462. this._alive = this.particles.length > 0;
  21463. this.updateFunction(this.particles);
  21464. // Add new ones
  21465. var worldMatrix;
  21466. if (this.emitter.position) {
  21467. worldMatrix = this.emitter.getWorldMatrix();
  21468. }
  21469. else {
  21470. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21471. }
  21472. for (var index = 0; index < newParticles; index++) {
  21473. if (this.particles.length === this._capacity) {
  21474. break;
  21475. }
  21476. if (this._stockParticles.length !== 0) {
  21477. var particle = this._stockParticles.pop();
  21478. particle.age = 0;
  21479. }
  21480. else {
  21481. particle = new BABYLON.Particle();
  21482. }
  21483. this.particles.push(particle);
  21484. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21485. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21486. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21487. particle.size = randomNumber(this.minSize, this.maxSize);
  21488. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21489. this.startPositionFunction(worldMatrix, particle.position);
  21490. var step = randomNumber(0, 1.0);
  21491. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21492. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21493. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21494. }
  21495. };
  21496. ParticleSystem.prototype._getEffect = function () {
  21497. if (this._customEffect) {
  21498. return this._customEffect;
  21499. }
  21500. ;
  21501. var defines = [];
  21502. if (this._scene.clipPlane) {
  21503. defines.push("#define CLIPPLANE");
  21504. }
  21505. // Effect
  21506. var join = defines.join("\n");
  21507. if (this._cachedDefines !== join) {
  21508. this._cachedDefines = join;
  21509. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21510. }
  21511. return this._effect;
  21512. };
  21513. ParticleSystem.prototype.animate = function () {
  21514. if (!this._started)
  21515. return;
  21516. var effect = this._getEffect();
  21517. // Check
  21518. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21519. return;
  21520. if (this._currentRenderId === this._scene.getRenderId()) {
  21521. return;
  21522. }
  21523. this._currentRenderId = this._scene.getRenderId();
  21524. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21525. // determine the number of particles we need to create
  21526. var emitCout;
  21527. if (this.manualEmitCount > -1) {
  21528. emitCout = this.manualEmitCount;
  21529. this.manualEmitCount = 0;
  21530. }
  21531. else {
  21532. emitCout = this.emitRate;
  21533. }
  21534. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21535. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21536. if (this._newPartsExcess > 1.0) {
  21537. newParticles += this._newPartsExcess >> 0;
  21538. this._newPartsExcess -= this._newPartsExcess >> 0;
  21539. }
  21540. this._alive = false;
  21541. if (!this._stopped) {
  21542. this._actualFrame += this._scaledUpdateSpeed;
  21543. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21544. this.stop();
  21545. }
  21546. else {
  21547. newParticles = 0;
  21548. }
  21549. this._update(newParticles);
  21550. // Stopped?
  21551. if (this._stopped) {
  21552. if (!this._alive) {
  21553. this._started = false;
  21554. if (this.disposeOnStop) {
  21555. this._scene._toBeDisposed.push(this);
  21556. }
  21557. }
  21558. }
  21559. // Update VBO
  21560. var offset = 0;
  21561. for (var index = 0; index < this.particles.length; index++) {
  21562. var particle = this.particles[index];
  21563. this._appendParticleVertex(offset++, particle, 0, 0);
  21564. this._appendParticleVertex(offset++, particle, 1, 0);
  21565. this._appendParticleVertex(offset++, particle, 1, 1);
  21566. this._appendParticleVertex(offset++, particle, 0, 1);
  21567. }
  21568. var engine = this._scene.getEngine();
  21569. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21570. };
  21571. ParticleSystem.prototype.render = function () {
  21572. var effect = this._getEffect();
  21573. // Check
  21574. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21575. return 0;
  21576. var engine = this._scene.getEngine();
  21577. // Render
  21578. engine.enableEffect(effect);
  21579. engine.setState(false);
  21580. var viewMatrix = this._scene.getViewMatrix();
  21581. effect.setTexture("diffuseSampler", this.particleTexture);
  21582. effect.setMatrix("view", viewMatrix);
  21583. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21584. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21585. if (this._scene.clipPlane) {
  21586. var clipPlane = this._scene.clipPlane;
  21587. var invView = viewMatrix.clone();
  21588. invView.invert();
  21589. effect.setMatrix("invView", invView);
  21590. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21591. }
  21592. // VBOs
  21593. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21594. // Draw order
  21595. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21596. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21597. }
  21598. else {
  21599. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21600. }
  21601. if (this.forceDepthWrite) {
  21602. engine.setDepthWrite(true);
  21603. }
  21604. engine.draw(true, 0, this.particles.length * 6);
  21605. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21606. return this.particles.length;
  21607. };
  21608. ParticleSystem.prototype.dispose = function () {
  21609. if (this._vertexBuffer) {
  21610. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21611. this._vertexBuffer = null;
  21612. }
  21613. if (this._indexBuffer) {
  21614. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21615. this._indexBuffer = null;
  21616. }
  21617. if (this.particleTexture) {
  21618. this.particleTexture.dispose();
  21619. this.particleTexture = null;
  21620. }
  21621. // Remove from scene
  21622. var index = this._scene.particleSystems.indexOf(this);
  21623. this._scene.particleSystems.splice(index, 1);
  21624. // Callback
  21625. if (this.onDispose) {
  21626. this.onDispose();
  21627. }
  21628. };
  21629. // Clone
  21630. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21631. var result = new ParticleSystem(name, this._capacity, this._scene);
  21632. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21633. if (newEmitter === undefined) {
  21634. newEmitter = this.emitter;
  21635. }
  21636. result.emitter = newEmitter;
  21637. if (this.particleTexture) {
  21638. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21639. }
  21640. result.start();
  21641. return result;
  21642. };
  21643. // Statics
  21644. ParticleSystem.BLENDMODE_ONEONE = 0;
  21645. ParticleSystem.BLENDMODE_STANDARD = 1;
  21646. return ParticleSystem;
  21647. })();
  21648. BABYLON.ParticleSystem = ParticleSystem;
  21649. })(BABYLON || (BABYLON = {}));
  21650. var BABYLON;
  21651. (function (BABYLON) {
  21652. var Animation = (function () {
  21653. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21654. this.name = name;
  21655. this.targetProperty = targetProperty;
  21656. this.framePerSecond = framePerSecond;
  21657. this.dataType = dataType;
  21658. this.loopMode = loopMode;
  21659. this._offsetsCache = {};
  21660. this._highLimitsCache = {};
  21661. this._stopped = false;
  21662. this.allowMatricesInterpolation = false;
  21663. this.targetPropertyPath = targetProperty.split(".");
  21664. this.dataType = dataType;
  21665. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21666. }
  21667. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21668. var dataType = undefined;
  21669. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21670. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21671. }
  21672. else if (from instanceof BABYLON.Quaternion) {
  21673. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21674. }
  21675. else if (from instanceof BABYLON.Vector3) {
  21676. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21677. }
  21678. else if (from instanceof BABYLON.Vector2) {
  21679. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21680. }
  21681. else if (from instanceof BABYLON.Color3) {
  21682. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21683. }
  21684. if (dataType == undefined) {
  21685. return null;
  21686. }
  21687. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21688. var keys = [];
  21689. keys.push({ frame: 0, value: from });
  21690. keys.push({ frame: totalFrame, value: to });
  21691. animation.setKeys(keys);
  21692. if (easingFunction !== undefined) {
  21693. animation.setEasingFunction(easingFunction);
  21694. }
  21695. mesh.animations.push(animation);
  21696. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21697. };
  21698. // Methods
  21699. Animation.prototype.reset = function () {
  21700. this._offsetsCache = {};
  21701. this._highLimitsCache = {};
  21702. this.currentFrame = 0;
  21703. };
  21704. Animation.prototype.isStopped = function () {
  21705. return this._stopped;
  21706. };
  21707. Animation.prototype.getKeys = function () {
  21708. return this._keys;
  21709. };
  21710. Animation.prototype.getEasingFunction = function () {
  21711. return this._easingFunction;
  21712. };
  21713. Animation.prototype.setEasingFunction = function (easingFunction) {
  21714. this._easingFunction = easingFunction;
  21715. };
  21716. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21717. return startValue + (endValue - startValue) * gradient;
  21718. };
  21719. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21720. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21721. };
  21722. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21723. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21724. };
  21725. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21726. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21727. };
  21728. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21729. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21730. };
  21731. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21732. var startScale = new BABYLON.Vector3(0, 0, 0);
  21733. var startRotation = new BABYLON.Quaternion();
  21734. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21735. startValue.decompose(startScale, startRotation, startTranslation);
  21736. var endScale = new BABYLON.Vector3(0, 0, 0);
  21737. var endRotation = new BABYLON.Quaternion();
  21738. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21739. endValue.decompose(endScale, endRotation, endTranslation);
  21740. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21741. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21742. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21743. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21744. return result;
  21745. };
  21746. Animation.prototype.clone = function () {
  21747. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21748. clone.setKeys(this._keys);
  21749. return clone;
  21750. };
  21751. Animation.prototype.setKeys = function (values) {
  21752. this._keys = values.slice(0);
  21753. this._offsetsCache = {};
  21754. this._highLimitsCache = {};
  21755. };
  21756. Animation.prototype._getKeyValue = function (value) {
  21757. if (typeof value === "function") {
  21758. return value();
  21759. }
  21760. return value;
  21761. };
  21762. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21763. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21764. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21765. }
  21766. this.currentFrame = currentFrame;
  21767. // Try to get a hash to find the right key
  21768. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  21769. if (this._keys[startKey].frame >= currentFrame) {
  21770. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21771. startKey--;
  21772. }
  21773. }
  21774. for (var key = startKey; key < this._keys.length; key++) {
  21775. if (this._keys[key + 1].frame >= currentFrame) {
  21776. var startValue = this._getKeyValue(this._keys[key].value);
  21777. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21778. // gradient : percent of currentFrame between the frame inf and the frame sup
  21779. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21780. // check for easingFunction and correction of gradient
  21781. if (this._easingFunction != null) {
  21782. gradient = this._easingFunction.ease(gradient);
  21783. }
  21784. switch (this.dataType) {
  21785. // Float
  21786. case Animation.ANIMATIONTYPE_FLOAT:
  21787. switch (loopMode) {
  21788. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21789. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21790. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21791. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21792. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21793. }
  21794. break;
  21795. // Quaternion
  21796. case Animation.ANIMATIONTYPE_QUATERNION:
  21797. var quaternion = null;
  21798. switch (loopMode) {
  21799. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21800. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21801. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21802. break;
  21803. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21804. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21805. break;
  21806. }
  21807. return quaternion;
  21808. // Vector3
  21809. case Animation.ANIMATIONTYPE_VECTOR3:
  21810. switch (loopMode) {
  21811. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21812. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21813. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21814. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21815. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21816. }
  21817. // Vector2
  21818. case Animation.ANIMATIONTYPE_VECTOR2:
  21819. switch (loopMode) {
  21820. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21821. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21822. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21823. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21824. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21825. }
  21826. // Color3
  21827. case Animation.ANIMATIONTYPE_COLOR3:
  21828. switch (loopMode) {
  21829. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21830. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21831. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21832. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21833. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21834. }
  21835. // Matrix
  21836. case Animation.ANIMATIONTYPE_MATRIX:
  21837. switch (loopMode) {
  21838. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21839. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21840. if (this.allowMatricesInterpolation) {
  21841. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21842. }
  21843. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21844. return startValue;
  21845. }
  21846. default:
  21847. break;
  21848. }
  21849. break;
  21850. }
  21851. }
  21852. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21853. };
  21854. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21855. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21856. this._stopped = true;
  21857. return false;
  21858. }
  21859. var returnValue = true;
  21860. // Adding a start key at frame 0 if missing
  21861. if (this._keys[0].frame !== 0) {
  21862. var newKey = { frame: 0, value: this._keys[0].value };
  21863. this._keys.splice(0, 0, newKey);
  21864. }
  21865. // Check limits
  21866. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21867. from = this._keys[0].frame;
  21868. }
  21869. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21870. to = this._keys[this._keys.length - 1].frame;
  21871. }
  21872. // Compute ratio
  21873. var range = to - from;
  21874. var offsetValue;
  21875. // ratio represents the frame delta between from and to
  21876. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21877. var highLimitValue = 0;
  21878. if (ratio > range && !loop) {
  21879. returnValue = false;
  21880. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21881. }
  21882. else {
  21883. // Get max value if required
  21884. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21885. var keyOffset = to.toString() + from.toString();
  21886. if (!this._offsetsCache[keyOffset]) {
  21887. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21888. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21889. switch (this.dataType) {
  21890. // Float
  21891. case Animation.ANIMATIONTYPE_FLOAT:
  21892. this._offsetsCache[keyOffset] = toValue - fromValue;
  21893. break;
  21894. // Quaternion
  21895. case Animation.ANIMATIONTYPE_QUATERNION:
  21896. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21897. break;
  21898. // Vector3
  21899. case Animation.ANIMATIONTYPE_VECTOR3:
  21900. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21901. // Vector2
  21902. case Animation.ANIMATIONTYPE_VECTOR2:
  21903. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21904. // Color3
  21905. case Animation.ANIMATIONTYPE_COLOR3:
  21906. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21907. default:
  21908. break;
  21909. }
  21910. this._highLimitsCache[keyOffset] = toValue;
  21911. }
  21912. highLimitValue = this._highLimitsCache[keyOffset];
  21913. offsetValue = this._offsetsCache[keyOffset];
  21914. }
  21915. }
  21916. if (offsetValue === undefined) {
  21917. switch (this.dataType) {
  21918. // Float
  21919. case Animation.ANIMATIONTYPE_FLOAT:
  21920. offsetValue = 0;
  21921. break;
  21922. // Quaternion
  21923. case Animation.ANIMATIONTYPE_QUATERNION:
  21924. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21925. break;
  21926. // Vector3
  21927. case Animation.ANIMATIONTYPE_VECTOR3:
  21928. offsetValue = BABYLON.Vector3.Zero();
  21929. break;
  21930. // Vector2
  21931. case Animation.ANIMATIONTYPE_VECTOR2:
  21932. offsetValue = BABYLON.Vector2.Zero();
  21933. break;
  21934. // Color3
  21935. case Animation.ANIMATIONTYPE_COLOR3:
  21936. offsetValue = BABYLON.Color3.Black();
  21937. }
  21938. }
  21939. // Compute value
  21940. var repeatCount = (ratio / range) >> 0;
  21941. var currentFrame = returnValue ? from + ratio % range : to;
  21942. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21943. // Set value
  21944. if (this.targetPropertyPath.length > 1) {
  21945. var property = this._target[this.targetPropertyPath[0]];
  21946. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21947. property = property[this.targetPropertyPath[index]];
  21948. }
  21949. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21950. }
  21951. else {
  21952. this._target[this.targetPropertyPath[0]] = currentValue;
  21953. }
  21954. if (this._target.markAsDirty) {
  21955. this._target.markAsDirty(this.targetProperty);
  21956. }
  21957. if (!returnValue) {
  21958. this._stopped = true;
  21959. }
  21960. return returnValue;
  21961. };
  21962. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21963. get: function () {
  21964. return Animation._ANIMATIONTYPE_FLOAT;
  21965. },
  21966. enumerable: true,
  21967. configurable: true
  21968. });
  21969. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21970. get: function () {
  21971. return Animation._ANIMATIONTYPE_VECTOR3;
  21972. },
  21973. enumerable: true,
  21974. configurable: true
  21975. });
  21976. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21977. get: function () {
  21978. return Animation._ANIMATIONTYPE_VECTOR2;
  21979. },
  21980. enumerable: true,
  21981. configurable: true
  21982. });
  21983. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21984. get: function () {
  21985. return Animation._ANIMATIONTYPE_QUATERNION;
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21991. get: function () {
  21992. return Animation._ANIMATIONTYPE_MATRIX;
  21993. },
  21994. enumerable: true,
  21995. configurable: true
  21996. });
  21997. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21998. get: function () {
  21999. return Animation._ANIMATIONTYPE_COLOR3;
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22005. get: function () {
  22006. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22007. },
  22008. enumerable: true,
  22009. configurable: true
  22010. });
  22011. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22012. get: function () {
  22013. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22014. },
  22015. enumerable: true,
  22016. configurable: true
  22017. });
  22018. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22019. get: function () {
  22020. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22021. },
  22022. enumerable: true,
  22023. configurable: true
  22024. });
  22025. // Statics
  22026. Animation._ANIMATIONTYPE_FLOAT = 0;
  22027. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22028. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22029. Animation._ANIMATIONTYPE_MATRIX = 3;
  22030. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22031. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22032. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22033. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22034. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22035. return Animation;
  22036. })();
  22037. BABYLON.Animation = Animation;
  22038. })(BABYLON || (BABYLON = {}));
  22039. var BABYLON;
  22040. (function (BABYLON) {
  22041. var Animatable = (function () {
  22042. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22043. if (fromFrame === void 0) { fromFrame = 0; }
  22044. if (toFrame === void 0) { toFrame = 100; }
  22045. if (loopAnimation === void 0) { loopAnimation = false; }
  22046. if (speedRatio === void 0) { speedRatio = 1.0; }
  22047. this.target = target;
  22048. this.fromFrame = fromFrame;
  22049. this.toFrame = toFrame;
  22050. this.loopAnimation = loopAnimation;
  22051. this.speedRatio = speedRatio;
  22052. this.onAnimationEnd = onAnimationEnd;
  22053. this._animations = new Array();
  22054. this._paused = false;
  22055. this.animationStarted = false;
  22056. if (animations) {
  22057. this.appendAnimations(target, animations);
  22058. }
  22059. this._scene = scene;
  22060. scene._activeAnimatables.push(this);
  22061. }
  22062. // Methods
  22063. Animatable.prototype.appendAnimations = function (target, animations) {
  22064. for (var index = 0; index < animations.length; index++) {
  22065. var animation = animations[index];
  22066. animation._target = target;
  22067. this._animations.push(animation);
  22068. }
  22069. };
  22070. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22071. var animations = this._animations;
  22072. for (var index = 0; index < animations.length; index++) {
  22073. if (animations[index].targetProperty === property) {
  22074. return animations[index];
  22075. }
  22076. }
  22077. return null;
  22078. };
  22079. Animatable.prototype.reset = function () {
  22080. var animations = this._animations;
  22081. for (var index = 0; index < animations.length; index++) {
  22082. animations[index].reset();
  22083. }
  22084. this._localDelayOffset = null;
  22085. this._pausedDelay = null;
  22086. };
  22087. Animatable.prototype.pause = function () {
  22088. if (this._paused) {
  22089. return;
  22090. }
  22091. this._paused = true;
  22092. };
  22093. Animatable.prototype.restart = function () {
  22094. this._paused = false;
  22095. };
  22096. Animatable.prototype.stop = function () {
  22097. var index = this._scene._activeAnimatables.indexOf(this);
  22098. if (index > -1) {
  22099. this._scene._activeAnimatables.splice(index, 1);
  22100. }
  22101. if (this.onAnimationEnd) {
  22102. this.onAnimationEnd();
  22103. }
  22104. };
  22105. Animatable.prototype._animate = function (delay) {
  22106. if (this._paused) {
  22107. if (!this._pausedDelay) {
  22108. this._pausedDelay = delay;
  22109. }
  22110. return true;
  22111. }
  22112. if (!this._localDelayOffset) {
  22113. this._localDelayOffset = delay;
  22114. }
  22115. else if (this._pausedDelay) {
  22116. this._localDelayOffset += delay - this._pausedDelay;
  22117. this._pausedDelay = null;
  22118. }
  22119. // Animating
  22120. var running = false;
  22121. var animations = this._animations;
  22122. for (var index = 0; index < animations.length; index++) {
  22123. var animation = animations[index];
  22124. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22125. running = running || isRunning;
  22126. }
  22127. if (!running) {
  22128. // Remove from active animatables
  22129. index = this._scene._activeAnimatables.indexOf(this);
  22130. this._scene._activeAnimatables.splice(index, 1);
  22131. }
  22132. if (!running && this.onAnimationEnd) {
  22133. this.onAnimationEnd();
  22134. }
  22135. return running;
  22136. };
  22137. return Animatable;
  22138. })();
  22139. BABYLON.Animatable = Animatable;
  22140. })(BABYLON || (BABYLON = {}));
  22141. var BABYLON;
  22142. (function (BABYLON) {
  22143. var EasingFunction = (function () {
  22144. function EasingFunction() {
  22145. // Properties
  22146. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22147. }
  22148. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22149. get: function () {
  22150. return EasingFunction._EASINGMODE_EASEIN;
  22151. },
  22152. enumerable: true,
  22153. configurable: true
  22154. });
  22155. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22156. get: function () {
  22157. return EasingFunction._EASINGMODE_EASEOUT;
  22158. },
  22159. enumerable: true,
  22160. configurable: true
  22161. });
  22162. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22163. get: function () {
  22164. return EasingFunction._EASINGMODE_EASEINOUT;
  22165. },
  22166. enumerable: true,
  22167. configurable: true
  22168. });
  22169. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22170. var n = Math.min(Math.max(easingMode, 0), 2);
  22171. this._easingMode = n;
  22172. };
  22173. EasingFunction.prototype.getEasingMode = function () {
  22174. return this._easingMode;
  22175. };
  22176. EasingFunction.prototype.easeInCore = function (gradient) {
  22177. throw new Error('You must implement this method');
  22178. };
  22179. EasingFunction.prototype.ease = function (gradient) {
  22180. switch (this._easingMode) {
  22181. case EasingFunction.EASINGMODE_EASEIN:
  22182. return this.easeInCore(gradient);
  22183. case EasingFunction.EASINGMODE_EASEOUT:
  22184. return (1 - this.easeInCore(1 - gradient));
  22185. }
  22186. if (gradient >= 0.5) {
  22187. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22188. }
  22189. return (this.easeInCore(gradient * 2) * 0.5);
  22190. };
  22191. //Statics
  22192. EasingFunction._EASINGMODE_EASEIN = 0;
  22193. EasingFunction._EASINGMODE_EASEOUT = 1;
  22194. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22195. return EasingFunction;
  22196. })();
  22197. BABYLON.EasingFunction = EasingFunction;
  22198. var CircleEase = (function (_super) {
  22199. __extends(CircleEase, _super);
  22200. function CircleEase() {
  22201. _super.apply(this, arguments);
  22202. }
  22203. CircleEase.prototype.easeInCore = function (gradient) {
  22204. gradient = Math.max(0, Math.min(1, gradient));
  22205. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22206. };
  22207. return CircleEase;
  22208. })(EasingFunction);
  22209. BABYLON.CircleEase = CircleEase;
  22210. var BackEase = (function (_super) {
  22211. __extends(BackEase, _super);
  22212. function BackEase(amplitude) {
  22213. if (amplitude === void 0) { amplitude = 1; }
  22214. _super.call(this);
  22215. this.amplitude = amplitude;
  22216. }
  22217. BackEase.prototype.easeInCore = function (gradient) {
  22218. var num = Math.max(0, this.amplitude);
  22219. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22220. };
  22221. return BackEase;
  22222. })(EasingFunction);
  22223. BABYLON.BackEase = BackEase;
  22224. var BounceEase = (function (_super) {
  22225. __extends(BounceEase, _super);
  22226. function BounceEase(bounces, bounciness) {
  22227. if (bounces === void 0) { bounces = 3; }
  22228. if (bounciness === void 0) { bounciness = 2; }
  22229. _super.call(this);
  22230. this.bounces = bounces;
  22231. this.bounciness = bounciness;
  22232. }
  22233. BounceEase.prototype.easeInCore = function (gradient) {
  22234. var y = Math.max(0.0, this.bounces);
  22235. var bounciness = this.bounciness;
  22236. if (bounciness <= 1.0) {
  22237. bounciness = 1.001;
  22238. }
  22239. var num9 = Math.pow(bounciness, y);
  22240. var num5 = 1.0 - bounciness;
  22241. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22242. var num15 = gradient * num4;
  22243. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22244. var num3 = Math.floor(num65);
  22245. var num13 = num3 + 1.0;
  22246. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22247. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22248. var num7 = (num8 + num12) * 0.5;
  22249. var num6 = gradient - num7;
  22250. var num2 = num7 - num8;
  22251. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22252. };
  22253. return BounceEase;
  22254. })(EasingFunction);
  22255. BABYLON.BounceEase = BounceEase;
  22256. var CubicEase = (function (_super) {
  22257. __extends(CubicEase, _super);
  22258. function CubicEase() {
  22259. _super.apply(this, arguments);
  22260. }
  22261. CubicEase.prototype.easeInCore = function (gradient) {
  22262. return (gradient * gradient * gradient);
  22263. };
  22264. return CubicEase;
  22265. })(EasingFunction);
  22266. BABYLON.CubicEase = CubicEase;
  22267. var ElasticEase = (function (_super) {
  22268. __extends(ElasticEase, _super);
  22269. function ElasticEase(oscillations, springiness) {
  22270. if (oscillations === void 0) { oscillations = 3; }
  22271. if (springiness === void 0) { springiness = 3; }
  22272. _super.call(this);
  22273. this.oscillations = oscillations;
  22274. this.springiness = springiness;
  22275. }
  22276. ElasticEase.prototype.easeInCore = function (gradient) {
  22277. var num2;
  22278. var num3 = Math.max(0.0, this.oscillations);
  22279. var num = Math.max(0.0, this.springiness);
  22280. if (num == 0) {
  22281. num2 = gradient;
  22282. }
  22283. else {
  22284. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22285. }
  22286. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22287. };
  22288. return ElasticEase;
  22289. })(EasingFunction);
  22290. BABYLON.ElasticEase = ElasticEase;
  22291. var ExponentialEase = (function (_super) {
  22292. __extends(ExponentialEase, _super);
  22293. function ExponentialEase(exponent) {
  22294. if (exponent === void 0) { exponent = 2; }
  22295. _super.call(this);
  22296. this.exponent = exponent;
  22297. }
  22298. ExponentialEase.prototype.easeInCore = function (gradient) {
  22299. if (this.exponent <= 0) {
  22300. return gradient;
  22301. }
  22302. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22303. };
  22304. return ExponentialEase;
  22305. })(EasingFunction);
  22306. BABYLON.ExponentialEase = ExponentialEase;
  22307. var PowerEase = (function (_super) {
  22308. __extends(PowerEase, _super);
  22309. function PowerEase(power) {
  22310. if (power === void 0) { power = 2; }
  22311. _super.call(this);
  22312. this.power = power;
  22313. }
  22314. PowerEase.prototype.easeInCore = function (gradient) {
  22315. var y = Math.max(0.0, this.power);
  22316. return Math.pow(gradient, y);
  22317. };
  22318. return PowerEase;
  22319. })(EasingFunction);
  22320. BABYLON.PowerEase = PowerEase;
  22321. var QuadraticEase = (function (_super) {
  22322. __extends(QuadraticEase, _super);
  22323. function QuadraticEase() {
  22324. _super.apply(this, arguments);
  22325. }
  22326. QuadraticEase.prototype.easeInCore = function (gradient) {
  22327. return (gradient * gradient);
  22328. };
  22329. return QuadraticEase;
  22330. })(EasingFunction);
  22331. BABYLON.QuadraticEase = QuadraticEase;
  22332. var QuarticEase = (function (_super) {
  22333. __extends(QuarticEase, _super);
  22334. function QuarticEase() {
  22335. _super.apply(this, arguments);
  22336. }
  22337. QuarticEase.prototype.easeInCore = function (gradient) {
  22338. return (gradient * gradient * gradient * gradient);
  22339. };
  22340. return QuarticEase;
  22341. })(EasingFunction);
  22342. BABYLON.QuarticEase = QuarticEase;
  22343. var QuinticEase = (function (_super) {
  22344. __extends(QuinticEase, _super);
  22345. function QuinticEase() {
  22346. _super.apply(this, arguments);
  22347. }
  22348. QuinticEase.prototype.easeInCore = function (gradient) {
  22349. return (gradient * gradient * gradient * gradient * gradient);
  22350. };
  22351. return QuinticEase;
  22352. })(EasingFunction);
  22353. BABYLON.QuinticEase = QuinticEase;
  22354. var SineEase = (function (_super) {
  22355. __extends(SineEase, _super);
  22356. function SineEase() {
  22357. _super.apply(this, arguments);
  22358. }
  22359. SineEase.prototype.easeInCore = function (gradient) {
  22360. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22361. };
  22362. return SineEase;
  22363. })(EasingFunction);
  22364. BABYLON.SineEase = SineEase;
  22365. var BezierCurveEase = (function (_super) {
  22366. __extends(BezierCurveEase, _super);
  22367. function BezierCurveEase(x1, y1, x2, y2) {
  22368. if (x1 === void 0) { x1 = 0; }
  22369. if (y1 === void 0) { y1 = 0; }
  22370. if (x2 === void 0) { x2 = 1; }
  22371. if (y2 === void 0) { y2 = 1; }
  22372. _super.call(this);
  22373. this.x1 = x1;
  22374. this.y1 = y1;
  22375. this.x2 = x2;
  22376. this.y2 = y2;
  22377. }
  22378. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22379. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22380. };
  22381. return BezierCurveEase;
  22382. })(EasingFunction);
  22383. BABYLON.BezierCurveEase = BezierCurveEase;
  22384. })(BABYLON || (BABYLON = {}));
  22385. var BABYLON;
  22386. (function (BABYLON) {
  22387. var Octree = (function () {
  22388. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22389. if (maxDepth === void 0) { maxDepth = 2; }
  22390. this.maxDepth = maxDepth;
  22391. this.dynamicContent = new Array();
  22392. this._maxBlockCapacity = maxBlockCapacity || 64;
  22393. this._selectionContent = new BABYLON.SmartArray(1024);
  22394. this._creationFunc = creationFunc;
  22395. }
  22396. // Methods
  22397. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22398. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22399. };
  22400. Octree.prototype.addMesh = function (entry) {
  22401. for (var index = 0; index < this.blocks.length; index++) {
  22402. var block = this.blocks[index];
  22403. block.addEntry(entry);
  22404. }
  22405. };
  22406. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22407. this._selectionContent.reset();
  22408. for (var index = 0; index < this.blocks.length; index++) {
  22409. var block = this.blocks[index];
  22410. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22411. }
  22412. if (allowDuplicate) {
  22413. this._selectionContent.concat(this.dynamicContent);
  22414. }
  22415. else {
  22416. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22417. }
  22418. return this._selectionContent;
  22419. };
  22420. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22421. this._selectionContent.reset();
  22422. for (var index = 0; index < this.blocks.length; index++) {
  22423. var block = this.blocks[index];
  22424. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22425. }
  22426. if (allowDuplicate) {
  22427. this._selectionContent.concat(this.dynamicContent);
  22428. }
  22429. else {
  22430. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22431. }
  22432. return this._selectionContent;
  22433. };
  22434. Octree.prototype.intersectsRay = function (ray) {
  22435. this._selectionContent.reset();
  22436. for (var index = 0; index < this.blocks.length; index++) {
  22437. var block = this.blocks[index];
  22438. block.intersectsRay(ray, this._selectionContent);
  22439. }
  22440. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22441. return this._selectionContent;
  22442. };
  22443. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22444. target.blocks = new Array();
  22445. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22446. // Segmenting space
  22447. for (var x = 0; x < 2; x++) {
  22448. for (var y = 0; y < 2; y++) {
  22449. for (var z = 0; z < 2; z++) {
  22450. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22451. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22452. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22453. block.addEntries(entries);
  22454. target.blocks.push(block);
  22455. }
  22456. }
  22457. }
  22458. };
  22459. Octree.CreationFuncForMeshes = function (entry, block) {
  22460. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22461. block.entries.push(entry);
  22462. }
  22463. };
  22464. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22465. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22466. block.entries.push(entry);
  22467. }
  22468. };
  22469. return Octree;
  22470. })();
  22471. BABYLON.Octree = Octree;
  22472. })(BABYLON || (BABYLON = {}));
  22473. var BABYLON;
  22474. (function (BABYLON) {
  22475. var OctreeBlock = (function () {
  22476. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22477. this.entries = new Array();
  22478. this._boundingVectors = new Array();
  22479. this._capacity = capacity;
  22480. this._depth = depth;
  22481. this._maxDepth = maxDepth;
  22482. this._creationFunc = creationFunc;
  22483. this._minPoint = minPoint;
  22484. this._maxPoint = maxPoint;
  22485. this._boundingVectors.push(minPoint.clone());
  22486. this._boundingVectors.push(maxPoint.clone());
  22487. this._boundingVectors.push(minPoint.clone());
  22488. this._boundingVectors[2].x = maxPoint.x;
  22489. this._boundingVectors.push(minPoint.clone());
  22490. this._boundingVectors[3].y = maxPoint.y;
  22491. this._boundingVectors.push(minPoint.clone());
  22492. this._boundingVectors[4].z = maxPoint.z;
  22493. this._boundingVectors.push(maxPoint.clone());
  22494. this._boundingVectors[5].z = minPoint.z;
  22495. this._boundingVectors.push(maxPoint.clone());
  22496. this._boundingVectors[6].x = minPoint.x;
  22497. this._boundingVectors.push(maxPoint.clone());
  22498. this._boundingVectors[7].y = minPoint.y;
  22499. }
  22500. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22501. // Property
  22502. get: function () {
  22503. return this._capacity;
  22504. },
  22505. enumerable: true,
  22506. configurable: true
  22507. });
  22508. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22509. get: function () {
  22510. return this._minPoint;
  22511. },
  22512. enumerable: true,
  22513. configurable: true
  22514. });
  22515. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22516. get: function () {
  22517. return this._maxPoint;
  22518. },
  22519. enumerable: true,
  22520. configurable: true
  22521. });
  22522. // Methods
  22523. OctreeBlock.prototype.addEntry = function (entry) {
  22524. if (this.blocks) {
  22525. for (var index = 0; index < this.blocks.length; index++) {
  22526. var block = this.blocks[index];
  22527. block.addEntry(entry);
  22528. }
  22529. return;
  22530. }
  22531. this._creationFunc(entry, this);
  22532. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22533. this.createInnerBlocks();
  22534. }
  22535. };
  22536. OctreeBlock.prototype.addEntries = function (entries) {
  22537. for (var index = 0; index < entries.length; index++) {
  22538. var mesh = entries[index];
  22539. this.addEntry(mesh);
  22540. }
  22541. };
  22542. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22543. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22544. if (this.blocks) {
  22545. for (var index = 0; index < this.blocks.length; index++) {
  22546. var block = this.blocks[index];
  22547. block.select(frustumPlanes, selection, allowDuplicate);
  22548. }
  22549. return;
  22550. }
  22551. if (allowDuplicate) {
  22552. selection.concat(this.entries);
  22553. }
  22554. else {
  22555. selection.concatWithNoDuplicate(this.entries);
  22556. }
  22557. }
  22558. };
  22559. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22560. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22561. if (this.blocks) {
  22562. for (var index = 0; index < this.blocks.length; index++) {
  22563. var block = this.blocks[index];
  22564. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22565. }
  22566. return;
  22567. }
  22568. if (allowDuplicate) {
  22569. selection.concat(this.entries);
  22570. }
  22571. else {
  22572. selection.concatWithNoDuplicate(this.entries);
  22573. }
  22574. }
  22575. };
  22576. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22577. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22578. if (this.blocks) {
  22579. for (var index = 0; index < this.blocks.length; index++) {
  22580. var block = this.blocks[index];
  22581. block.intersectsRay(ray, selection);
  22582. }
  22583. return;
  22584. }
  22585. selection.concatWithNoDuplicate(this.entries);
  22586. }
  22587. };
  22588. OctreeBlock.prototype.createInnerBlocks = function () {
  22589. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22590. };
  22591. return OctreeBlock;
  22592. })();
  22593. BABYLON.OctreeBlock = OctreeBlock;
  22594. })(BABYLON || (BABYLON = {}));
  22595. var BABYLON;
  22596. (function (BABYLON) {
  22597. var Bone = (function (_super) {
  22598. __extends(Bone, _super);
  22599. function Bone(name, skeleton, parentBone, matrix) {
  22600. _super.call(this, name, skeleton.getScene());
  22601. this.name = name;
  22602. this.children = new Array();
  22603. this.animations = new Array();
  22604. this._worldTransform = new BABYLON.Matrix();
  22605. this._absoluteTransform = new BABYLON.Matrix();
  22606. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22607. this._skeleton = skeleton;
  22608. this._matrix = matrix;
  22609. this._baseMatrix = matrix;
  22610. skeleton.bones.push(this);
  22611. if (parentBone) {
  22612. this._parent = parentBone;
  22613. parentBone.children.push(this);
  22614. }
  22615. else {
  22616. this._parent = null;
  22617. }
  22618. this._updateDifferenceMatrix();
  22619. }
  22620. // Members
  22621. Bone.prototype.getParent = function () {
  22622. return this._parent;
  22623. };
  22624. Bone.prototype.getLocalMatrix = function () {
  22625. return this._matrix;
  22626. };
  22627. Bone.prototype.getBaseMatrix = function () {
  22628. return this._baseMatrix;
  22629. };
  22630. Bone.prototype.getWorldMatrix = function () {
  22631. return this._worldTransform;
  22632. };
  22633. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22634. return this._invertedAbsoluteTransform;
  22635. };
  22636. Bone.prototype.getAbsoluteMatrix = function () {
  22637. var matrix = this._matrix.clone();
  22638. var parent = this._parent;
  22639. while (parent) {
  22640. matrix = matrix.multiply(parent.getLocalMatrix());
  22641. parent = parent.getParent();
  22642. }
  22643. return matrix;
  22644. };
  22645. // Methods
  22646. Bone.prototype.updateMatrix = function (matrix) {
  22647. this._matrix = matrix;
  22648. this._skeleton._markAsDirty();
  22649. this._updateDifferenceMatrix();
  22650. };
  22651. Bone.prototype._updateDifferenceMatrix = function () {
  22652. if (this._parent) {
  22653. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22654. }
  22655. else {
  22656. this._absoluteTransform.copyFrom(this._matrix);
  22657. }
  22658. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22659. for (var index = 0; index < this.children.length; index++) {
  22660. this.children[index]._updateDifferenceMatrix();
  22661. }
  22662. };
  22663. Bone.prototype.markAsDirty = function () {
  22664. this._currentRenderId++;
  22665. this._skeleton._markAsDirty();
  22666. };
  22667. return Bone;
  22668. })(BABYLON.Node);
  22669. BABYLON.Bone = Bone;
  22670. })(BABYLON || (BABYLON = {}));
  22671. var BABYLON;
  22672. (function (BABYLON) {
  22673. var Skeleton = (function () {
  22674. function Skeleton(name, id, scene) {
  22675. this.name = name;
  22676. this.id = id;
  22677. this.bones = new Array();
  22678. this._isDirty = true;
  22679. this._identity = BABYLON.Matrix.Identity();
  22680. this.bones = [];
  22681. this._scene = scene;
  22682. scene.skeletons.push(this);
  22683. this.prepare();
  22684. //make sure it will recalculate the matrix next time prepare is called.
  22685. this._isDirty = true;
  22686. }
  22687. // Members
  22688. Skeleton.prototype.getTransformMatrices = function () {
  22689. return this._transformMatrices;
  22690. };
  22691. Skeleton.prototype.getScene = function () {
  22692. return this._scene;
  22693. };
  22694. // Methods
  22695. Skeleton.prototype._markAsDirty = function () {
  22696. this._isDirty = true;
  22697. };
  22698. Skeleton.prototype.prepare = function () {
  22699. if (!this._isDirty) {
  22700. return;
  22701. }
  22702. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22703. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22704. }
  22705. for (var index = 0; index < this.bones.length; index++) {
  22706. var bone = this.bones[index];
  22707. var parentBone = bone.getParent();
  22708. if (parentBone) {
  22709. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22710. }
  22711. else {
  22712. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22713. }
  22714. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22715. }
  22716. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22717. this._isDirty = false;
  22718. this._scene._activeBones += this.bones.length;
  22719. };
  22720. Skeleton.prototype.getAnimatables = function () {
  22721. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22722. this._animatables = [];
  22723. for (var index = 0; index < this.bones.length; index++) {
  22724. this._animatables.push(this.bones[index]);
  22725. }
  22726. }
  22727. return this._animatables;
  22728. };
  22729. Skeleton.prototype.clone = function (name, id) {
  22730. var result = new Skeleton(name, id || name, this._scene);
  22731. for (var index = 0; index < this.bones.length; index++) {
  22732. var source = this.bones[index];
  22733. var parentBone = null;
  22734. if (source.getParent()) {
  22735. var parentIndex = this.bones.indexOf(source.getParent());
  22736. parentBone = result.bones[parentIndex];
  22737. }
  22738. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22739. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22740. }
  22741. return result;
  22742. };
  22743. return Skeleton;
  22744. })();
  22745. BABYLON.Skeleton = Skeleton;
  22746. })(BABYLON || (BABYLON = {}));
  22747. var BABYLON;
  22748. (function (BABYLON) {
  22749. var PostProcess = (function () {
  22750. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22752. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22753. this.name = name;
  22754. this.width = -1;
  22755. this.height = -1;
  22756. this._reusable = false;
  22757. this._textures = new BABYLON.SmartArray(2);
  22758. this._currentRenderTextureInd = 0;
  22759. if (camera != null) {
  22760. this._camera = camera;
  22761. this._scene = camera.getScene();
  22762. camera.attachPostProcess(this);
  22763. this._engine = this._scene.getEngine();
  22764. }
  22765. else {
  22766. this._engine = engine;
  22767. }
  22768. this._renderRatio = ratio;
  22769. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22770. this._reusable = reusable || false;
  22771. this._textureType = textureType;
  22772. samplers = samplers || [];
  22773. samplers.push("textureSampler");
  22774. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22775. }
  22776. PostProcess.prototype.isReusable = function () {
  22777. return this._reusable;
  22778. };
  22779. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22780. camera = camera || this._camera;
  22781. var scene = camera.getScene();
  22782. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22783. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22784. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22785. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22786. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22787. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22788. if (this._textures.length > 0) {
  22789. for (var i = 0; i < this._textures.length; i++) {
  22790. this._engine._releaseTexture(this._textures.data[i]);
  22791. }
  22792. this._textures.reset();
  22793. }
  22794. this.width = desiredWidth;
  22795. this.height = desiredHeight;
  22796. 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, type: this._textureType }));
  22797. if (this._reusable) {
  22798. 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, type: this._textureType }));
  22799. }
  22800. if (this.onSizeChanged) {
  22801. this.onSizeChanged();
  22802. }
  22803. }
  22804. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22805. if (this.onActivate) {
  22806. this.onActivate(camera);
  22807. }
  22808. // Clear
  22809. if (this.clearColor) {
  22810. this._engine.clear(this.clearColor, true, true);
  22811. }
  22812. else {
  22813. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22814. }
  22815. if (this._reusable) {
  22816. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22817. }
  22818. };
  22819. PostProcess.prototype.apply = function () {
  22820. // Check
  22821. if (!this._effect.isReady())
  22822. return null;
  22823. // States
  22824. this._engine.enableEffect(this._effect);
  22825. this._engine.setState(false);
  22826. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22827. this._engine.setDepthBuffer(false);
  22828. this._engine.setDepthWrite(false);
  22829. // Texture
  22830. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22831. // Parameters
  22832. if (this.onApply) {
  22833. this.onApply(this._effect);
  22834. }
  22835. return this._effect;
  22836. };
  22837. PostProcess.prototype.dispose = function (camera) {
  22838. camera = camera || this._camera;
  22839. if (this._textures.length > 0) {
  22840. for (var i = 0; i < this._textures.length; i++) {
  22841. this._engine._releaseTexture(this._textures.data[i]);
  22842. }
  22843. this._textures.reset();
  22844. }
  22845. if (!camera) {
  22846. return;
  22847. }
  22848. camera.detachPostProcess(this);
  22849. var index = camera._postProcesses.indexOf(this);
  22850. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22851. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22852. }
  22853. };
  22854. return PostProcess;
  22855. })();
  22856. BABYLON.PostProcess = PostProcess;
  22857. })(BABYLON || (BABYLON = {}));
  22858. var BABYLON;
  22859. (function (BABYLON) {
  22860. var PostProcessManager = (function () {
  22861. function PostProcessManager(scene) {
  22862. this._vertexDeclaration = [2];
  22863. this._vertexStrideSize = 2 * 4;
  22864. this._scene = scene;
  22865. }
  22866. PostProcessManager.prototype._prepareBuffers = function () {
  22867. if (this._vertexBuffer) {
  22868. return;
  22869. }
  22870. // VBO
  22871. var vertices = [];
  22872. vertices.push(1, 1);
  22873. vertices.push(-1, 1);
  22874. vertices.push(-1, -1);
  22875. vertices.push(1, -1);
  22876. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22877. // Indices
  22878. var indices = [];
  22879. indices.push(0);
  22880. indices.push(1);
  22881. indices.push(2);
  22882. indices.push(0);
  22883. indices.push(2);
  22884. indices.push(3);
  22885. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22886. };
  22887. // Methods
  22888. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22889. var postProcesses = this._scene.activeCamera._postProcesses;
  22890. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22891. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22892. return false;
  22893. }
  22894. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22895. return true;
  22896. };
  22897. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22898. var engine = this._scene.getEngine();
  22899. for (var index = 0; index < postProcesses.length; index++) {
  22900. if (index < postProcesses.length - 1) {
  22901. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22902. }
  22903. else {
  22904. if (targetTexture) {
  22905. engine.bindFramebuffer(targetTexture);
  22906. }
  22907. else {
  22908. engine.restoreDefaultFramebuffer();
  22909. }
  22910. }
  22911. var pp = postProcesses[index];
  22912. var effect = pp.apply();
  22913. if (effect) {
  22914. if (pp.onBeforeRender) {
  22915. pp.onBeforeRender(effect);
  22916. }
  22917. // VBOs
  22918. this._prepareBuffers();
  22919. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22920. // Draw order
  22921. engine.draw(true, 0, 6);
  22922. if (pp.onAfterRender) {
  22923. pp.onAfterRender(effect);
  22924. }
  22925. }
  22926. }
  22927. // Restore depth buffer
  22928. engine.setDepthBuffer(true);
  22929. engine.setDepthWrite(true);
  22930. };
  22931. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22932. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22933. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22934. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22935. return;
  22936. }
  22937. var engine = this._scene.getEngine();
  22938. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22939. if (index < postProcessesTakenIndices.length - 1) {
  22940. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22941. }
  22942. else {
  22943. if (targetTexture) {
  22944. engine.bindFramebuffer(targetTexture);
  22945. }
  22946. else {
  22947. engine.restoreDefaultFramebuffer();
  22948. }
  22949. }
  22950. if (doNotPresent) {
  22951. break;
  22952. }
  22953. var pp = postProcesses[postProcessesTakenIndices[index]];
  22954. var effect = pp.apply();
  22955. if (effect) {
  22956. if (pp.onBeforeRender) {
  22957. pp.onBeforeRender(effect);
  22958. }
  22959. // VBOs
  22960. this._prepareBuffers();
  22961. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22962. // Draw order
  22963. engine.draw(true, 0, 6);
  22964. if (pp.onAfterRender) {
  22965. pp.onAfterRender(effect);
  22966. }
  22967. }
  22968. }
  22969. // Restore depth buffer
  22970. engine.setDepthBuffer(true);
  22971. engine.setDepthWrite(true);
  22972. };
  22973. PostProcessManager.prototype.dispose = function () {
  22974. if (this._vertexBuffer) {
  22975. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22976. this._vertexBuffer = null;
  22977. }
  22978. if (this._indexBuffer) {
  22979. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22980. this._indexBuffer = null;
  22981. }
  22982. };
  22983. return PostProcessManager;
  22984. })();
  22985. BABYLON.PostProcessManager = PostProcessManager;
  22986. })(BABYLON || (BABYLON = {}));
  22987. var BABYLON;
  22988. (function (BABYLON) {
  22989. var PassPostProcess = (function (_super) {
  22990. __extends(PassPostProcess, _super);
  22991. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22992. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22993. }
  22994. return PassPostProcess;
  22995. })(BABYLON.PostProcess);
  22996. BABYLON.PassPostProcess = PassPostProcess;
  22997. })(BABYLON || (BABYLON = {}));
  22998. var BABYLON;
  22999. (function (BABYLON) {
  23000. var BlurPostProcess = (function (_super) {
  23001. __extends(BlurPostProcess, _super);
  23002. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  23003. var _this = this;
  23004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  23005. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  23006. this.direction = direction;
  23007. this.blurWidth = blurWidth;
  23008. this.onApply = function (effect) {
  23009. effect.setFloat2("screenSize", _this.width, _this.height);
  23010. effect.setVector2("direction", _this.direction);
  23011. effect.setFloat("blurWidth", _this.blurWidth);
  23012. };
  23013. }
  23014. return BlurPostProcess;
  23015. })(BABYLON.PostProcess);
  23016. BABYLON.BlurPostProcess = BlurPostProcess;
  23017. })(BABYLON || (BABYLON = {}));
  23018. var BABYLON;
  23019. (function (BABYLON) {
  23020. var RefractionPostProcess = (function (_super) {
  23021. __extends(RefractionPostProcess, _super);
  23022. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  23023. var _this = this;
  23024. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  23025. this.color = color;
  23026. this.depth = depth;
  23027. this.colorLevel = colorLevel;
  23028. this.onActivate = function (cam) {
  23029. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23030. };
  23031. this.onApply = function (effect) {
  23032. effect.setColor3("baseColor", _this.color);
  23033. effect.setFloat("depth", _this.depth);
  23034. effect.setFloat("colorLevel", _this.colorLevel);
  23035. effect.setTexture("refractionSampler", _this._refRexture);
  23036. };
  23037. }
  23038. // Methods
  23039. RefractionPostProcess.prototype.dispose = function (camera) {
  23040. if (this._refRexture) {
  23041. this._refRexture.dispose();
  23042. }
  23043. _super.prototype.dispose.call(this, camera);
  23044. };
  23045. return RefractionPostProcess;
  23046. })(BABYLON.PostProcess);
  23047. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23048. })(BABYLON || (BABYLON = {}));
  23049. var BABYLON;
  23050. (function (BABYLON) {
  23051. var BlackAndWhitePostProcess = (function (_super) {
  23052. __extends(BlackAndWhitePostProcess, _super);
  23053. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23054. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23055. }
  23056. return BlackAndWhitePostProcess;
  23057. })(BABYLON.PostProcess);
  23058. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23059. })(BABYLON || (BABYLON = {}));
  23060. var BABYLON;
  23061. (function (BABYLON) {
  23062. var ConvolutionPostProcess = (function (_super) {
  23063. __extends(ConvolutionPostProcess, _super);
  23064. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23065. var _this = this;
  23066. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23067. this.kernel = kernel;
  23068. this.onApply = function (effect) {
  23069. effect.setFloat2("screenSize", _this.width, _this.height);
  23070. effect.setArray("kernel", _this.kernel);
  23071. };
  23072. }
  23073. // Statics
  23074. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23075. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23076. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23077. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23078. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23079. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23080. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23081. return ConvolutionPostProcess;
  23082. })(BABYLON.PostProcess);
  23083. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23084. })(BABYLON || (BABYLON = {}));
  23085. var BABYLON;
  23086. (function (BABYLON) {
  23087. var FilterPostProcess = (function (_super) {
  23088. __extends(FilterPostProcess, _super);
  23089. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23090. var _this = this;
  23091. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23092. this.kernelMatrix = kernelMatrix;
  23093. this.onApply = function (effect) {
  23094. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23095. };
  23096. }
  23097. return FilterPostProcess;
  23098. })(BABYLON.PostProcess);
  23099. BABYLON.FilterPostProcess = FilterPostProcess;
  23100. })(BABYLON || (BABYLON = {}));
  23101. var BABYLON;
  23102. (function (BABYLON) {
  23103. var FxaaPostProcess = (function (_super) {
  23104. __extends(FxaaPostProcess, _super);
  23105. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23106. var _this = this;
  23107. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23108. this.onSizeChanged = function () {
  23109. _this.texelWidth = 1.0 / _this.width;
  23110. _this.texelHeight = 1.0 / _this.height;
  23111. };
  23112. this.onApply = function (effect) {
  23113. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23114. };
  23115. }
  23116. return FxaaPostProcess;
  23117. })(BABYLON.PostProcess);
  23118. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23119. })(BABYLON || (BABYLON = {}));
  23120. var BABYLON;
  23121. (function (BABYLON) {
  23122. var StereoscopicInterlacePostProcess = (function (_super) {
  23123. __extends(StereoscopicInterlacePostProcess, _super);
  23124. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23125. var _this = this;
  23126. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23127. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23128. this.onSizeChanged = function () {
  23129. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23130. };
  23131. this.onApply = function (effect) {
  23132. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23133. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23134. };
  23135. }
  23136. return StereoscopicInterlacePostProcess;
  23137. })(BABYLON.PostProcess);
  23138. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23139. })(BABYLON || (BABYLON = {}));
  23140. var BABYLON;
  23141. (function (BABYLON) {
  23142. var LensFlare = (function () {
  23143. function LensFlare(size, position, color, imgUrl, system) {
  23144. this.size = size;
  23145. this.position = position;
  23146. this.dispose = function () {
  23147. if (this.texture) {
  23148. this.texture.dispose();
  23149. }
  23150. // Remove from scene
  23151. var index = this._system.lensFlares.indexOf(this);
  23152. this._system.lensFlares.splice(index, 1);
  23153. };
  23154. this.color = color || new BABYLON.Color3(1, 1, 1);
  23155. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23156. this._system = system;
  23157. system.lensFlares.push(this);
  23158. }
  23159. return LensFlare;
  23160. })();
  23161. BABYLON.LensFlare = LensFlare;
  23162. })(BABYLON || (BABYLON = {}));
  23163. var BABYLON;
  23164. (function (BABYLON) {
  23165. var LensFlareSystem = (function () {
  23166. function LensFlareSystem(name, emitter, scene) {
  23167. this.name = name;
  23168. this.lensFlares = new Array();
  23169. this.borderLimit = 300;
  23170. this.layerMask = 0x0FFFFFFF;
  23171. this._vertexDeclaration = [2];
  23172. this._vertexStrideSize = 2 * 4;
  23173. this._isEnabled = true;
  23174. this._scene = scene;
  23175. this._emitter = emitter;
  23176. scene.lensFlareSystems.push(this);
  23177. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23178. // VBO
  23179. var vertices = [];
  23180. vertices.push(1, 1);
  23181. vertices.push(-1, 1);
  23182. vertices.push(-1, -1);
  23183. vertices.push(1, -1);
  23184. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23185. // Indices
  23186. var indices = [];
  23187. indices.push(0);
  23188. indices.push(1);
  23189. indices.push(2);
  23190. indices.push(0);
  23191. indices.push(2);
  23192. indices.push(3);
  23193. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23194. // Effects
  23195. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23196. }
  23197. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23198. get: function () {
  23199. return this._isEnabled;
  23200. },
  23201. set: function (value) {
  23202. this._isEnabled = value;
  23203. },
  23204. enumerable: true,
  23205. configurable: true
  23206. });
  23207. LensFlareSystem.prototype.getScene = function () {
  23208. return this._scene;
  23209. };
  23210. LensFlareSystem.prototype.getEmitter = function () {
  23211. return this._emitter;
  23212. };
  23213. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23214. this._emitter = newEmitter;
  23215. };
  23216. LensFlareSystem.prototype.getEmitterPosition = function () {
  23217. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23218. };
  23219. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23220. var position = this.getEmitterPosition();
  23221. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23222. this._positionX = position.x;
  23223. this._positionY = position.y;
  23224. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23225. if (position.z > 0) {
  23226. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23227. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23228. return true;
  23229. }
  23230. }
  23231. return false;
  23232. };
  23233. LensFlareSystem.prototype._isVisible = function () {
  23234. if (!this._isEnabled) {
  23235. return false;
  23236. }
  23237. var emitterPosition = this.getEmitterPosition();
  23238. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23239. var distance = direction.length();
  23240. direction.normalize();
  23241. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23242. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23243. return !pickInfo.hit || pickInfo.distance > distance;
  23244. };
  23245. LensFlareSystem.prototype.render = function () {
  23246. if (!this._effect.isReady())
  23247. return false;
  23248. var engine = this._scene.getEngine();
  23249. var viewport = this._scene.activeCamera.viewport;
  23250. var globalViewport = viewport.toGlobal(engine);
  23251. // Position
  23252. if (!this.computeEffectivePosition(globalViewport)) {
  23253. return false;
  23254. }
  23255. // Visibility
  23256. if (!this._isVisible()) {
  23257. return false;
  23258. }
  23259. // Intensity
  23260. var awayX;
  23261. var awayY;
  23262. if (this._positionX < this.borderLimit + globalViewport.x) {
  23263. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23264. }
  23265. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23266. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23267. }
  23268. else {
  23269. awayX = 0;
  23270. }
  23271. if (this._positionY < this.borderLimit + globalViewport.y) {
  23272. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23273. }
  23274. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23275. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23276. }
  23277. else {
  23278. awayY = 0;
  23279. }
  23280. var away = (awayX > awayY) ? awayX : awayY;
  23281. if (away > this.borderLimit) {
  23282. away = this.borderLimit;
  23283. }
  23284. var intensity = 1.0 - (away / this.borderLimit);
  23285. if (intensity < 0) {
  23286. return false;
  23287. }
  23288. if (intensity > 1.0) {
  23289. intensity = 1.0;
  23290. }
  23291. // Position
  23292. var centerX = globalViewport.x + globalViewport.width / 2;
  23293. var centerY = globalViewport.y + globalViewport.height / 2;
  23294. var distX = centerX - this._positionX;
  23295. var distY = centerY - this._positionY;
  23296. // Effects
  23297. engine.enableEffect(this._effect);
  23298. engine.setState(false);
  23299. engine.setDepthBuffer(false);
  23300. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23301. // VBOs
  23302. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23303. // Flares
  23304. for (var index = 0; index < this.lensFlares.length; index++) {
  23305. var flare = this.lensFlares[index];
  23306. var x = centerX - (distX * flare.position);
  23307. var y = centerY - (distY * flare.position);
  23308. var cw = flare.size;
  23309. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23310. var cx = 2 * (x / globalViewport.width) - 1.0;
  23311. var cy = 1.0 - 2 * (y / globalViewport.height);
  23312. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23313. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23314. // Texture
  23315. this._effect.setTexture("textureSampler", flare.texture);
  23316. // Color
  23317. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23318. // Draw order
  23319. engine.draw(true, 0, 6);
  23320. }
  23321. engine.setDepthBuffer(true);
  23322. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23323. return true;
  23324. };
  23325. LensFlareSystem.prototype.dispose = function () {
  23326. if (this._vertexBuffer) {
  23327. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23328. this._vertexBuffer = null;
  23329. }
  23330. if (this._indexBuffer) {
  23331. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23332. this._indexBuffer = null;
  23333. }
  23334. while (this.lensFlares.length) {
  23335. this.lensFlares[0].dispose();
  23336. }
  23337. // Remove from scene
  23338. var index = this._scene.lensFlareSystems.indexOf(this);
  23339. this._scene.lensFlareSystems.splice(index, 1);
  23340. };
  23341. return LensFlareSystem;
  23342. })();
  23343. BABYLON.LensFlareSystem = LensFlareSystem;
  23344. })(BABYLON || (BABYLON = {}));
  23345. var BABYLON;
  23346. (function (BABYLON) {
  23347. var CannonJSPlugin = (function () {
  23348. function CannonJSPlugin() {
  23349. this._registeredMeshes = [];
  23350. this._physicsMaterials = [];
  23351. this.updateBodyPosition = function (mesh) {
  23352. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23353. var registeredMesh = this._registeredMeshes[index];
  23354. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23355. var body = registeredMesh.body;
  23356. var center = mesh.getBoundingInfo().boundingBox.center;
  23357. body.position.set(center.x, center.z, center.y);
  23358. body.quaternion.x = mesh.rotationQuaternion.x;
  23359. body.quaternion.z = mesh.rotationQuaternion.y;
  23360. body.quaternion.y = mesh.rotationQuaternion.z;
  23361. body.quaternion.w = -mesh.rotationQuaternion.w;
  23362. return;
  23363. }
  23364. }
  23365. };
  23366. }
  23367. CannonJSPlugin.prototype.initialize = function (iterations) {
  23368. if (iterations === void 0) { iterations = 10; }
  23369. this._world = new CANNON.World();
  23370. this._world.broadphase = new CANNON.NaiveBroadphase();
  23371. this._world.solver.iterations = iterations;
  23372. };
  23373. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23374. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23375. };
  23376. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23377. this._world.step(delta);
  23378. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23379. var registeredMesh = this._registeredMeshes[index];
  23380. if (registeredMesh.isChild) {
  23381. continue;
  23382. }
  23383. // Body position
  23384. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23385. var deltaPos = registeredMesh.delta;
  23386. if (deltaPos) {
  23387. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23388. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23389. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23390. }
  23391. else {
  23392. registeredMesh.mesh.position.x = bodyX;
  23393. registeredMesh.mesh.position.y = bodyZ;
  23394. registeredMesh.mesh.position.z = bodyY;
  23395. }
  23396. if (!registeredMesh.mesh.rotationQuaternion) {
  23397. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23398. }
  23399. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23400. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23401. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23402. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23403. }
  23404. };
  23405. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23406. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23407. };
  23408. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23409. this.unregisterMesh(mesh);
  23410. mesh.computeWorldMatrix(true);
  23411. switch (impostor) {
  23412. case BABYLON.PhysicsEngine.SphereImpostor:
  23413. var bbox = mesh.getBoundingInfo().boundingBox;
  23414. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23415. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23416. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23417. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23418. case BABYLON.PhysicsEngine.BoxImpostor:
  23419. bbox = mesh.getBoundingInfo().boundingBox;
  23420. var min = bbox.minimumWorld;
  23421. var max = bbox.maximumWorld;
  23422. var box = max.subtract(min).scale(0.5);
  23423. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23424. case BABYLON.PhysicsEngine.PlaneImpostor:
  23425. return this._createPlane(mesh, options);
  23426. case BABYLON.PhysicsEngine.MeshImpostor:
  23427. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23428. var rawFaces = mesh.getIndices();
  23429. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23430. }
  23431. return null;
  23432. };
  23433. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23434. var shape = new CANNON.Sphere(radius);
  23435. if (!options) {
  23436. return shape;
  23437. }
  23438. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23439. };
  23440. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23441. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23442. if (!options) {
  23443. return shape;
  23444. }
  23445. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23446. };
  23447. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23448. var shape = new CANNON.Plane();
  23449. if (!options) {
  23450. return shape;
  23451. }
  23452. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23453. };
  23454. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23455. var verts = [], faces = [];
  23456. mesh.computeWorldMatrix(true);
  23457. // Get vertices
  23458. for (var i = 0; i < rawVerts.length; i += 3) {
  23459. var transformed = BABYLON.Vector3.Zero();
  23460. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23461. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23462. }
  23463. // Get faces
  23464. for (var j = 0; j < rawFaces.length; j += 3) {
  23465. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23466. }
  23467. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23468. if (!options) {
  23469. return shape;
  23470. }
  23471. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23472. };
  23473. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23474. var index;
  23475. var mat;
  23476. for (index = 0; index < this._physicsMaterials.length; index++) {
  23477. mat = this._physicsMaterials[index];
  23478. if (mat.friction === friction && mat.restitution === restitution) {
  23479. return mat;
  23480. }
  23481. }
  23482. var currentMat = new CANNON.Material();
  23483. currentMat.friction = friction;
  23484. currentMat.restitution = restitution;
  23485. this._physicsMaterials.push(currentMat);
  23486. for (index = 0; index < this._physicsMaterials.length; index++) {
  23487. mat = this._physicsMaterials[index];
  23488. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23489. contactMaterial.contactEquationStiffness = 1e10;
  23490. contactMaterial.contactEquationRegularizationTime = 10;
  23491. this._world.addContactMaterial(contactMaterial);
  23492. }
  23493. return currentMat;
  23494. };
  23495. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23496. var initialRotation = null;
  23497. if (mesh.rotationQuaternion) {
  23498. initialRotation = mesh.rotationQuaternion.clone();
  23499. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23500. }
  23501. // The delta between the mesh position and the mesh bounding box center
  23502. var bbox = mesh.getBoundingInfo().boundingBox;
  23503. var deltaPosition = mesh.position.subtract(bbox.center);
  23504. var material = this._addMaterial(friction, restitution);
  23505. var body = new CANNON.RigidBody(mass, shape, material);
  23506. if (initialRotation) {
  23507. body.quaternion.x = initialRotation.x;
  23508. body.quaternion.z = initialRotation.y;
  23509. body.quaternion.y = initialRotation.z;
  23510. body.quaternion.w = -initialRotation.w;
  23511. }
  23512. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23513. this._world.add(body);
  23514. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23515. return body;
  23516. };
  23517. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23518. var compoundShape = new CANNON.Compound();
  23519. for (var index = 0; index < parts.length; index++) {
  23520. var mesh = parts[index].mesh;
  23521. var shape = this.registerMesh(mesh, parts[index].impostor);
  23522. if (index == 0) {
  23523. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23524. }
  23525. else {
  23526. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23527. }
  23528. }
  23529. var initialMesh = parts[0].mesh;
  23530. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23531. body.parts = parts;
  23532. return body;
  23533. };
  23534. CannonJSPlugin.prototype._unbindBody = function (body) {
  23535. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23536. var registeredMesh = this._registeredMeshes[index];
  23537. if (registeredMesh.body === body) {
  23538. registeredMesh.body = null;
  23539. registeredMesh.delta = 0;
  23540. }
  23541. }
  23542. };
  23543. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23544. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23545. var registeredMesh = this._registeredMeshes[index];
  23546. if (registeredMesh.mesh === mesh) {
  23547. // Remove body
  23548. if (registeredMesh.body) {
  23549. this._world.remove(registeredMesh.body);
  23550. this._unbindBody(registeredMesh.body);
  23551. }
  23552. this._registeredMeshes.splice(index, 1);
  23553. return;
  23554. }
  23555. }
  23556. };
  23557. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23558. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23559. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23560. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23561. var registeredMesh = this._registeredMeshes[index];
  23562. if (registeredMesh.mesh === mesh) {
  23563. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23564. return;
  23565. }
  23566. }
  23567. };
  23568. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23569. var body1 = null, body2 = null;
  23570. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23571. var registeredMesh = this._registeredMeshes[index];
  23572. if (registeredMesh.mesh === mesh1) {
  23573. body1 = registeredMesh.body;
  23574. }
  23575. else if (registeredMesh.mesh === mesh2) {
  23576. body2 = registeredMesh.body;
  23577. }
  23578. }
  23579. if (!body1 || !body2) {
  23580. return false;
  23581. }
  23582. 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));
  23583. this._world.addConstraint(constraint);
  23584. return true;
  23585. };
  23586. CannonJSPlugin.prototype.dispose = function () {
  23587. while (this._registeredMeshes.length) {
  23588. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23589. }
  23590. };
  23591. CannonJSPlugin.prototype.isSupported = function () {
  23592. return window.CANNON !== undefined;
  23593. };
  23594. return CannonJSPlugin;
  23595. })();
  23596. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23597. })(BABYLON || (BABYLON = {}));
  23598. var BABYLON;
  23599. (function (BABYLON) {
  23600. var OimoJSPlugin = (function () {
  23601. function OimoJSPlugin() {
  23602. this._registeredMeshes = [];
  23603. /**
  23604. * Update the body position according to the mesh position
  23605. * @param mesh
  23606. */
  23607. this.updateBodyPosition = function (mesh) {
  23608. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23609. var registeredMesh = this._registeredMeshes[index];
  23610. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23611. var body = registeredMesh.body.body;
  23612. mesh.computeWorldMatrix(true);
  23613. var center = mesh.getBoundingInfo().boundingBox.center;
  23614. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23615. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23616. body.sleeping = false;
  23617. return;
  23618. }
  23619. // Case where the parent has been updated
  23620. if (registeredMesh.mesh.parent === mesh) {
  23621. mesh.computeWorldMatrix(true);
  23622. registeredMesh.mesh.computeWorldMatrix(true);
  23623. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23624. var absoluteRotation = mesh.rotation;
  23625. body = registeredMesh.body.body;
  23626. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23627. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23628. body.sleeping = false;
  23629. return;
  23630. }
  23631. }
  23632. };
  23633. }
  23634. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23635. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23636. };
  23637. OimoJSPlugin.prototype.initialize = function (iterations) {
  23638. this._world = new OIMO.World();
  23639. this._world.clear();
  23640. };
  23641. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23642. this._world.gravity = gravity;
  23643. };
  23644. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23645. var body = null;
  23646. this.unregisterMesh(mesh);
  23647. mesh.computeWorldMatrix(true);
  23648. var initialRotation = null;
  23649. if (mesh.rotationQuaternion) {
  23650. initialRotation = mesh.rotationQuaternion.clone();
  23651. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23652. mesh.computeWorldMatrix(true);
  23653. }
  23654. var bbox = mesh.getBoundingInfo().boundingBox;
  23655. // The delta between the mesh position and the mesh bounding box center
  23656. var deltaPosition = mesh.position.subtract(bbox.center);
  23657. // Transform delta position with the rotation
  23658. if (initialRotation) {
  23659. var m = new BABYLON.Matrix();
  23660. initialRotation.toRotationMatrix(m);
  23661. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23662. }
  23663. // register mesh
  23664. switch (impostor) {
  23665. case BABYLON.PhysicsEngine.SphereImpostor:
  23666. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23667. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23668. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23669. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23670. body = new OIMO.Body({
  23671. type: 'sphere',
  23672. size: [size],
  23673. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23674. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23675. move: options.mass != 0,
  23676. config: [options.mass, options.friction, options.restitution],
  23677. world: this._world
  23678. });
  23679. break;
  23680. case BABYLON.PhysicsEngine.PlaneImpostor:
  23681. //Oimo "fakes" a cylinder as a box, so why don't we!
  23682. case BABYLON.PhysicsEngine.CylinderImpostor:
  23683. case BABYLON.PhysicsEngine.BoxImpostor:
  23684. var min = bbox.minimumWorld;
  23685. var max = bbox.maximumWorld;
  23686. var box = max.subtract(min);
  23687. var sizeX = this._checkWithEpsilon(box.x);
  23688. var sizeY = this._checkWithEpsilon(box.y);
  23689. var sizeZ = this._checkWithEpsilon(box.z);
  23690. body = new OIMO.Body({
  23691. type: 'box',
  23692. size: [sizeX, sizeY, sizeZ],
  23693. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23694. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23695. move: options.mass != 0,
  23696. config: [options.mass, options.friction, options.restitution],
  23697. world: this._world
  23698. });
  23699. break;
  23700. }
  23701. //If quaternion was set as the rotation of the object
  23702. if (initialRotation) {
  23703. //We have to access the rigid body's properties to set the quaternion.
  23704. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23705. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23706. //update the internal rotation matrix
  23707. body.body.syncShapes();
  23708. }
  23709. this._registeredMeshes.push({
  23710. mesh: mesh,
  23711. body: body,
  23712. delta: deltaPosition
  23713. });
  23714. return body;
  23715. };
  23716. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23717. var types = [], sizes = [], positions = [], rotations = [];
  23718. var initialMesh = parts[0].mesh;
  23719. for (var index = 0; index < parts.length; index++) {
  23720. var part = parts[index];
  23721. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23722. types.push(bodyParameters.type);
  23723. sizes.push.apply(sizes, bodyParameters.size);
  23724. positions.push.apply(positions, bodyParameters.pos);
  23725. rotations.push.apply(rotations, bodyParameters.rot);
  23726. }
  23727. var body = new OIMO.Body({
  23728. type: types,
  23729. size: sizes,
  23730. pos: positions,
  23731. rot: rotations,
  23732. move: options.mass != 0,
  23733. config: [options.mass, options.friction, options.restitution],
  23734. world: this._world
  23735. });
  23736. this._registeredMeshes.push({
  23737. mesh: initialMesh,
  23738. body: body
  23739. });
  23740. return body;
  23741. };
  23742. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23743. var bodyParameters = null;
  23744. var mesh = part.mesh;
  23745. // We need the bounding box/sphere info to compute the physics body
  23746. mesh.computeWorldMatrix();
  23747. switch (part.impostor) {
  23748. case BABYLON.PhysicsEngine.SphereImpostor:
  23749. var bbox = mesh.getBoundingInfo().boundingBox;
  23750. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23751. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23752. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23753. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23754. bodyParameters = {
  23755. type: 'sphere',
  23756. /* bug with oimo : sphere needs 3 sizes in this case */
  23757. size: [size, -1, -1],
  23758. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23759. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23760. };
  23761. break;
  23762. case BABYLON.PhysicsEngine.PlaneImpostor:
  23763. case BABYLON.PhysicsEngine.BoxImpostor:
  23764. bbox = mesh.getBoundingInfo().boundingBox;
  23765. var min = bbox.minimumWorld;
  23766. var max = bbox.maximumWorld;
  23767. var box = max.subtract(min);
  23768. var sizeX = this._checkWithEpsilon(box.x);
  23769. var sizeY = this._checkWithEpsilon(box.y);
  23770. var sizeZ = this._checkWithEpsilon(box.z);
  23771. var relativePosition = mesh.position;
  23772. bodyParameters = {
  23773. type: 'box',
  23774. size: [sizeX, sizeY, sizeZ],
  23775. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23776. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23777. };
  23778. break;
  23779. }
  23780. return bodyParameters;
  23781. };
  23782. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23783. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23784. var registeredMesh = this._registeredMeshes[index];
  23785. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23786. if (registeredMesh.body) {
  23787. this._world.removeRigidBody(registeredMesh.body.body);
  23788. this._unbindBody(registeredMesh.body);
  23789. }
  23790. this._registeredMeshes.splice(index, 1);
  23791. return;
  23792. }
  23793. }
  23794. };
  23795. OimoJSPlugin.prototype._unbindBody = function (body) {
  23796. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23797. var registeredMesh = this._registeredMeshes[index];
  23798. if (registeredMesh.body === body) {
  23799. registeredMesh.body = null;
  23800. }
  23801. }
  23802. };
  23803. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23804. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23805. var registeredMesh = this._registeredMeshes[index];
  23806. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23807. // Get object mass to have a behaviour similar to cannon.js
  23808. var mass = registeredMesh.body.body.massInfo.mass;
  23809. // The force is scaled with the mass of object
  23810. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23811. return;
  23812. }
  23813. }
  23814. };
  23815. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23816. var body1 = null, body2 = null;
  23817. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23818. var registeredMesh = this._registeredMeshes[index];
  23819. if (registeredMesh.mesh === mesh1) {
  23820. body1 = registeredMesh.body.body;
  23821. }
  23822. else if (registeredMesh.mesh === mesh2) {
  23823. body2 = registeredMesh.body.body;
  23824. }
  23825. }
  23826. if (!body1 || !body2) {
  23827. return false;
  23828. }
  23829. if (!options) {
  23830. options = {};
  23831. }
  23832. new OIMO.Link({
  23833. type: options.type,
  23834. body1: body1,
  23835. body2: body2,
  23836. min: options.min,
  23837. max: options.max,
  23838. axe1: options.axe1,
  23839. axe2: options.axe2,
  23840. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23841. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23842. collision: options.collision,
  23843. spring: options.spring,
  23844. world: this._world
  23845. });
  23846. return true;
  23847. };
  23848. OimoJSPlugin.prototype.dispose = function () {
  23849. this._world.clear();
  23850. while (this._registeredMeshes.length) {
  23851. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23852. }
  23853. };
  23854. OimoJSPlugin.prototype.isSupported = function () {
  23855. return OIMO !== undefined;
  23856. };
  23857. OimoJSPlugin.prototype._getLastShape = function (body) {
  23858. var lastShape = body.shapes;
  23859. while (lastShape.next) {
  23860. lastShape = lastShape.next;
  23861. }
  23862. return lastShape;
  23863. };
  23864. OimoJSPlugin.prototype.runOneStep = function (time) {
  23865. this._world.step();
  23866. // Update the position of all registered meshes
  23867. var i = this._registeredMeshes.length;
  23868. var m;
  23869. while (i--) {
  23870. var body = this._registeredMeshes[i].body.body;
  23871. var mesh = this._registeredMeshes[i].mesh;
  23872. var delta = this._registeredMeshes[i].delta;
  23873. if (!body.sleeping) {
  23874. if (body.shapes.next) {
  23875. var parentShape = this._getLastShape(body);
  23876. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23877. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23878. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23879. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23880. if (!mesh.rotationQuaternion) {
  23881. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23882. }
  23883. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23884. mesh.computeWorldMatrix();
  23885. }
  23886. else {
  23887. m = body.getMatrix();
  23888. mtx = BABYLON.Matrix.FromArray(m);
  23889. // Body position
  23890. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23891. if (!delta) {
  23892. mesh.position.x = bodyX;
  23893. mesh.position.y = bodyY;
  23894. mesh.position.z = bodyZ;
  23895. }
  23896. else {
  23897. mesh.position.x = bodyX + delta.x;
  23898. mesh.position.y = bodyY + delta.y;
  23899. mesh.position.z = bodyZ + delta.z;
  23900. }
  23901. if (!mesh.rotationQuaternion) {
  23902. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23903. }
  23904. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23905. mesh.computeWorldMatrix();
  23906. }
  23907. }
  23908. }
  23909. };
  23910. return OimoJSPlugin;
  23911. })();
  23912. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23913. })(BABYLON || (BABYLON = {}));
  23914. var BABYLON;
  23915. (function (BABYLON) {
  23916. var PhysicsEngine = (function () {
  23917. function PhysicsEngine(plugin) {
  23918. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23919. }
  23920. PhysicsEngine.prototype._initialize = function (gravity) {
  23921. this._currentPlugin.initialize();
  23922. this._setGravity(gravity);
  23923. };
  23924. PhysicsEngine.prototype._runOneStep = function (delta) {
  23925. if (delta > 0.1) {
  23926. delta = 0.1;
  23927. }
  23928. else if (delta <= 0) {
  23929. delta = 1.0 / 60.0;
  23930. }
  23931. this._currentPlugin.runOneStep(delta);
  23932. };
  23933. PhysicsEngine.prototype._setGravity = function (gravity) {
  23934. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23935. this._currentPlugin.setGravity(this.gravity);
  23936. };
  23937. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23938. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23939. };
  23940. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23941. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23942. };
  23943. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23944. this._currentPlugin.unregisterMesh(mesh);
  23945. };
  23946. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23947. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23948. };
  23949. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23950. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23951. };
  23952. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23953. this._currentPlugin.updateBodyPosition(mesh);
  23954. };
  23955. PhysicsEngine.prototype.dispose = function () {
  23956. this._currentPlugin.dispose();
  23957. };
  23958. PhysicsEngine.prototype.isSupported = function () {
  23959. return this._currentPlugin.isSupported();
  23960. };
  23961. // Statics
  23962. PhysicsEngine.NoImpostor = 0;
  23963. PhysicsEngine.SphereImpostor = 1;
  23964. PhysicsEngine.BoxImpostor = 2;
  23965. PhysicsEngine.PlaneImpostor = 3;
  23966. PhysicsEngine.MeshImpostor = 4;
  23967. PhysicsEngine.CapsuleImpostor = 5;
  23968. PhysicsEngine.ConeImpostor = 6;
  23969. PhysicsEngine.CylinderImpostor = 7;
  23970. PhysicsEngine.ConvexHullImpostor = 8;
  23971. PhysicsEngine.Epsilon = 0.001;
  23972. return PhysicsEngine;
  23973. })();
  23974. BABYLON.PhysicsEngine = PhysicsEngine;
  23975. })(BABYLON || (BABYLON = {}));
  23976. var BABYLON;
  23977. (function (BABYLON) {
  23978. var serializeLight = function (light) {
  23979. var serializationObject = {};
  23980. serializationObject.name = light.name;
  23981. serializationObject.id = light.id;
  23982. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23983. if (light instanceof BABYLON.PointLight) {
  23984. serializationObject.type = 0;
  23985. serializationObject.position = (light).position.asArray();
  23986. }
  23987. else if (light instanceof BABYLON.DirectionalLight) {
  23988. serializationObject.type = 1;
  23989. var directionalLight = light;
  23990. serializationObject.position = directionalLight.position.asArray();
  23991. serializationObject.direction = directionalLight.direction.asArray();
  23992. }
  23993. else if (light instanceof BABYLON.SpotLight) {
  23994. serializationObject.type = 2;
  23995. var spotLight = light;
  23996. serializationObject.position = spotLight.position.asArray();
  23997. serializationObject.direction = spotLight.position.asArray();
  23998. serializationObject.angle = spotLight.angle;
  23999. serializationObject.exponent = spotLight.exponent;
  24000. }
  24001. else if (light instanceof BABYLON.HemisphericLight) {
  24002. serializationObject.type = 3;
  24003. var hemisphericLight = light;
  24004. serializationObject.direction = hemisphericLight.direction.asArray();
  24005. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  24006. }
  24007. if (light.intensity) {
  24008. serializationObject.intensity = light.intensity;
  24009. }
  24010. serializationObject.range = light.range;
  24011. serializationObject.diffuse = light.diffuse.asArray();
  24012. serializationObject.specular = light.specular.asArray();
  24013. return serializationObject;
  24014. };
  24015. var serializeFresnelParameter = function (fresnelParameter) {
  24016. var serializationObject = {};
  24017. serializationObject.isEnabled = fresnelParameter.isEnabled;
  24018. serializationObject.leftColor = fresnelParameter.leftColor;
  24019. serializationObject.rightColor = fresnelParameter.rightColor;
  24020. serializationObject.bias = fresnelParameter.bias;
  24021. serializationObject.power = fresnelParameter.power;
  24022. return serializationObject;
  24023. };
  24024. var serializeAnimation;
  24025. var appendAnimations = function (source, destination) {
  24026. if (source.animations) {
  24027. destination.animations = [];
  24028. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24029. var animation = source.animations[animationIndex];
  24030. destination.animations.push(serializeAnimation(animation));
  24031. }
  24032. }
  24033. };
  24034. var serializeCamera = function (camera) {
  24035. var serializationObject = {};
  24036. serializationObject.name = camera.name;
  24037. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24038. serializationObject.id = camera.id;
  24039. serializationObject.position = camera.position.asArray();
  24040. // Parent
  24041. if (camera.parent) {
  24042. serializationObject.parentId = camera.parent.id;
  24043. }
  24044. serializationObject.fov = camera.fov;
  24045. serializationObject.minZ = camera.minZ;
  24046. serializationObject.maxZ = camera.maxZ;
  24047. serializationObject.inertia = camera.inertia;
  24048. //setting the type
  24049. if (camera instanceof BABYLON.FreeCamera) {
  24050. serializationObject.type = "FreeCamera";
  24051. }
  24052. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24053. serializationObject.type = "ArcRotateCamera";
  24054. }
  24055. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24056. serializationObject.type = "AnaglyphArcRotateCamera";
  24057. }
  24058. else if (camera instanceof BABYLON.GamepadCamera) {
  24059. serializationObject.type = "GamepadCamera";
  24060. }
  24061. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24062. serializationObject.type = "AnaglyphFreeCamera";
  24063. }
  24064. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24065. serializationObject.type = "DeviceOrientationCamera";
  24066. }
  24067. else if (camera instanceof BABYLON.FollowCamera) {
  24068. serializationObject.type = "FollowCamera";
  24069. }
  24070. else if (camera instanceof BABYLON.TouchCamera) {
  24071. serializationObject.type = "TouchCamera";
  24072. }
  24073. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24074. serializationObject.type = "VirtualJoysticksCamera";
  24075. }
  24076. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24077. serializationObject.type = "WebVRFreeCamera";
  24078. }
  24079. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24080. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24081. }
  24082. //special properties of specific cameras
  24083. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24084. var arcCamera = camera;
  24085. serializationObject.alpha = arcCamera.alpha;
  24086. serializationObject.beta = arcCamera.beta;
  24087. serializationObject.radius = arcCamera.radius;
  24088. if (arcCamera.target && arcCamera.target.id) {
  24089. serializationObject.lockedTargetId = arcCamera.target.id;
  24090. }
  24091. }
  24092. else if (camera instanceof BABYLON.FollowCamera) {
  24093. var followCam = camera;
  24094. serializationObject.radius = followCam.radius;
  24095. serializationObject.heightOffset = followCam.heightOffset;
  24096. serializationObject.rotationOffset = followCam.rotationOffset;
  24097. }
  24098. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24099. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  24100. if (camera['_interaxialDistance'] !== undefined) {
  24101. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24102. }
  24103. }
  24104. //general properties that not all cameras have. The [] is due to typescript's type safety
  24105. if (camera['speed'] !== undefined) {
  24106. serializationObject.speed = camera['speed'];
  24107. }
  24108. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24109. serializationObject.target = camera['target'].asArray();
  24110. }
  24111. // Target
  24112. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24113. serializationObject.rotation = camera['rotation'].asArray();
  24114. }
  24115. // Locked target
  24116. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24117. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24118. }
  24119. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24120. serializationObject.applyGravity = camera['applyGravity'] || false;
  24121. if (camera['ellipsoid']) {
  24122. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24123. }
  24124. // Animations
  24125. appendAnimations(camera, serializationObject);
  24126. // Layer mask
  24127. serializationObject.layerMask = camera.layerMask;
  24128. return serializationObject;
  24129. };
  24130. serializeAnimation = function (animation) {
  24131. var serializationObject = {};
  24132. serializationObject.name = animation.name;
  24133. serializationObject.property = animation.targetProperty;
  24134. serializationObject.framePerSecond = animation.framePerSecond;
  24135. serializationObject.dataType = animation.dataType;
  24136. serializationObject.loopBehavior = animation.loopMode;
  24137. var dataType = animation.dataType;
  24138. serializationObject.keys = [];
  24139. var keys = animation.getKeys();
  24140. for (var index = 0; index < keys.length; index++) {
  24141. var animationKey = keys[index];
  24142. var key = {};
  24143. key.frame = animationKey.frame;
  24144. switch (dataType) {
  24145. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24146. key.values = [animationKey.value];
  24147. break;
  24148. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24149. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24150. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24151. key.values = animationKey.value.asArray();
  24152. break;
  24153. }
  24154. serializationObject.keys.push(key);
  24155. }
  24156. return serializationObject;
  24157. };
  24158. var serializeMultiMaterial = function (material) {
  24159. var serializationObject = {};
  24160. serializationObject.name = material.name;
  24161. serializationObject.id = material.id;
  24162. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24163. serializationObject.materials = [];
  24164. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24165. var subMat = material.subMaterials[matIndex];
  24166. if (subMat) {
  24167. serializationObject.materials.push(subMat.id);
  24168. }
  24169. else {
  24170. serializationObject.materials.push(null);
  24171. }
  24172. }
  24173. return serializationObject;
  24174. };
  24175. var serializeTexture;
  24176. var serializeMaterial = function (material) {
  24177. var serializationObject = {};
  24178. serializationObject.name = material.name;
  24179. serializationObject.ambient = material.ambientColor.asArray();
  24180. serializationObject.diffuse = material.diffuseColor.asArray();
  24181. serializationObject.specular = material.specularColor.asArray();
  24182. serializationObject.specularPower = material.specularPower;
  24183. serializationObject.emissive = material.emissiveColor.asArray();
  24184. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24185. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24186. serializationObject.alpha = material.alpha;
  24187. serializationObject.id = material.id;
  24188. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24189. serializationObject.backFaceCulling = material.backFaceCulling;
  24190. if (material.diffuseTexture) {
  24191. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24192. }
  24193. if (material.diffuseFresnelParameters) {
  24194. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24195. }
  24196. if (material.ambientTexture) {
  24197. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24198. }
  24199. if (material.opacityTexture) {
  24200. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24201. }
  24202. if (material.opacityFresnelParameters) {
  24203. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24204. }
  24205. if (material.reflectionTexture) {
  24206. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24207. }
  24208. if (material.reflectionFresnelParameters) {
  24209. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24210. }
  24211. if (material.emissiveTexture) {
  24212. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24213. }
  24214. if (material.lightmapTexture) {
  24215. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  24216. serializationObject.lightmapThreshold = material.lightmapThreshold;
  24217. }
  24218. if (material.emissiveFresnelParameters) {
  24219. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24220. }
  24221. if (material.specularTexture) {
  24222. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24223. }
  24224. if (material.bumpTexture) {
  24225. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24226. }
  24227. return serializationObject;
  24228. };
  24229. serializeTexture = function (texture) {
  24230. var serializationObject = {};
  24231. if (!texture.name) {
  24232. return null;
  24233. }
  24234. if (texture instanceof BABYLON.CubeTexture) {
  24235. serializationObject.name = texture.name;
  24236. serializationObject.hasAlpha = texture.hasAlpha;
  24237. serializationObject.isCube = true;
  24238. serializationObject.level = texture.level;
  24239. serializationObject.coordinatesMode = texture.coordinatesMode;
  24240. return serializationObject;
  24241. }
  24242. var index;
  24243. if (texture instanceof BABYLON.MirrorTexture) {
  24244. var mirrorTexture = texture;
  24245. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24246. serializationObject.renderList = [];
  24247. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24248. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24249. }
  24250. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24251. }
  24252. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24253. var renderTargetTexture = texture;
  24254. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24255. serializationObject.renderList = [];
  24256. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24257. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24258. }
  24259. }
  24260. var regularTexture = texture;
  24261. serializationObject.name = texture.name;
  24262. serializationObject.hasAlpha = texture.hasAlpha;
  24263. serializationObject.level = texture.level;
  24264. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24265. serializationObject.coordinatesMode = texture.coordinatesMode;
  24266. serializationObject.uOffset = regularTexture.uOffset;
  24267. serializationObject.vOffset = regularTexture.vOffset;
  24268. serializationObject.uScale = regularTexture.uScale;
  24269. serializationObject.vScale = regularTexture.vScale;
  24270. serializationObject.uAng = regularTexture.uAng;
  24271. serializationObject.vAng = regularTexture.vAng;
  24272. serializationObject.wAng = regularTexture.wAng;
  24273. serializationObject.wrapU = texture.wrapU;
  24274. serializationObject.wrapV = texture.wrapV;
  24275. // Animations
  24276. appendAnimations(texture, serializationObject);
  24277. return serializationObject;
  24278. };
  24279. var serializeSkeleton = function (skeleton) {
  24280. var serializationObject = {};
  24281. serializationObject.name = skeleton.name;
  24282. serializationObject.id = skeleton.id;
  24283. serializationObject.bones = [];
  24284. for (var index = 0; index < skeleton.bones.length; index++) {
  24285. var bone = skeleton.bones[index];
  24286. var serializedBone = {
  24287. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24288. name: bone.name,
  24289. matrix: bone.getLocalMatrix().toArray()
  24290. };
  24291. serializationObject.bones.push(serializedBone);
  24292. if (bone.animations && bone.animations.length > 0) {
  24293. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24294. }
  24295. }
  24296. return serializationObject;
  24297. };
  24298. var serializeParticleSystem = function (particleSystem) {
  24299. var serializationObject = {};
  24300. serializationObject.emitterId = particleSystem.emitter.id;
  24301. serializationObject.capacity = particleSystem.getCapacity();
  24302. if (particleSystem.particleTexture) {
  24303. serializationObject.textureName = particleSystem.particleTexture.name;
  24304. }
  24305. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24306. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24307. serializationObject.minSize = particleSystem.minSize;
  24308. serializationObject.maxSize = particleSystem.maxSize;
  24309. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24310. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24311. serializationObject.emitRate = particleSystem.emitRate;
  24312. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24313. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24314. serializationObject.gravity = particleSystem.gravity.asArray();
  24315. serializationObject.direction1 = particleSystem.direction1.asArray();
  24316. serializationObject.direction2 = particleSystem.direction2.asArray();
  24317. serializationObject.color1 = particleSystem.color1.asArray();
  24318. serializationObject.color2 = particleSystem.color2.asArray();
  24319. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24320. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24321. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24322. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24323. serializationObject.blendMode = particleSystem.blendMode;
  24324. return serializationObject;
  24325. };
  24326. var serializeLensFlareSystem = function (lensFlareSystem) {
  24327. var serializationObject = {};
  24328. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24329. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24330. serializationObject.flares = [];
  24331. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24332. var flare = lensFlareSystem.lensFlares[index];
  24333. serializationObject.flares.push({
  24334. size: flare.size,
  24335. position: flare.position,
  24336. color: flare.color.asArray(),
  24337. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24338. });
  24339. }
  24340. return serializationObject;
  24341. };
  24342. var serializeShadowGenerator = function (light) {
  24343. var serializationObject = {};
  24344. var shadowGenerator = light.getShadowGenerator();
  24345. serializationObject.lightId = light.id;
  24346. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24347. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24348. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24349. serializationObject.renderList = [];
  24350. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24351. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24352. serializationObject.renderList.push(mesh.id);
  24353. }
  24354. return serializationObject;
  24355. };
  24356. var serializedGeometries = [];
  24357. var serializeVertexData;
  24358. var serializeTorusKnot;
  24359. var serializePlane;
  24360. var serializeGround;
  24361. var serializeTorus;
  24362. var serializeCylinder;
  24363. var serializeSphere;
  24364. var serializeBox;
  24365. var serializeGeometry = function (geometry, serializationGeometries) {
  24366. if (serializedGeometries[geometry.id]) {
  24367. return;
  24368. }
  24369. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24370. serializationGeometries.boxes.push(serializeBox(geometry));
  24371. }
  24372. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24373. serializationGeometries.spheres.push(serializeSphere(geometry));
  24374. }
  24375. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24376. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24377. }
  24378. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24379. serializationGeometries.toruses.push(serializeTorus(geometry));
  24380. }
  24381. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24382. serializationGeometries.grounds.push(serializeGround(geometry));
  24383. }
  24384. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24385. serializationGeometries.planes.push(serializePlane(geometry));
  24386. }
  24387. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24388. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24389. }
  24390. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24391. throw new Error("Unknown primitive type");
  24392. }
  24393. else {
  24394. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24395. }
  24396. serializedGeometries[geometry.id] = true;
  24397. };
  24398. var serializeGeometryBase = function (geometry) {
  24399. var serializationObject = {};
  24400. serializationObject.id = geometry.id;
  24401. if (BABYLON.Tags.HasTags(geometry)) {
  24402. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24403. }
  24404. return serializationObject;
  24405. };
  24406. serializeVertexData = function (vertexData) {
  24407. var serializationObject = serializeGeometryBase(vertexData);
  24408. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24409. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24410. }
  24411. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24412. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24413. }
  24414. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24415. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24416. }
  24417. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24418. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24419. }
  24420. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24421. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24422. }
  24423. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24424. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24425. }
  24426. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24427. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24428. }
  24429. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24430. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24431. }
  24432. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24433. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24434. }
  24435. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24436. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24437. serializationObject.matricesIndices._isExpanded = true;
  24438. }
  24439. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24440. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24441. }
  24442. serializationObject.indices = vertexData.getIndices();
  24443. return serializationObject;
  24444. };
  24445. var serializePrimitive = function (primitive) {
  24446. var serializationObject = serializeGeometryBase(primitive);
  24447. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24448. return serializationObject;
  24449. };
  24450. serializeBox = function (box) {
  24451. var serializationObject = serializePrimitive(box);
  24452. serializationObject.size = box.size;
  24453. return serializationObject;
  24454. };
  24455. serializeSphere = function (sphere) {
  24456. var serializationObject = serializePrimitive(sphere);
  24457. serializationObject.segments = sphere.segments;
  24458. serializationObject.diameter = sphere.diameter;
  24459. return serializationObject;
  24460. };
  24461. serializeCylinder = function (cylinder) {
  24462. var serializationObject = serializePrimitive(cylinder);
  24463. serializationObject.height = cylinder.height;
  24464. serializationObject.diameterTop = cylinder.diameterTop;
  24465. serializationObject.diameterBottom = cylinder.diameterBottom;
  24466. serializationObject.tessellation = cylinder.tessellation;
  24467. return serializationObject;
  24468. };
  24469. serializeTorus = function (torus) {
  24470. var serializationObject = serializePrimitive(torus);
  24471. serializationObject.diameter = torus.diameter;
  24472. serializationObject.thickness = torus.thickness;
  24473. serializationObject.tessellation = torus.tessellation;
  24474. return serializationObject;
  24475. };
  24476. serializeGround = function (ground) {
  24477. var serializationObject = serializePrimitive(ground);
  24478. serializationObject.width = ground.width;
  24479. serializationObject.height = ground.height;
  24480. serializationObject.subdivisions = ground.subdivisions;
  24481. return serializationObject;
  24482. };
  24483. serializePlane = function (plane) {
  24484. var serializationObject = serializePrimitive(plane);
  24485. serializationObject.size = plane.size;
  24486. return serializationObject;
  24487. };
  24488. serializeTorusKnot = function (torusKnot) {
  24489. var serializationObject = serializePrimitive(torusKnot);
  24490. serializationObject.radius = torusKnot.radius;
  24491. serializationObject.tube = torusKnot.tube;
  24492. serializationObject.radialSegments = torusKnot.radialSegments;
  24493. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24494. serializationObject.p = torusKnot.p;
  24495. serializationObject.q = torusKnot.q;
  24496. return serializationObject;
  24497. };
  24498. var serializeMesh = function (mesh, serializationScene) {
  24499. var serializationObject = {};
  24500. serializationObject.name = mesh.name;
  24501. serializationObject.id = mesh.id;
  24502. if (BABYLON.Tags.HasTags(mesh)) {
  24503. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24504. }
  24505. serializationObject.position = mesh.position.asArray();
  24506. if (mesh.rotationQuaternion) {
  24507. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24508. }
  24509. else if (mesh.rotation) {
  24510. serializationObject.rotation = mesh.rotation.asArray();
  24511. }
  24512. serializationObject.scaling = mesh.scaling.asArray();
  24513. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24514. serializationObject.isEnabled = mesh.isEnabled();
  24515. serializationObject.isVisible = mesh.isVisible;
  24516. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24517. serializationObject.pickable = mesh.isPickable;
  24518. serializationObject.receiveShadows = mesh.receiveShadows;
  24519. serializationObject.billboardMode = mesh.billboardMode;
  24520. serializationObject.visibility = mesh.visibility;
  24521. serializationObject.checkCollisions = mesh.checkCollisions;
  24522. // Parent
  24523. if (mesh.parent) {
  24524. serializationObject.parentId = mesh.parent.id;
  24525. }
  24526. // Geometry
  24527. var geometry = mesh._geometry;
  24528. if (geometry) {
  24529. var geometryId = geometry.id;
  24530. serializationObject.geometryId = geometryId;
  24531. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24532. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  24533. serializeGeometry(geometry, serializationScene.geometries);
  24534. }
  24535. // SubMeshes
  24536. serializationObject.subMeshes = [];
  24537. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24538. var subMesh = mesh.subMeshes[subIndex];
  24539. serializationObject.subMeshes.push({
  24540. materialIndex: subMesh.materialIndex,
  24541. verticesStart: subMesh.verticesStart,
  24542. verticesCount: subMesh.verticesCount,
  24543. indexStart: subMesh.indexStart,
  24544. indexCount: subMesh.indexCount
  24545. });
  24546. }
  24547. }
  24548. // Material
  24549. if (mesh.material) {
  24550. serializationObject.materialId = mesh.material.id;
  24551. }
  24552. else {
  24553. mesh.material = null;
  24554. }
  24555. // Skeleton
  24556. if (mesh.skeleton) {
  24557. serializationObject.skeletonId = mesh.skeleton.id;
  24558. }
  24559. // Physics
  24560. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24561. serializationObject.physicsMass = mesh.getPhysicsMass();
  24562. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24563. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24564. switch (mesh.getPhysicsImpostor()) {
  24565. case BABYLON.PhysicsEngine.BoxImpostor:
  24566. serializationObject.physicsImpostor = 1;
  24567. break;
  24568. case BABYLON.PhysicsEngine.SphereImpostor:
  24569. serializationObject.physicsImpostor = 2;
  24570. break;
  24571. }
  24572. }
  24573. // Instances
  24574. serializationObject.instances = [];
  24575. for (var index = 0; index < mesh.instances.length; index++) {
  24576. var instance = mesh.instances[index];
  24577. var serializationInstance = {
  24578. name: instance.name,
  24579. position: instance.position,
  24580. rotation: instance.rotation,
  24581. rotationQuaternion: instance.rotationQuaternion,
  24582. scaling: instance.scaling
  24583. };
  24584. serializationObject.instances.push(serializationInstance);
  24585. // Animations
  24586. appendAnimations(instance, serializationInstance);
  24587. }
  24588. // Animations
  24589. appendAnimations(mesh, serializationObject);
  24590. // Layer mask
  24591. serializationObject.layerMask = mesh.layerMask;
  24592. return serializationObject;
  24593. };
  24594. var finalizeSingleMesh = function (mesh, serializationObject) {
  24595. //only works if the mesh is already loaded
  24596. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24597. //serialize material
  24598. if (mesh.material) {
  24599. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24600. serializationObject.materials = serializationObject.materials || [];
  24601. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24602. serializationObject.materials.push(serializeMaterial(mesh.material));
  24603. }
  24604. }
  24605. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24606. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24607. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24608. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24609. }
  24610. }
  24611. }
  24612. //serialize geometry
  24613. var geometry = mesh._geometry;
  24614. if (geometry) {
  24615. if (!serializationObject.geometries) {
  24616. serializationObject.geometries = {};
  24617. serializationObject.geometries.boxes = [];
  24618. serializationObject.geometries.spheres = [];
  24619. serializationObject.geometries.cylinders = [];
  24620. serializationObject.geometries.toruses = [];
  24621. serializationObject.geometries.grounds = [];
  24622. serializationObject.geometries.planes = [];
  24623. serializationObject.geometries.torusKnots = [];
  24624. serializationObject.geometries.vertexData = [];
  24625. }
  24626. serializeGeometry(geometry, serializationObject.geometries);
  24627. }
  24628. // Skeletons
  24629. if (mesh.skeleton) {
  24630. serializationObject.skeletons = serializationObject.skeletons || [];
  24631. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24632. }
  24633. //serialize the actual mesh
  24634. serializationObject.meshes = serializationObject.meshes || [];
  24635. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24636. }
  24637. };
  24638. var SceneSerializer = (function () {
  24639. function SceneSerializer() {
  24640. }
  24641. SceneSerializer.Serialize = function (scene) {
  24642. var serializationObject = {};
  24643. // Scene
  24644. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24645. serializationObject.autoClear = scene.autoClear;
  24646. serializationObject.clearColor = scene.clearColor.asArray();
  24647. serializationObject.ambientColor = scene.ambientColor.asArray();
  24648. serializationObject.gravity = scene.gravity.asArray();
  24649. // Fog
  24650. if (scene.fogMode && scene.fogMode !== 0) {
  24651. serializationObject.fogMode = scene.fogMode;
  24652. serializationObject.fogColor = scene.fogColor.asArray();
  24653. serializationObject.fogStart = scene.fogStart;
  24654. serializationObject.fogEnd = scene.fogEnd;
  24655. serializationObject.fogDensity = scene.fogDensity;
  24656. }
  24657. // Lights
  24658. serializationObject.lights = [];
  24659. var index;
  24660. var light;
  24661. for (index = 0; index < scene.lights.length; index++) {
  24662. light = scene.lights[index];
  24663. serializationObject.lights.push(serializeLight(light));
  24664. }
  24665. // Cameras
  24666. serializationObject.cameras = [];
  24667. for (index = 0; index < scene.cameras.length; index++) {
  24668. var camera = scene.cameras[index];
  24669. serializationObject.cameras.push(serializeCamera(camera));
  24670. }
  24671. if (scene.activeCamera) {
  24672. serializationObject.activeCameraID = scene.activeCamera.id;
  24673. }
  24674. // Materials
  24675. serializationObject.materials = [];
  24676. serializationObject.multiMaterials = [];
  24677. var material;
  24678. for (index = 0; index < scene.materials.length; index++) {
  24679. material = scene.materials[index];
  24680. serializationObject.materials.push(serializeMaterial(material));
  24681. }
  24682. // MultiMaterials
  24683. serializationObject.multiMaterials = [];
  24684. for (index = 0; index < scene.multiMaterials.length; index++) {
  24685. var multiMaterial = scene.multiMaterials[index];
  24686. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  24687. }
  24688. for (index = 0; index < scene.materials.length; index++) {
  24689. material = scene.materials[index];
  24690. if (material instanceof BABYLON.StandardMaterial) {
  24691. serializationObject.materials.push(serializeMaterial(material));
  24692. }
  24693. else if (material instanceof BABYLON.MultiMaterial) {
  24694. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24695. }
  24696. }
  24697. // Skeletons
  24698. serializationObject.skeletons = [];
  24699. for (index = 0; index < scene.skeletons.length; index++) {
  24700. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24701. }
  24702. // Geometries
  24703. serializationObject.geometries = {};
  24704. serializationObject.geometries.boxes = [];
  24705. serializationObject.geometries.spheres = [];
  24706. serializationObject.geometries.cylinders = [];
  24707. serializationObject.geometries.toruses = [];
  24708. serializationObject.geometries.grounds = [];
  24709. serializationObject.geometries.planes = [];
  24710. serializationObject.geometries.torusKnots = [];
  24711. serializationObject.geometries.vertexData = [];
  24712. serializedGeometries = [];
  24713. var geometries = scene.getGeometries();
  24714. for (index = 0; index < geometries.length; index++) {
  24715. var geometry = geometries[index];
  24716. if (geometry.isReady()) {
  24717. serializeGeometry(geometry, serializationObject.geometries);
  24718. }
  24719. }
  24720. // Meshes
  24721. serializationObject.meshes = [];
  24722. for (index = 0; index < scene.meshes.length; index++) {
  24723. var abstractMesh = scene.meshes[index];
  24724. if (abstractMesh instanceof BABYLON.Mesh) {
  24725. var mesh = abstractMesh;
  24726. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24727. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24728. }
  24729. }
  24730. }
  24731. // Particles Systems
  24732. serializationObject.particleSystems = [];
  24733. for (index = 0; index < scene.particleSystems.length; index++) {
  24734. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24735. }
  24736. // Lens flares
  24737. serializationObject.lensFlareSystems = [];
  24738. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24739. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24740. }
  24741. // Shadows
  24742. serializationObject.shadowGenerators = [];
  24743. for (index = 0; index < scene.lights.length; index++) {
  24744. light = scene.lights[index];
  24745. if (light.getShadowGenerator()) {
  24746. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24747. }
  24748. }
  24749. return serializationObject;
  24750. };
  24751. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24752. if (withParents === void 0) { withParents = false; }
  24753. if (withChildren === void 0) { withChildren = false; }
  24754. var serializationObject = {};
  24755. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24756. if (withParents || withChildren) {
  24757. //deliberate for loop! not for each, appended should be processed as well.
  24758. for (var i = 0; i < toSerialize.length; ++i) {
  24759. if (withChildren) {
  24760. toSerialize[i].getDescendants().forEach(function (node) {
  24761. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24762. toSerialize.push(node);
  24763. }
  24764. });
  24765. }
  24766. //make sure the array doesn't contain the object already
  24767. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24768. toSerialize.push(toSerialize[i].parent);
  24769. }
  24770. }
  24771. }
  24772. toSerialize.forEach(function (mesh) {
  24773. finalizeSingleMesh(mesh, serializationObject);
  24774. });
  24775. return serializationObject;
  24776. };
  24777. return SceneSerializer;
  24778. })();
  24779. BABYLON.SceneSerializer = SceneSerializer;
  24780. })(BABYLON || (BABYLON = {}));
  24781. var BABYLON;
  24782. (function (BABYLON) {
  24783. // Unique ID when we import meshes from Babylon to CSG
  24784. var currentCSGMeshId = 0;
  24785. // # class Vertex
  24786. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24787. // one to provide additional features like texture coordinates and vertex
  24788. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24789. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24790. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24791. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24792. // is not used anywhere else.
  24793. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24794. var Vertex = (function () {
  24795. function Vertex(pos, normal, uv) {
  24796. this.pos = pos;
  24797. this.normal = normal;
  24798. this.uv = uv;
  24799. }
  24800. Vertex.prototype.clone = function () {
  24801. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24802. };
  24803. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24804. // orientation of a polygon is flipped.
  24805. Vertex.prototype.flip = function () {
  24806. this.normal = this.normal.scale(-1);
  24807. };
  24808. // Create a new vertex between this vertex and `other` by linearly
  24809. // interpolating all properties using a parameter of `t`. Subclasses should
  24810. // override this to interpolate additional properties.
  24811. Vertex.prototype.interpolate = function (other, t) {
  24812. 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));
  24813. };
  24814. return Vertex;
  24815. })();
  24816. // # class Plane
  24817. // Represents a plane in 3D space.
  24818. var Plane = (function () {
  24819. function Plane(normal, w) {
  24820. this.normal = normal;
  24821. this.w = w;
  24822. }
  24823. Plane.FromPoints = function (a, b, c) {
  24824. var v0 = c.subtract(a);
  24825. var v1 = b.subtract(a);
  24826. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24827. return null;
  24828. }
  24829. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24830. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24831. };
  24832. Plane.prototype.clone = function () {
  24833. return new Plane(this.normal.clone(), this.w);
  24834. };
  24835. Plane.prototype.flip = function () {
  24836. this.normal.scaleInPlace(-1);
  24837. this.w = -this.w;
  24838. };
  24839. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24840. // fragments in the appropriate lists. Coplanar polygons go into either
  24841. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24842. // respect to this plane. Polygons in front or in back of this plane go into
  24843. // either `front` or `back`.
  24844. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24845. var COPLANAR = 0;
  24846. var FRONT = 1;
  24847. var BACK = 2;
  24848. var SPANNING = 3;
  24849. // Classify each point as well as the entire polygon into one of the above
  24850. // four classes.
  24851. var polygonType = 0;
  24852. var types = [];
  24853. for (var i = 0; i < polygon.vertices.length; i++) {
  24854. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24855. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24856. polygonType |= type;
  24857. types.push(type);
  24858. }
  24859. // Put the polygon in the correct list, splitting it when necessary.
  24860. switch (polygonType) {
  24861. case COPLANAR:
  24862. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24863. break;
  24864. case FRONT:
  24865. front.push(polygon);
  24866. break;
  24867. case BACK:
  24868. back.push(polygon);
  24869. break;
  24870. case SPANNING:
  24871. var f = [], b = [];
  24872. for (i = 0; i < polygon.vertices.length; i++) {
  24873. var j = (i + 1) % polygon.vertices.length;
  24874. var ti = types[i], tj = types[j];
  24875. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24876. if (ti != BACK)
  24877. f.push(vi);
  24878. if (ti != FRONT)
  24879. b.push(ti != BACK ? vi.clone() : vi);
  24880. if ((ti | tj) == SPANNING) {
  24881. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24882. var v = vi.interpolate(vj, t);
  24883. f.push(v);
  24884. b.push(v.clone());
  24885. }
  24886. }
  24887. if (f.length >= 3) {
  24888. var poly = new Polygon(f, polygon.shared);
  24889. if (poly.plane)
  24890. front.push(poly);
  24891. }
  24892. if (b.length >= 3) {
  24893. poly = new Polygon(b, polygon.shared);
  24894. if (poly.plane)
  24895. back.push(poly);
  24896. }
  24897. break;
  24898. }
  24899. };
  24900. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24901. // point is on the plane.
  24902. Plane.EPSILON = 1e-5;
  24903. return Plane;
  24904. })();
  24905. // # class Polygon
  24906. // Represents a convex polygon. The vertices used to initialize a polygon must
  24907. // be coplanar and form a convex loop.
  24908. //
  24909. // Each convex polygon has a `shared` property, which is shared between all
  24910. // polygons that are clones of each other or were split from the same polygon.
  24911. // This can be used to define per-polygon properties (such as surface color).
  24912. var Polygon = (function () {
  24913. function Polygon(vertices, shared) {
  24914. this.vertices = vertices;
  24915. this.shared = shared;
  24916. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24917. }
  24918. Polygon.prototype.clone = function () {
  24919. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24920. return new Polygon(vertices, this.shared);
  24921. };
  24922. Polygon.prototype.flip = function () {
  24923. this.vertices.reverse().map(function (v) { v.flip(); });
  24924. this.plane.flip();
  24925. };
  24926. return Polygon;
  24927. })();
  24928. // # class Node
  24929. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24930. // by picking a polygon to split along. That polygon (and all other coplanar
  24931. // polygons) are added directly to that node and the other polygons are added to
  24932. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24933. // no distinction between internal and leaf nodes.
  24934. var Node = (function () {
  24935. function Node(polygons) {
  24936. this.plane = null;
  24937. this.front = null;
  24938. this.back = null;
  24939. this.polygons = [];
  24940. if (polygons) {
  24941. this.build(polygons);
  24942. }
  24943. }
  24944. Node.prototype.clone = function () {
  24945. var node = new Node();
  24946. node.plane = this.plane && this.plane.clone();
  24947. node.front = this.front && this.front.clone();
  24948. node.back = this.back && this.back.clone();
  24949. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24950. return node;
  24951. };
  24952. // Convert solid space to empty space and empty space to solid space.
  24953. Node.prototype.invert = function () {
  24954. for (var i = 0; i < this.polygons.length; i++) {
  24955. this.polygons[i].flip();
  24956. }
  24957. if (this.plane) {
  24958. this.plane.flip();
  24959. }
  24960. if (this.front) {
  24961. this.front.invert();
  24962. }
  24963. if (this.back) {
  24964. this.back.invert();
  24965. }
  24966. var temp = this.front;
  24967. this.front = this.back;
  24968. this.back = temp;
  24969. };
  24970. // Recursively remove all polygons in `polygons` that are inside this BSP
  24971. // tree.
  24972. Node.prototype.clipPolygons = function (polygons) {
  24973. if (!this.plane)
  24974. return polygons.slice();
  24975. var front = [], back = [];
  24976. for (var i = 0; i < polygons.length; i++) {
  24977. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24978. }
  24979. if (this.front) {
  24980. front = this.front.clipPolygons(front);
  24981. }
  24982. if (this.back) {
  24983. back = this.back.clipPolygons(back);
  24984. }
  24985. else {
  24986. back = [];
  24987. }
  24988. return front.concat(back);
  24989. };
  24990. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24991. // `bsp`.
  24992. Node.prototype.clipTo = function (bsp) {
  24993. this.polygons = bsp.clipPolygons(this.polygons);
  24994. if (this.front)
  24995. this.front.clipTo(bsp);
  24996. if (this.back)
  24997. this.back.clipTo(bsp);
  24998. };
  24999. // Return a list of all polygons in this BSP tree.
  25000. Node.prototype.allPolygons = function () {
  25001. var polygons = this.polygons.slice();
  25002. if (this.front)
  25003. polygons = polygons.concat(this.front.allPolygons());
  25004. if (this.back)
  25005. polygons = polygons.concat(this.back.allPolygons());
  25006. return polygons;
  25007. };
  25008. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  25009. // new polygons are filtered down to the bottom of the tree and become new
  25010. // nodes there. Each set of polygons is partitioned using the first polygon
  25011. // (no heuristic is used to pick a good split).
  25012. Node.prototype.build = function (polygons) {
  25013. if (!polygons.length)
  25014. return;
  25015. if (!this.plane)
  25016. this.plane = polygons[0].plane.clone();
  25017. var front = [], back = [];
  25018. for (var i = 0; i < polygons.length; i++) {
  25019. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  25020. }
  25021. if (front.length) {
  25022. if (!this.front)
  25023. this.front = new Node();
  25024. this.front.build(front);
  25025. }
  25026. if (back.length) {
  25027. if (!this.back)
  25028. this.back = new Node();
  25029. this.back.build(back);
  25030. }
  25031. };
  25032. return Node;
  25033. })();
  25034. var CSG = (function () {
  25035. function CSG() {
  25036. this.polygons = new Array();
  25037. }
  25038. // Convert BABYLON.Mesh to BABYLON.CSG
  25039. CSG.FromMesh = function (mesh) {
  25040. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25041. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25042. if (mesh instanceof BABYLON.Mesh) {
  25043. mesh.computeWorldMatrix(true);
  25044. matrix = mesh.getWorldMatrix();
  25045. meshPosition = mesh.position.clone();
  25046. meshRotation = mesh.rotation.clone();
  25047. if (mesh.rotationQuaternion) {
  25048. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25049. }
  25050. meshScaling = mesh.scaling.clone();
  25051. }
  25052. else {
  25053. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25054. }
  25055. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25056. var subMeshes = mesh.subMeshes;
  25057. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25058. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25059. vertices = [];
  25060. for (var j = 0; j < 3; j++) {
  25061. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25062. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25063. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25064. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25065. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25066. vertex = new Vertex(position, normal, uv);
  25067. vertices.push(vertex);
  25068. }
  25069. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25070. // To handle the case of degenerated triangle
  25071. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25072. if (polygon.plane)
  25073. polygons.push(polygon);
  25074. }
  25075. }
  25076. var csg = CSG.FromPolygons(polygons);
  25077. csg.matrix = matrix;
  25078. csg.position = meshPosition;
  25079. csg.rotation = meshRotation;
  25080. csg.scaling = meshScaling;
  25081. csg.rotationQuaternion = meshRotationQuaternion;
  25082. currentCSGMeshId++;
  25083. return csg;
  25084. };
  25085. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25086. CSG.FromPolygons = function (polygons) {
  25087. var csg = new CSG();
  25088. csg.polygons = polygons;
  25089. return csg;
  25090. };
  25091. CSG.prototype.clone = function () {
  25092. var csg = new CSG();
  25093. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25094. csg.copyTransformAttributes(this);
  25095. return csg;
  25096. };
  25097. CSG.prototype.toPolygons = function () {
  25098. return this.polygons;
  25099. };
  25100. CSG.prototype.union = function (csg) {
  25101. var a = new Node(this.clone().polygons);
  25102. var b = new Node(csg.clone().polygons);
  25103. a.clipTo(b);
  25104. b.clipTo(a);
  25105. b.invert();
  25106. b.clipTo(a);
  25107. b.invert();
  25108. a.build(b.allPolygons());
  25109. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25110. };
  25111. CSG.prototype.unionInPlace = function (csg) {
  25112. var a = new Node(this.polygons);
  25113. var b = new Node(csg.polygons);
  25114. a.clipTo(b);
  25115. b.clipTo(a);
  25116. b.invert();
  25117. b.clipTo(a);
  25118. b.invert();
  25119. a.build(b.allPolygons());
  25120. this.polygons = a.allPolygons();
  25121. };
  25122. CSG.prototype.subtract = function (csg) {
  25123. var a = new Node(this.clone().polygons);
  25124. var b = new Node(csg.clone().polygons);
  25125. a.invert();
  25126. a.clipTo(b);
  25127. b.clipTo(a);
  25128. b.invert();
  25129. b.clipTo(a);
  25130. b.invert();
  25131. a.build(b.allPolygons());
  25132. a.invert();
  25133. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25134. };
  25135. CSG.prototype.subtractInPlace = function (csg) {
  25136. var a = new Node(this.polygons);
  25137. var b = new Node(csg.polygons);
  25138. a.invert();
  25139. a.clipTo(b);
  25140. b.clipTo(a);
  25141. b.invert();
  25142. b.clipTo(a);
  25143. b.invert();
  25144. a.build(b.allPolygons());
  25145. a.invert();
  25146. this.polygons = a.allPolygons();
  25147. };
  25148. CSG.prototype.intersect = function (csg) {
  25149. var a = new Node(this.clone().polygons);
  25150. var b = new Node(csg.clone().polygons);
  25151. a.invert();
  25152. b.clipTo(a);
  25153. b.invert();
  25154. a.clipTo(b);
  25155. b.clipTo(a);
  25156. a.build(b.allPolygons());
  25157. a.invert();
  25158. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25159. };
  25160. CSG.prototype.intersectInPlace = function (csg) {
  25161. var a = new Node(this.polygons);
  25162. var b = new Node(csg.polygons);
  25163. a.invert();
  25164. b.clipTo(a);
  25165. b.invert();
  25166. a.clipTo(b);
  25167. b.clipTo(a);
  25168. a.build(b.allPolygons());
  25169. a.invert();
  25170. this.polygons = a.allPolygons();
  25171. };
  25172. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25173. // not modified.
  25174. CSG.prototype.inverse = function () {
  25175. var csg = this.clone();
  25176. csg.inverseInPlace();
  25177. return csg;
  25178. };
  25179. CSG.prototype.inverseInPlace = function () {
  25180. this.polygons.map(function (p) { p.flip(); });
  25181. };
  25182. // This is used to keep meshes transformations so they can be restored
  25183. // when we build back a Babylon Mesh
  25184. // NB : All CSG operations are performed in world coordinates
  25185. CSG.prototype.copyTransformAttributes = function (csg) {
  25186. this.matrix = csg.matrix;
  25187. this.position = csg.position;
  25188. this.rotation = csg.rotation;
  25189. this.scaling = csg.scaling;
  25190. this.rotationQuaternion = csg.rotationQuaternion;
  25191. return this;
  25192. };
  25193. // Build Raw mesh from CSG
  25194. // Coordinates here are in world space
  25195. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25196. var matrix = this.matrix.clone();
  25197. matrix.invert();
  25198. 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;
  25199. if (keepSubMeshes) {
  25200. // Sort Polygons, since subMeshes are indices range
  25201. polygons.sort(function (a, b) {
  25202. if (a.shared.meshId === b.shared.meshId) {
  25203. return a.shared.subMeshId - b.shared.subMeshId;
  25204. }
  25205. else {
  25206. return a.shared.meshId - b.shared.meshId;
  25207. }
  25208. });
  25209. }
  25210. for (var i = 0, il = polygons.length; i < il; i++) {
  25211. polygon = polygons[i];
  25212. // Building SubMeshes
  25213. if (!subMesh_dict[polygon.shared.meshId]) {
  25214. subMesh_dict[polygon.shared.meshId] = {};
  25215. }
  25216. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25217. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25218. indexStart: +Infinity,
  25219. indexEnd: -Infinity,
  25220. materialIndex: polygon.shared.materialIndex
  25221. };
  25222. }
  25223. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25224. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25225. polygonIndices[0] = 0;
  25226. polygonIndices[1] = j - 1;
  25227. polygonIndices[2] = j;
  25228. for (var k = 0; k < 3; k++) {
  25229. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25230. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25231. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25232. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25233. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25234. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25235. // Check if 2 points can be merged
  25236. if (!(typeof vertex_idx !== 'undefined' &&
  25237. normals[vertex_idx * 3] === localNormal.x &&
  25238. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25239. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25240. uvs[vertex_idx * 2] === uv.x &&
  25241. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25242. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25243. uvs.push(uv.x, uv.y);
  25244. normals.push(normal.x, normal.y, normal.z);
  25245. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25246. }
  25247. indices.push(vertex_idx);
  25248. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25249. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25250. currentIndex++;
  25251. }
  25252. }
  25253. }
  25254. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25255. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25256. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25257. mesh.setIndices(indices);
  25258. if (keepSubMeshes) {
  25259. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25260. var materialIndexOffset = 0, materialMaxIndex;
  25261. mesh.subMeshes.length = 0;
  25262. for (var m in subMesh_dict) {
  25263. materialMaxIndex = -1;
  25264. for (var sm in subMesh_dict[m]) {
  25265. subMesh_obj = subMesh_dict[m][sm];
  25266. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25267. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25268. }
  25269. materialIndexOffset += ++materialMaxIndex;
  25270. }
  25271. }
  25272. return mesh;
  25273. };
  25274. // Build Mesh from CSG taking material and transforms into account
  25275. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25276. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25277. mesh.material = material;
  25278. mesh.position.copyFrom(this.position);
  25279. mesh.rotation.copyFrom(this.rotation);
  25280. if (this.rotationQuaternion) {
  25281. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25282. }
  25283. mesh.scaling.copyFrom(this.scaling);
  25284. mesh.computeWorldMatrix(true);
  25285. return mesh;
  25286. };
  25287. return CSG;
  25288. })();
  25289. BABYLON.CSG = CSG;
  25290. })(BABYLON || (BABYLON = {}));
  25291. var BABYLON;
  25292. (function (BABYLON) {
  25293. var VRDistortionCorrectionPostProcess = (function (_super) {
  25294. __extends(VRDistortionCorrectionPostProcess, _super);
  25295. //ANY
  25296. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25297. var _this = this;
  25298. _super.call(this, name, "vrDistortionCorrection", [
  25299. 'LensCenter',
  25300. 'Scale',
  25301. 'ScaleIn',
  25302. 'HmdWarpParam'
  25303. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25304. this._isRightEye = isRightEye;
  25305. this._distortionFactors = vrMetrics.distortionK;
  25306. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25307. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25308. this.onSizeChanged = function () {
  25309. _this.aspectRatio = _this.width * .5 / _this.height;
  25310. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25311. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25312. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25313. };
  25314. this.onApply = function (effect) {
  25315. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25316. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25317. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25318. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25319. };
  25320. }
  25321. return VRDistortionCorrectionPostProcess;
  25322. })(BABYLON.PostProcess);
  25323. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25324. })(BABYLON || (BABYLON = {}));
  25325. // Mainly based on these 2 articles :
  25326. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  25327. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25328. var BABYLON;
  25329. (function (BABYLON) {
  25330. (function (JoystickAxis) {
  25331. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25332. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25333. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25334. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25335. var JoystickAxis = BABYLON.JoystickAxis;
  25336. var VirtualJoystick = (function () {
  25337. function VirtualJoystick(leftJoystick) {
  25338. var _this = this;
  25339. if (leftJoystick) {
  25340. this._leftJoystick = true;
  25341. }
  25342. else {
  25343. this._leftJoystick = false;
  25344. }
  25345. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25346. VirtualJoystick._globalJoystickIndex++;
  25347. // By default left & right arrow keys are moving the X
  25348. // and up & down keys are moving the Y
  25349. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25350. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25351. this.reverseLeftRight = false;
  25352. this.reverseUpDown = false;
  25353. // collections of pointers
  25354. this._touches = new BABYLON.SmartCollection();
  25355. this.deltaPosition = BABYLON.Vector3.Zero();
  25356. this._joystickSensibility = 25;
  25357. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25358. this._rotationSpeed = 25;
  25359. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25360. this._rotateOnAxisRelativeToMesh = false;
  25361. this._onResize = function (evt) {
  25362. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25363. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25364. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25365. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25366. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25367. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25368. };
  25369. // injecting a canvas element on top of the canvas 3D game
  25370. if (!VirtualJoystick.vjCanvas) {
  25371. window.addEventListener("resize", this._onResize, false);
  25372. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25373. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25374. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25375. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25376. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25377. VirtualJoystick.vjCanvas.style.width = "100%";
  25378. VirtualJoystick.vjCanvas.style.height = "100%";
  25379. VirtualJoystick.vjCanvas.style.position = "absolute";
  25380. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25381. VirtualJoystick.vjCanvas.style.top = "0px";
  25382. VirtualJoystick.vjCanvas.style.left = "0px";
  25383. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25384. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25385. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25386. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25387. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25388. document.body.appendChild(VirtualJoystick.vjCanvas);
  25389. }
  25390. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25391. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25392. this.pressed = false;
  25393. // default joystick color
  25394. this._joystickColor = "cyan";
  25395. this._joystickPointerID = -1;
  25396. // current joystick position
  25397. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25398. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25399. // origin joystick position
  25400. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25401. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25402. this._onPointerDownHandlerRef = function (evt) {
  25403. _this._onPointerDown(evt);
  25404. };
  25405. this._onPointerMoveHandlerRef = function (evt) {
  25406. _this._onPointerMove(evt);
  25407. };
  25408. this._onPointerOutHandlerRef = function (evt) {
  25409. _this._onPointerUp(evt);
  25410. };
  25411. this._onPointerUpHandlerRef = function (evt) {
  25412. _this._onPointerUp(evt);
  25413. };
  25414. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25415. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25416. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25417. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25418. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25419. evt.preventDefault(); // Disables system menu
  25420. }, false);
  25421. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25422. }
  25423. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25424. this._joystickSensibility = newJoystickSensibility;
  25425. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25426. };
  25427. VirtualJoystick.prototype._onPointerDown = function (e) {
  25428. var positionOnScreenCondition;
  25429. e.preventDefault();
  25430. if (this._leftJoystick === true) {
  25431. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25432. }
  25433. else {
  25434. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25435. }
  25436. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25437. // First contact will be dedicated to the virtual joystick
  25438. this._joystickPointerID = e.pointerId;
  25439. this._joystickPointerStartPos.x = e.clientX;
  25440. this._joystickPointerStartPos.y = e.clientY;
  25441. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25442. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25443. this._deltaJoystickVector.x = 0;
  25444. this._deltaJoystickVector.y = 0;
  25445. this.pressed = true;
  25446. this._touches.add(e.pointerId.toString(), e);
  25447. }
  25448. else {
  25449. // You can only trigger the action buttons with a joystick declared
  25450. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25451. this._action();
  25452. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25453. }
  25454. }
  25455. };
  25456. VirtualJoystick.prototype._onPointerMove = function (e) {
  25457. // If the current pointer is the one associated to the joystick (first touch contact)
  25458. if (this._joystickPointerID == e.pointerId) {
  25459. this._joystickPointerPos.x = e.clientX;
  25460. this._joystickPointerPos.y = e.clientY;
  25461. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25462. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25463. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25464. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25465. switch (this._axisTargetedByLeftAndRight) {
  25466. case JoystickAxis.X:
  25467. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25468. break;
  25469. case JoystickAxis.Y:
  25470. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25471. break;
  25472. case JoystickAxis.Z:
  25473. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25474. break;
  25475. }
  25476. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25477. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25478. switch (this._axisTargetedByUpAndDown) {
  25479. case JoystickAxis.X:
  25480. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25481. break;
  25482. case JoystickAxis.Y:
  25483. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25484. break;
  25485. case JoystickAxis.Z:
  25486. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25487. break;
  25488. }
  25489. }
  25490. else {
  25491. if (this._touches.item(e.pointerId.toString())) {
  25492. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25493. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25494. }
  25495. }
  25496. };
  25497. VirtualJoystick.prototype._onPointerUp = function (e) {
  25498. if (this._joystickPointerID == e.pointerId) {
  25499. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25500. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25501. this._joystickPointerID = -1;
  25502. this.pressed = false;
  25503. }
  25504. else {
  25505. var touch = this._touches.item(e.pointerId.toString());
  25506. if (touch) {
  25507. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25508. }
  25509. }
  25510. this._deltaJoystickVector.x = 0;
  25511. this._deltaJoystickVector.y = 0;
  25512. this._touches.remove(e.pointerId.toString());
  25513. };
  25514. /**
  25515. * Change the color of the virtual joystick
  25516. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25517. */
  25518. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25519. this._joystickColor = newColor;
  25520. };
  25521. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25522. this._action = action;
  25523. };
  25524. // Define which axis you'd like to control for left & right
  25525. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25526. switch (axis) {
  25527. case JoystickAxis.X:
  25528. case JoystickAxis.Y:
  25529. case JoystickAxis.Z:
  25530. this._axisTargetedByLeftAndRight = axis;
  25531. break;
  25532. default:
  25533. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25534. break;
  25535. }
  25536. };
  25537. // Define which axis you'd like to control for up & down
  25538. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25539. switch (axis) {
  25540. case JoystickAxis.X:
  25541. case JoystickAxis.Y:
  25542. case JoystickAxis.Z:
  25543. this._axisTargetedByUpAndDown = axis;
  25544. break;
  25545. default:
  25546. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25547. break;
  25548. }
  25549. };
  25550. VirtualJoystick.prototype._clearCanvas = function () {
  25551. if (this._leftJoystick) {
  25552. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25553. }
  25554. else {
  25555. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25556. }
  25557. };
  25558. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25559. var _this = this;
  25560. if (this.pressed) {
  25561. this._touches.forEach(function (touch) {
  25562. if (touch.pointerId === _this._joystickPointerID) {
  25563. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25564. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25565. VirtualJoystick.vjCanvasContext.beginPath();
  25566. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25567. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25568. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25569. VirtualJoystick.vjCanvasContext.stroke();
  25570. VirtualJoystick.vjCanvasContext.closePath();
  25571. VirtualJoystick.vjCanvasContext.beginPath();
  25572. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25573. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25574. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25575. VirtualJoystick.vjCanvasContext.stroke();
  25576. VirtualJoystick.vjCanvasContext.closePath();
  25577. VirtualJoystick.vjCanvasContext.beginPath();
  25578. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25579. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25580. VirtualJoystick.vjCanvasContext.stroke();
  25581. VirtualJoystick.vjCanvasContext.closePath();
  25582. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25583. }
  25584. else {
  25585. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25586. VirtualJoystick.vjCanvasContext.beginPath();
  25587. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25588. VirtualJoystick.vjCanvasContext.beginPath();
  25589. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25590. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25591. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25592. VirtualJoystick.vjCanvasContext.stroke();
  25593. VirtualJoystick.vjCanvasContext.closePath();
  25594. touch.prevX = touch.x;
  25595. touch.prevY = touch.y;
  25596. }
  25597. ;
  25598. });
  25599. }
  25600. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25601. };
  25602. VirtualJoystick.prototype.releaseCanvas = function () {
  25603. if (VirtualJoystick.vjCanvas) {
  25604. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25605. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25606. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25607. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25608. window.removeEventListener("resize", this._onResize);
  25609. document.body.removeChild(VirtualJoystick.vjCanvas);
  25610. VirtualJoystick.vjCanvas = null;
  25611. }
  25612. };
  25613. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25614. VirtualJoystick._globalJoystickIndex = 0;
  25615. return VirtualJoystick;
  25616. })();
  25617. BABYLON.VirtualJoystick = VirtualJoystick;
  25618. })(BABYLON || (BABYLON = {}));
  25619. var BABYLON;
  25620. (function (BABYLON) {
  25621. // We're mainly based on the logic defined into the FreeCamera code
  25622. var VirtualJoysticksCamera = (function (_super) {
  25623. __extends(VirtualJoysticksCamera, _super);
  25624. function VirtualJoysticksCamera(name, position, scene) {
  25625. _super.call(this, name, position, scene);
  25626. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25627. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25628. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25629. this._leftjoystick.setJoystickSensibility(0.15);
  25630. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25631. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25632. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25633. this._rightjoystick.reverseUpDown = true;
  25634. this._rightjoystick.setJoystickSensibility(0.05);
  25635. this._rightjoystick.setJoystickColor("yellow");
  25636. }
  25637. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25638. return this._leftjoystick;
  25639. };
  25640. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25641. return this._rightjoystick;
  25642. };
  25643. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25644. var speed = this._computeLocalCameraSpeed() * 50;
  25645. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25646. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25647. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25648. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25649. if (!this._leftjoystick.pressed) {
  25650. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25651. }
  25652. if (!this._rightjoystick.pressed) {
  25653. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25654. }
  25655. _super.prototype._checkInputs.call(this);
  25656. };
  25657. VirtualJoysticksCamera.prototype.dispose = function () {
  25658. this._leftjoystick.releaseCanvas();
  25659. _super.prototype.dispose.call(this);
  25660. };
  25661. return VirtualJoysticksCamera;
  25662. })(BABYLON.FreeCamera);
  25663. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25664. })(BABYLON || (BABYLON = {}));
  25665. var BABYLON;
  25666. (function (BABYLON) {
  25667. var ShaderMaterial = (function (_super) {
  25668. __extends(ShaderMaterial, _super);
  25669. function ShaderMaterial(name, scene, shaderPath, options) {
  25670. _super.call(this, name, scene);
  25671. this._textures = new Array();
  25672. this._floats = new Array();
  25673. this._floatsArrays = {};
  25674. this._colors3 = new Array();
  25675. this._colors4 = new Array();
  25676. this._vectors2 = new Array();
  25677. this._vectors3 = new Array();
  25678. this._vectors4 = new Array();
  25679. this._matrices = new Array();
  25680. this._matrices3x3 = new Array();
  25681. this._matrices2x2 = new Array();
  25682. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25683. this._shaderPath = shaderPath;
  25684. options.needAlphaBlending = options.needAlphaBlending || false;
  25685. options.needAlphaTesting = options.needAlphaTesting || false;
  25686. options.attributes = options.attributes || ["position", "normal", "uv"];
  25687. options.uniforms = options.uniforms || ["worldViewProjection"];
  25688. options.samplers = options.samplers || [];
  25689. options.defines = options.defines || [];
  25690. this._options = options;
  25691. }
  25692. ShaderMaterial.prototype.needAlphaBlending = function () {
  25693. return this._options.needAlphaBlending;
  25694. };
  25695. ShaderMaterial.prototype.needAlphaTesting = function () {
  25696. return this._options.needAlphaTesting;
  25697. };
  25698. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25699. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25700. this._options.uniforms.push(uniformName);
  25701. }
  25702. };
  25703. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25704. if (this._options.samplers.indexOf(name) === -1) {
  25705. this._options.samplers.push(name);
  25706. }
  25707. this._textures[name] = texture;
  25708. return this;
  25709. };
  25710. ShaderMaterial.prototype.setFloat = function (name, value) {
  25711. this._checkUniform(name);
  25712. this._floats[name] = value;
  25713. return this;
  25714. };
  25715. ShaderMaterial.prototype.setFloats = function (name, value) {
  25716. this._checkUniform(name);
  25717. this._floatsArrays[name] = value;
  25718. return this;
  25719. };
  25720. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25721. this._checkUniform(name);
  25722. this._colors3[name] = value;
  25723. return this;
  25724. };
  25725. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25726. this._checkUniform(name);
  25727. this._colors4[name] = value;
  25728. return this;
  25729. };
  25730. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25731. this._checkUniform(name);
  25732. this._vectors2[name] = value;
  25733. return this;
  25734. };
  25735. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25736. this._checkUniform(name);
  25737. this._vectors3[name] = value;
  25738. return this;
  25739. };
  25740. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25741. this._checkUniform(name);
  25742. this._vectors4[name] = value;
  25743. return this;
  25744. };
  25745. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25746. this._checkUniform(name);
  25747. this._matrices[name] = value;
  25748. return this;
  25749. };
  25750. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25751. this._checkUniform(name);
  25752. this._matrices3x3[name] = value;
  25753. return this;
  25754. };
  25755. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25756. this._checkUniform(name);
  25757. this._matrices2x2[name] = value;
  25758. return this;
  25759. };
  25760. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25761. var scene = this.getScene();
  25762. var engine = scene.getEngine();
  25763. if (!this.checkReadyOnEveryCall) {
  25764. if (this._renderId === scene.getRenderId()) {
  25765. return true;
  25766. }
  25767. }
  25768. // Instances
  25769. var defines = [];
  25770. var fallbacks = new BABYLON.EffectFallbacks();
  25771. if (useInstances) {
  25772. defines.push("#define INSTANCES");
  25773. }
  25774. for (var index = 0; index < this._options.defines.length; index++) {
  25775. defines.push(this._options.defines[index]);
  25776. }
  25777. // Bones
  25778. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25779. defines.push("#define BONES");
  25780. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25781. defines.push("#define BONES4");
  25782. fallbacks.addFallback(0, "BONES4");
  25783. }
  25784. // Alpha test
  25785. if (engine.getAlphaTesting()) {
  25786. defines.push("#define ALPHATEST");
  25787. }
  25788. var previousEffect = this._effect;
  25789. var join = defines.join("\n");
  25790. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25791. if (!this._effect.isReady()) {
  25792. return false;
  25793. }
  25794. if (previousEffect !== this._effect) {
  25795. scene.resetCachedMaterial();
  25796. }
  25797. this._renderId = scene.getRenderId();
  25798. return true;
  25799. };
  25800. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25801. var scene = this.getScene();
  25802. if (this._options.uniforms.indexOf("world") !== -1) {
  25803. this._effect.setMatrix("world", world);
  25804. }
  25805. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25806. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25807. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25808. }
  25809. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25810. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25811. }
  25812. };
  25813. ShaderMaterial.prototype.bind = function (world, mesh) {
  25814. // Std values
  25815. this.bindOnlyWorldMatrix(world);
  25816. if (this.getScene().getCachedMaterial() !== this) {
  25817. if (this._options.uniforms.indexOf("view") !== -1) {
  25818. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25819. }
  25820. if (this._options.uniforms.indexOf("projection") !== -1) {
  25821. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25822. }
  25823. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25824. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25825. }
  25826. // Bones
  25827. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25828. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25829. }
  25830. // Texture
  25831. for (var name in this._textures) {
  25832. this._effect.setTexture(name, this._textures[name]);
  25833. }
  25834. // Float
  25835. for (name in this._floats) {
  25836. this._effect.setFloat(name, this._floats[name]);
  25837. }
  25838. // Float s
  25839. for (name in this._floatsArrays) {
  25840. this._effect.setArray(name, this._floatsArrays[name]);
  25841. }
  25842. // Color3
  25843. for (name in this._colors3) {
  25844. this._effect.setColor3(name, this._colors3[name]);
  25845. }
  25846. // Color4
  25847. for (name in this._colors4) {
  25848. var color = this._colors4[name];
  25849. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25850. }
  25851. // Vector2
  25852. for (name in this._vectors2) {
  25853. this._effect.setVector2(name, this._vectors2[name]);
  25854. }
  25855. // Vector3
  25856. for (name in this._vectors3) {
  25857. this._effect.setVector3(name, this._vectors3[name]);
  25858. }
  25859. // Vector4
  25860. for (name in this._vectors4) {
  25861. this._effect.setVector4(name, this._vectors4[name]);
  25862. }
  25863. // Matrix
  25864. for (name in this._matrices) {
  25865. this._effect.setMatrix(name, this._matrices[name]);
  25866. }
  25867. // Matrix 3x3
  25868. for (name in this._matrices3x3) {
  25869. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25870. }
  25871. // Matrix 2x2
  25872. for (name in this._matrices2x2) {
  25873. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25874. }
  25875. }
  25876. _super.prototype.bind.call(this, world, mesh);
  25877. };
  25878. ShaderMaterial.prototype.clone = function (name) {
  25879. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25880. return newShaderMaterial;
  25881. };
  25882. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25883. for (var name in this._textures) {
  25884. this._textures[name].dispose();
  25885. }
  25886. this._textures = [];
  25887. _super.prototype.dispose.call(this, forceDisposeEffect);
  25888. };
  25889. return ShaderMaterial;
  25890. })(BABYLON.Material);
  25891. BABYLON.ShaderMaterial = ShaderMaterial;
  25892. })(BABYLON || (BABYLON = {}));
  25893. var BABYLON;
  25894. (function (BABYLON) {
  25895. var VertexData = (function () {
  25896. function VertexData() {
  25897. }
  25898. VertexData.prototype.set = function (data, kind) {
  25899. switch (kind) {
  25900. case BABYLON.VertexBuffer.PositionKind:
  25901. this.positions = data;
  25902. break;
  25903. case BABYLON.VertexBuffer.NormalKind:
  25904. this.normals = data;
  25905. break;
  25906. case BABYLON.VertexBuffer.UVKind:
  25907. this.uvs = data;
  25908. break;
  25909. case BABYLON.VertexBuffer.UV2Kind:
  25910. this.uvs2 = data;
  25911. break;
  25912. case BABYLON.VertexBuffer.UV3Kind:
  25913. this.uvs3 = data;
  25914. break;
  25915. case BABYLON.VertexBuffer.UV4Kind:
  25916. this.uvs4 = data;
  25917. break;
  25918. case BABYLON.VertexBuffer.UV5Kind:
  25919. this.uvs5 = data;
  25920. break;
  25921. case BABYLON.VertexBuffer.UV6Kind:
  25922. this.uvs6 = data;
  25923. break;
  25924. case BABYLON.VertexBuffer.ColorKind:
  25925. this.colors = data;
  25926. break;
  25927. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25928. this.matricesIndices = data;
  25929. break;
  25930. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25931. this.matricesWeights = data;
  25932. break;
  25933. }
  25934. };
  25935. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25936. this._applyTo(mesh, updatable);
  25937. };
  25938. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25939. this._applyTo(geometry, updatable);
  25940. };
  25941. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25942. this._update(mesh);
  25943. };
  25944. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25945. this._update(geometry);
  25946. };
  25947. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25948. if (this.positions) {
  25949. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25950. }
  25951. if (this.normals) {
  25952. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25953. }
  25954. if (this.uvs) {
  25955. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25956. }
  25957. if (this.uvs2) {
  25958. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25959. }
  25960. if (this.uvs3) {
  25961. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25962. }
  25963. if (this.uvs4) {
  25964. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25965. }
  25966. if (this.uvs5) {
  25967. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25968. }
  25969. if (this.uvs6) {
  25970. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25971. }
  25972. if (this.colors) {
  25973. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25974. }
  25975. if (this.matricesIndices) {
  25976. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25977. }
  25978. if (this.matricesWeights) {
  25979. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25980. }
  25981. if (this.indices) {
  25982. meshOrGeometry.setIndices(this.indices);
  25983. }
  25984. };
  25985. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25986. if (this.positions) {
  25987. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25988. }
  25989. if (this.normals) {
  25990. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25991. }
  25992. if (this.uvs) {
  25993. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25994. }
  25995. if (this.uvs2) {
  25996. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25997. }
  25998. if (this.uvs3) {
  25999. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26000. }
  26001. if (this.uvs4) {
  26002. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26003. }
  26004. if (this.uvs5) {
  26005. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26006. }
  26007. if (this.uvs6) {
  26008. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26009. }
  26010. if (this.colors) {
  26011. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26012. }
  26013. if (this.matricesIndices) {
  26014. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26015. }
  26016. if (this.matricesWeights) {
  26017. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26018. }
  26019. if (this.indices) {
  26020. meshOrGeometry.setIndices(this.indices);
  26021. }
  26022. };
  26023. VertexData.prototype.transform = function (matrix) {
  26024. var transformed = BABYLON.Vector3.Zero();
  26025. var index;
  26026. if (this.positions) {
  26027. var position = BABYLON.Vector3.Zero();
  26028. for (index = 0; index < this.positions.length; index += 3) {
  26029. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26030. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26031. this.positions[index] = transformed.x;
  26032. this.positions[index + 1] = transformed.y;
  26033. this.positions[index + 2] = transformed.z;
  26034. }
  26035. }
  26036. if (this.normals) {
  26037. var normal = BABYLON.Vector3.Zero();
  26038. for (index = 0; index < this.normals.length; index += 3) {
  26039. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26040. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26041. this.normals[index] = transformed.x;
  26042. this.normals[index + 1] = transformed.y;
  26043. this.normals[index + 2] = transformed.z;
  26044. }
  26045. }
  26046. };
  26047. VertexData.prototype.merge = function (other) {
  26048. var index;
  26049. if (other.indices) {
  26050. if (!this.indices) {
  26051. this.indices = [];
  26052. }
  26053. var offset = this.positions ? this.positions.length / 3 : 0;
  26054. for (index = 0; index < other.indices.length; index++) {
  26055. this.indices.push(other.indices[index] + offset);
  26056. }
  26057. }
  26058. if (other.positions) {
  26059. if (!this.positions) {
  26060. this.positions = [];
  26061. }
  26062. for (index = 0; index < other.positions.length; index++) {
  26063. this.positions.push(other.positions[index]);
  26064. }
  26065. }
  26066. if (other.normals) {
  26067. if (!this.normals) {
  26068. this.normals = [];
  26069. }
  26070. for (index = 0; index < other.normals.length; index++) {
  26071. this.normals.push(other.normals[index]);
  26072. }
  26073. }
  26074. if (other.uvs) {
  26075. if (!this.uvs) {
  26076. this.uvs = [];
  26077. }
  26078. for (index = 0; index < other.uvs.length; index++) {
  26079. this.uvs.push(other.uvs[index]);
  26080. }
  26081. }
  26082. if (other.uvs2) {
  26083. if (!this.uvs2) {
  26084. this.uvs2 = [];
  26085. }
  26086. for (index = 0; index < other.uvs2.length; index++) {
  26087. this.uvs2.push(other.uvs2[index]);
  26088. }
  26089. }
  26090. if (other.uvs3) {
  26091. if (!this.uvs3) {
  26092. this.uvs3 = [];
  26093. }
  26094. for (index = 0; index < other.uvs3.length; index++) {
  26095. this.uvs3.push(other.uvs3[index]);
  26096. }
  26097. }
  26098. if (other.uvs4) {
  26099. if (!this.uvs4) {
  26100. this.uvs4 = [];
  26101. }
  26102. for (index = 0; index < other.uvs4.length; index++) {
  26103. this.uvs4.push(other.uvs4[index]);
  26104. }
  26105. }
  26106. if (other.uvs5) {
  26107. if (!this.uvs5) {
  26108. this.uvs5 = [];
  26109. }
  26110. for (index = 0; index < other.uvs5.length; index++) {
  26111. this.uvs5.push(other.uvs5[index]);
  26112. }
  26113. }
  26114. if (other.uvs6) {
  26115. if (!this.uvs6) {
  26116. this.uvs6 = [];
  26117. }
  26118. for (index = 0; index < other.uvs6.length; index++) {
  26119. this.uvs6.push(other.uvs6[index]);
  26120. }
  26121. }
  26122. if (other.matricesIndices) {
  26123. if (!this.matricesIndices) {
  26124. this.matricesIndices = [];
  26125. }
  26126. for (index = 0; index < other.matricesIndices.length; index++) {
  26127. this.matricesIndices.push(other.matricesIndices[index]);
  26128. }
  26129. }
  26130. if (other.matricesWeights) {
  26131. if (!this.matricesWeights) {
  26132. this.matricesWeights = [];
  26133. }
  26134. for (index = 0; index < other.matricesWeights.length; index++) {
  26135. this.matricesWeights.push(other.matricesWeights[index]);
  26136. }
  26137. }
  26138. if (other.colors) {
  26139. if (!this.colors) {
  26140. this.colors = [];
  26141. }
  26142. for (index = 0; index < other.colors.length; index++) {
  26143. this.colors.push(other.colors[index]);
  26144. }
  26145. }
  26146. };
  26147. // Statics
  26148. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26149. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26150. };
  26151. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26152. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26153. };
  26154. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26155. var result = new VertexData();
  26156. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26157. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26158. }
  26159. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26160. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26161. }
  26162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26163. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26164. }
  26165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26166. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26167. }
  26168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26169. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26170. }
  26171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26172. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26173. }
  26174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26175. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26176. }
  26177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26178. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26179. }
  26180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26181. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26182. }
  26183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26184. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26185. }
  26186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26187. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26188. }
  26189. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26190. return result;
  26191. };
  26192. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  26193. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26194. closeArray = closeArray || false;
  26195. closePath = closePath || false;
  26196. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26197. offset = offset || defaultOffset;
  26198. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26199. var positions = [];
  26200. var indices = [];
  26201. var normals = [];
  26202. var uvs = [];
  26203. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26204. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26205. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26206. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26207. var minlg; // minimal length among all paths from pathArray
  26208. var lg = []; // array of path lengths : nb of vertex per path
  26209. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26210. var p; // path iterator
  26211. var i; // point iterator
  26212. var j; // point iterator
  26213. // if single path in pathArray
  26214. if (pathArray.length < 2) {
  26215. var ar1 = [];
  26216. var ar2 = [];
  26217. for (i = 0; i < pathArray[0].length - offset; i++) {
  26218. ar1.push(pathArray[0][i]);
  26219. ar2.push(pathArray[0][i + offset]);
  26220. }
  26221. pathArray = [ar1, ar2];
  26222. }
  26223. // positions and horizontal distances (u)
  26224. var idc = 0;
  26225. var closePathCorr = (closePath) ? 1 : 0;
  26226. var path;
  26227. var l;
  26228. minlg = pathArray[0].length;
  26229. var vectlg;
  26230. var dist;
  26231. for (p = 0; p < pathArray.length; p++) {
  26232. uTotalDistance[p] = 0;
  26233. us[p] = [0];
  26234. path = pathArray[p];
  26235. l = path.length;
  26236. minlg = (minlg < l) ? minlg : l;
  26237. j = 0;
  26238. while (j < l) {
  26239. positions.push(path[j].x, path[j].y, path[j].z);
  26240. if (j > 0) {
  26241. vectlg = path[j].subtract(path[j - 1]).length();
  26242. dist = vectlg + uTotalDistance[p];
  26243. us[p].push(dist);
  26244. uTotalDistance[p] = dist;
  26245. }
  26246. j++;
  26247. }
  26248. if (closePath) {
  26249. j--;
  26250. positions.push(path[0].x, path[0].y, path[0].z);
  26251. vectlg = path[j].subtract(path[0]).length();
  26252. dist = vectlg + uTotalDistance[p];
  26253. us[p].push(dist);
  26254. uTotalDistance[p] = dist;
  26255. }
  26256. lg[p] = l + closePathCorr;
  26257. idx[p] = idc;
  26258. idc += (l + closePathCorr);
  26259. }
  26260. // vertical distances (v)
  26261. var path1;
  26262. var path2;
  26263. var vertex1;
  26264. var vertex2;
  26265. for (i = 0; i < minlg + closePathCorr; i++) {
  26266. vTotalDistance[i] = 0;
  26267. vs[i] = [0];
  26268. for (p = 0; p < pathArray.length - 1; p++) {
  26269. path1 = pathArray[p];
  26270. path2 = pathArray[p + 1];
  26271. if (i === minlg) {
  26272. vertex1 = path1[0];
  26273. vertex2 = path2[0];
  26274. }
  26275. else {
  26276. vertex1 = path1[i];
  26277. vertex2 = path2[i];
  26278. }
  26279. vectlg = vertex2.subtract(vertex1).length();
  26280. dist = vectlg + vTotalDistance[i];
  26281. vs[i].push(dist);
  26282. vTotalDistance[i] = dist;
  26283. }
  26284. if (closeArray) {
  26285. path1 = pathArray[p];
  26286. path2 = pathArray[0];
  26287. vectlg = path2[i].subtract(path1[i]).length();
  26288. dist = vectlg + vTotalDistance[i];
  26289. vTotalDistance[i] = dist;
  26290. }
  26291. }
  26292. // uvs
  26293. var u;
  26294. var v;
  26295. for (p = 0; p < pathArray.length; p++) {
  26296. for (i = 0; i < minlg + closePathCorr; i++) {
  26297. u = us[p][i] / uTotalDistance[p];
  26298. v = vs[i][p] / vTotalDistance[i];
  26299. uvs.push(u, v);
  26300. }
  26301. }
  26302. // indices
  26303. p = 0; // path index
  26304. var pi = 0; // positions array index
  26305. var l1 = lg[p] - 1; // path1 length
  26306. var l2 = lg[p + 1] - 1; // path2 length
  26307. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26308. var shft = idx[1] - idx[0]; // shift
  26309. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26310. while (pi <= min && p < path1nb) {
  26311. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  26312. indices.push(pi, pi + shft, pi + 1);
  26313. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26314. pi += 1;
  26315. if (pi === min) {
  26316. p++;
  26317. if (p === lg.length - 1) {
  26318. shft = idx[0] - idx[p];
  26319. l1 = lg[p] - 1;
  26320. l2 = lg[0] - 1;
  26321. }
  26322. else {
  26323. shft = idx[p + 1] - idx[p];
  26324. l1 = lg[p] - 1;
  26325. l2 = lg[p + 1] - 1;
  26326. }
  26327. pi = idx[p];
  26328. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26329. }
  26330. }
  26331. // normals
  26332. VertexData.ComputeNormals(positions, indices, normals);
  26333. if (closePath) {
  26334. var indexFirst = 0;
  26335. var indexLast = 0;
  26336. for (p = 0; p < pathArray.length; p++) {
  26337. indexFirst = idx[p] * 3;
  26338. if (p + 1 < pathArray.length) {
  26339. indexLast = (idx[p + 1] - 1) * 3;
  26340. }
  26341. else {
  26342. indexLast = normals.length - 3;
  26343. }
  26344. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26345. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26346. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26347. normals[indexLast] = normals[indexFirst];
  26348. normals[indexLast + 1] = normals[indexFirst + 1];
  26349. normals[indexLast + 2] = normals[indexFirst + 2];
  26350. }
  26351. }
  26352. // sides
  26353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26354. // Result
  26355. var vertexData = new VertexData();
  26356. vertexData.indices = indices;
  26357. vertexData.positions = positions;
  26358. vertexData.normals = normals;
  26359. vertexData.uvs = uvs;
  26360. if (closePath) {
  26361. vertexData._idx = idx;
  26362. }
  26363. return vertexData;
  26364. };
  26365. VertexData.CreateBox = function (options, sideOrientation) {
  26366. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26367. var normalsSource = [
  26368. new BABYLON.Vector3(0, 0, 1),
  26369. new BABYLON.Vector3(0, 0, -1),
  26370. new BABYLON.Vector3(1, 0, 0),
  26371. new BABYLON.Vector3(-1, 0, 0),
  26372. new BABYLON.Vector3(0, 1, 0),
  26373. new BABYLON.Vector3(0, -1, 0)
  26374. ];
  26375. var indices = [];
  26376. var positions = [];
  26377. var normals = [];
  26378. var uvs = [];
  26379. var width = 1;
  26380. var height = 1;
  26381. var depth = 1;
  26382. var faceUV = options.faceUV || new Array(6);
  26383. var faceColors;
  26384. var colors = [];
  26385. if (options.faceColors) {
  26386. faceColors = options.faceColors;
  26387. }
  26388. if (options.width !== undefined) {
  26389. width = options.width || 1;
  26390. height = options.height || 1;
  26391. depth = options.depth || 1;
  26392. }
  26393. else {
  26394. width = options || 1;
  26395. height = options || 1;
  26396. depth = options || 1;
  26397. }
  26398. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26399. for (var f = 0; f < 6; f++) {
  26400. if (faceUV[f] === undefined) {
  26401. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26402. }
  26403. if (faceColors && faceColors[f] === undefined) {
  26404. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26405. }
  26406. }
  26407. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26408. // Create each face in turn.
  26409. for (var index = 0; index < normalsSource.length; index++) {
  26410. var normal = normalsSource[index];
  26411. // Get two vectors perpendicular to the face normal and to each other.
  26412. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26413. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26414. // Six indices (two triangles) per face.
  26415. var verticesLength = positions.length / 3;
  26416. indices.push(verticesLength);
  26417. indices.push(verticesLength + 1);
  26418. indices.push(verticesLength + 2);
  26419. indices.push(verticesLength);
  26420. indices.push(verticesLength + 2);
  26421. indices.push(verticesLength + 3);
  26422. // Four vertices per face.
  26423. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26424. positions.push(vertex.x, vertex.y, vertex.z);
  26425. normals.push(normal.x, normal.y, normal.z);
  26426. uvs.push(faceUV[index].z, faceUV[index].w);
  26427. if (faceColors) {
  26428. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26429. }
  26430. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26431. positions.push(vertex.x, vertex.y, vertex.z);
  26432. normals.push(normal.x, normal.y, normal.z);
  26433. uvs.push(faceUV[index].x, faceUV[index].w);
  26434. if (faceColors) {
  26435. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26436. }
  26437. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26438. positions.push(vertex.x, vertex.y, vertex.z);
  26439. normals.push(normal.x, normal.y, normal.z);
  26440. uvs.push(faceUV[index].x, faceUV[index].y);
  26441. if (faceColors) {
  26442. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26443. }
  26444. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26445. positions.push(vertex.x, vertex.y, vertex.z);
  26446. normals.push(normal.x, normal.y, normal.z);
  26447. uvs.push(faceUV[index].z, faceUV[index].y);
  26448. if (faceColors) {
  26449. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26450. }
  26451. }
  26452. // sides
  26453. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26454. // Result
  26455. var vertexData = new VertexData();
  26456. vertexData.indices = indices;
  26457. vertexData.positions = positions;
  26458. vertexData.normals = normals;
  26459. vertexData.uvs = uvs;
  26460. if (faceColors) {
  26461. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26462. vertexData.colors = totalColors;
  26463. }
  26464. return vertexData;
  26465. };
  26466. VertexData.CreateSphere = function (options, diameter, sideOrientation) {
  26467. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26468. var segments;
  26469. var diameterX;
  26470. var diameterY;
  26471. var diameterZ;
  26472. if (options.segments) {
  26473. segments = options.segments || 32;
  26474. diameterX = options.diameterX || 1;
  26475. diameterY = options.diameterY || 1;
  26476. diameterZ = options.diameterZ || 1;
  26477. }
  26478. else {
  26479. segments = options || 32;
  26480. diameterX = diameter || 1;
  26481. diameterY = diameterX;
  26482. diameterZ = diameterX;
  26483. }
  26484. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26485. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26486. var totalZRotationSteps = 2 + segments;
  26487. var totalYRotationSteps = 2 * totalZRotationSteps;
  26488. var indices = [];
  26489. var positions = [];
  26490. var normals = [];
  26491. var uvs = [];
  26492. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26493. var normalizedZ = zRotationStep / totalZRotationSteps;
  26494. var angleZ = (normalizedZ * Math.PI);
  26495. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26496. var normalizedY = yRotationStep / totalYRotationSteps;
  26497. var angleY = normalizedY * Math.PI * 2;
  26498. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26499. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26500. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26501. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26502. var vertex = complete.multiply(radius);
  26503. var normal = BABYLON.Vector3.Normalize(vertex);
  26504. positions.push(vertex.x, vertex.y, vertex.z);
  26505. normals.push(normal.x, normal.y, normal.z);
  26506. uvs.push(normalizedY, normalizedZ);
  26507. }
  26508. if (zRotationStep > 0) {
  26509. var verticesCount = positions.length / 3;
  26510. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26511. indices.push((firstIndex));
  26512. indices.push((firstIndex + 1));
  26513. indices.push(firstIndex + totalYRotationSteps + 1);
  26514. indices.push((firstIndex + totalYRotationSteps + 1));
  26515. indices.push((firstIndex + 1));
  26516. indices.push((firstIndex + totalYRotationSteps + 2));
  26517. }
  26518. }
  26519. }
  26520. // Sides
  26521. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26522. // Result
  26523. var vertexData = new VertexData();
  26524. vertexData.indices = indices;
  26525. vertexData.positions = positions;
  26526. vertexData.normals = normals;
  26527. vertexData.uvs = uvs;
  26528. return vertexData;
  26529. };
  26530. // Cylinder and cone (made using ribbons)
  26531. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26532. if (subdivisions === void 0) { subdivisions = 1; }
  26533. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26534. var indices = [];
  26535. var positions = [];
  26536. var normals = [];
  26537. var uvs = [];
  26538. var angle_step = Math.PI * 2 / tessellation;
  26539. var angle;
  26540. var h;
  26541. var radius;
  26542. var tan = (diameterBottom - diameterTop) / 2 / height;
  26543. var ringVertex = BABYLON.Vector3.Zero();
  26544. var ringNormal = BABYLON.Vector3.Zero();
  26545. // positions, normals, uvs
  26546. var i;
  26547. var j;
  26548. for (i = 0; i <= subdivisions; i++) {
  26549. h = i / subdivisions;
  26550. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26551. for (j = 0; j <= tessellation; j++) {
  26552. angle = j * angle_step;
  26553. ringVertex.x = Math.cos(-angle) * radius;
  26554. ringVertex.y = -height / 2 + h * height;
  26555. ringVertex.z = Math.sin(-angle) * radius;
  26556. if (diameterTop === 0 && i === subdivisions) {
  26557. // if no top cap, reuse former normals
  26558. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26559. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26560. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26561. }
  26562. else {
  26563. ringNormal.x = ringVertex.x;
  26564. ringNormal.z = ringVertex.z;
  26565. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26566. ringNormal.normalize();
  26567. }
  26568. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26569. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26570. uvs.push(j / tessellation, 1 - h);
  26571. }
  26572. }
  26573. // indices
  26574. for (i = 0; i < subdivisions; i++) {
  26575. for (j = 0; j < tessellation; j++) {
  26576. var i0 = i * (tessellation + 1) + j;
  26577. var i1 = (i + 1) * (tessellation + 1) + j;
  26578. var i2 = i * (tessellation + 1) + (j + 1);
  26579. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  26580. indices.push(i0, i1, i2);
  26581. indices.push(i3, i2, i1);
  26582. }
  26583. }
  26584. // Caps
  26585. var createCylinderCap = function (isTop) {
  26586. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26587. if (radius === 0) {
  26588. return;
  26589. }
  26590. var vbase = positions.length / 3;
  26591. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26592. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26593. // Cap positions, normals & uvs
  26594. var angle;
  26595. var circleVector;
  26596. var i;
  26597. for (i = 0; i < tessellation; i++) {
  26598. angle = Math.PI * 2 * i / tessellation;
  26599. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26600. var position = circleVector.scale(radius).add(offset);
  26601. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26602. positions.push(position.x, position.y, position.z);
  26603. normals.push(0, isTop ? 1 : -1, 0);
  26604. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26605. }
  26606. // Cap indices
  26607. for (i = 0; i < tessellation - 2; i++) {
  26608. if (!isTop) {
  26609. indices.push(vbase);
  26610. indices.push(vbase + (i + 1) % tessellation);
  26611. indices.push(vbase + (i + 2) % tessellation);
  26612. }
  26613. else {
  26614. indices.push(vbase);
  26615. indices.push(vbase + (i + 2) % tessellation);
  26616. indices.push(vbase + (i + 1) % tessellation);
  26617. }
  26618. }
  26619. };
  26620. // add caps to geometry
  26621. createCylinderCap(true);
  26622. createCylinderCap(false);
  26623. // Sides
  26624. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26625. var vertexData = new VertexData();
  26626. vertexData.indices = indices;
  26627. vertexData.positions = positions;
  26628. vertexData.normals = normals;
  26629. vertexData.uvs = uvs;
  26630. return vertexData;
  26631. };
  26632. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26633. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26634. var indices = [];
  26635. var positions = [];
  26636. var normals = [];
  26637. var uvs = [];
  26638. diameter = diameter || 1;
  26639. thickness = thickness || 0.5;
  26640. tessellation = tessellation || 16;
  26641. var stride = tessellation + 1;
  26642. for (var i = 0; i <= tessellation; i++) {
  26643. var u = i / tessellation;
  26644. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26645. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26646. for (var j = 0; j <= tessellation; j++) {
  26647. var v = 1 - j / tessellation;
  26648. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26649. var dx = Math.cos(innerAngle);
  26650. var dy = Math.sin(innerAngle);
  26651. // Create a vertex.
  26652. var normal = new BABYLON.Vector3(dx, dy, 0);
  26653. var position = normal.scale(thickness / 2);
  26654. var textureCoordinate = new BABYLON.Vector2(u, v);
  26655. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26656. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26657. positions.push(position.x, position.y, position.z);
  26658. normals.push(normal.x, normal.y, normal.z);
  26659. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26660. // And create indices for two triangles.
  26661. var nextI = (i + 1) % stride;
  26662. var nextJ = (j + 1) % stride;
  26663. indices.push(i * stride + j);
  26664. indices.push(i * stride + nextJ);
  26665. indices.push(nextI * stride + j);
  26666. indices.push(i * stride + nextJ);
  26667. indices.push(nextI * stride + nextJ);
  26668. indices.push(nextI * stride + j);
  26669. }
  26670. }
  26671. // Sides
  26672. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26673. // Result
  26674. var vertexData = new VertexData();
  26675. vertexData.indices = indices;
  26676. vertexData.positions = positions;
  26677. vertexData.normals = normals;
  26678. vertexData.uvs = uvs;
  26679. return vertexData;
  26680. };
  26681. VertexData.CreateLines = function (points) {
  26682. var indices = [];
  26683. var positions = [];
  26684. for (var index = 0; index < points.length; index++) {
  26685. positions.push(points[index].x, points[index].y, points[index].z);
  26686. if (index > 0) {
  26687. indices.push(index - 1);
  26688. indices.push(index);
  26689. }
  26690. }
  26691. // Result
  26692. var vertexData = new VertexData();
  26693. vertexData.indices = indices;
  26694. vertexData.positions = positions;
  26695. return vertexData;
  26696. };
  26697. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26698. dashSize = dashSize || 3;
  26699. gapSize = gapSize || 1;
  26700. dashNb = dashNb || 200;
  26701. var positions = new Array();
  26702. var indices = new Array();
  26703. var curvect = BABYLON.Vector3.Zero();
  26704. var lg = 0;
  26705. var nb = 0;
  26706. var shft = 0;
  26707. var dashshft = 0;
  26708. var curshft = 0;
  26709. var idx = 0;
  26710. var i = 0;
  26711. for (i = 0; i < points.length - 1; i++) {
  26712. points[i + 1].subtractToRef(points[i], curvect);
  26713. lg += curvect.length();
  26714. }
  26715. shft = lg / dashNb;
  26716. dashshft = dashSize * shft / (dashSize + gapSize);
  26717. for (i = 0; i < points.length - 1; i++) {
  26718. points[i + 1].subtractToRef(points[i], curvect);
  26719. nb = Math.floor(curvect.length() / shft);
  26720. curvect.normalize();
  26721. for (var j = 0; j < nb; j++) {
  26722. curshft = shft * j;
  26723. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26724. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26725. indices.push(idx, idx + 1);
  26726. idx += 2;
  26727. }
  26728. }
  26729. // Result
  26730. var vertexData = new VertexData();
  26731. vertexData.positions = positions;
  26732. vertexData.indices = indices;
  26733. return vertexData;
  26734. };
  26735. VertexData.CreateGround = function (options, height, subdivisions) {
  26736. var indices = [];
  26737. var positions = [];
  26738. var normals = [];
  26739. var uvs = [];
  26740. var row, col;
  26741. var width;
  26742. if (options.width) {
  26743. width = options.width || 1;
  26744. height = options.height || 1;
  26745. subdivisions = options.subdivisions || 1;
  26746. }
  26747. else {
  26748. width = options || 1;
  26749. height = height || 1;
  26750. subdivisions = subdivisions || 1;
  26751. }
  26752. for (row = 0; row <= subdivisions; row++) {
  26753. for (col = 0; col <= subdivisions; col++) {
  26754. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26755. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26756. positions.push(position.x, position.y, position.z);
  26757. normals.push(normal.x, normal.y, normal.z);
  26758. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26759. }
  26760. }
  26761. for (row = 0; row < subdivisions; row++) {
  26762. for (col = 0; col < subdivisions; col++) {
  26763. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26764. indices.push(col + 1 + row * (subdivisions + 1));
  26765. indices.push(col + row * (subdivisions + 1));
  26766. indices.push(col + (row + 1) * (subdivisions + 1));
  26767. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26768. indices.push(col + row * (subdivisions + 1));
  26769. }
  26770. }
  26771. // Result
  26772. var vertexData = new VertexData();
  26773. vertexData.indices = indices;
  26774. vertexData.positions = positions;
  26775. vertexData.normals = normals;
  26776. vertexData.uvs = uvs;
  26777. return vertexData;
  26778. };
  26779. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26780. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26781. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26782. var indices = [];
  26783. var positions = [];
  26784. var normals = [];
  26785. var uvs = [];
  26786. var row, col, tileRow, tileCol;
  26787. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26788. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26789. precision.w = (precision.w < 1) ? 1 : precision.w;
  26790. precision.h = (precision.h < 1) ? 1 : precision.h;
  26791. var tileSize = {
  26792. 'w': (xmax - xmin) / subdivisions.w,
  26793. 'h': (zmax - zmin) / subdivisions.h
  26794. };
  26795. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26796. // Indices
  26797. var base = positions.length / 3;
  26798. var rowLength = precision.w + 1;
  26799. for (row = 0; row < precision.h; row++) {
  26800. for (col = 0; col < precision.w; col++) {
  26801. var square = [
  26802. base + col + row * rowLength,
  26803. base + (col + 1) + row * rowLength,
  26804. base + (col + 1) + (row + 1) * rowLength,
  26805. base + col + (row + 1) * rowLength
  26806. ];
  26807. indices.push(square[1]);
  26808. indices.push(square[2]);
  26809. indices.push(square[3]);
  26810. indices.push(square[0]);
  26811. indices.push(square[1]);
  26812. indices.push(square[3]);
  26813. }
  26814. }
  26815. // Position, normals and uvs
  26816. var position = BABYLON.Vector3.Zero();
  26817. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26818. for (row = 0; row <= precision.h; row++) {
  26819. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26820. for (col = 0; col <= precision.w; col++) {
  26821. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26822. position.y = 0;
  26823. positions.push(position.x, position.y, position.z);
  26824. normals.push(normal.x, normal.y, normal.z);
  26825. uvs.push(col / precision.w, row / precision.h);
  26826. }
  26827. }
  26828. }
  26829. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26830. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26831. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26832. }
  26833. }
  26834. // Result
  26835. var vertexData = new VertexData();
  26836. vertexData.indices = indices;
  26837. vertexData.positions = positions;
  26838. vertexData.normals = normals;
  26839. vertexData.uvs = uvs;
  26840. return vertexData;
  26841. };
  26842. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26843. var indices = [];
  26844. var positions = [];
  26845. var normals = [];
  26846. var uvs = [];
  26847. var row, col;
  26848. // Vertices
  26849. for (row = 0; row <= subdivisions; row++) {
  26850. for (col = 0; col <= subdivisions; col++) {
  26851. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26852. // Compute height
  26853. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26854. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26855. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26856. var r = buffer[pos] / 255.0;
  26857. var g = buffer[pos + 1] / 255.0;
  26858. var b = buffer[pos + 2] / 255.0;
  26859. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26860. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26861. // Add vertex
  26862. positions.push(position.x, position.y, position.z);
  26863. normals.push(0, 0, 0);
  26864. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26865. }
  26866. }
  26867. // Indices
  26868. for (row = 0; row < subdivisions; row++) {
  26869. for (col = 0; col < subdivisions; col++) {
  26870. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26871. indices.push(col + 1 + row * (subdivisions + 1));
  26872. indices.push(col + row * (subdivisions + 1));
  26873. indices.push(col + (row + 1) * (subdivisions + 1));
  26874. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26875. indices.push(col + row * (subdivisions + 1));
  26876. }
  26877. }
  26878. // Normals
  26879. VertexData.ComputeNormals(positions, indices, normals);
  26880. // Result
  26881. var vertexData = new VertexData();
  26882. vertexData.indices = indices;
  26883. vertexData.positions = positions;
  26884. vertexData.normals = normals;
  26885. vertexData.uvs = uvs;
  26886. return vertexData;
  26887. };
  26888. VertexData.CreatePlane = function (options, sideOrientation) {
  26889. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26890. var indices = [];
  26891. var positions = [];
  26892. var normals = [];
  26893. var uvs = [];
  26894. var width;
  26895. var height;
  26896. if (options.width) {
  26897. width = options.width || 1;
  26898. height = options.height || 1;
  26899. sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26900. }
  26901. else {
  26902. width = options || 1;
  26903. height = options || 1;
  26904. }
  26905. // Vertices
  26906. var halfWidth = width / 2.0;
  26907. var halfHeight = height / 2.0;
  26908. positions.push(-halfWidth, -halfHeight, 0);
  26909. normals.push(0, 0, -1.0);
  26910. uvs.push(0.0, 0.0);
  26911. positions.push(halfWidth, -halfHeight, 0);
  26912. normals.push(0, 0, -1.0);
  26913. uvs.push(1.0, 0.0);
  26914. positions.push(halfWidth, halfHeight, 0);
  26915. normals.push(0, 0, -1.0);
  26916. uvs.push(1.0, 1.0);
  26917. positions.push(-halfWidth, halfHeight, 0);
  26918. normals.push(0, 0, -1.0);
  26919. uvs.push(0.0, 1.0);
  26920. // Indices
  26921. indices.push(0);
  26922. indices.push(1);
  26923. indices.push(2);
  26924. indices.push(0);
  26925. indices.push(2);
  26926. indices.push(3);
  26927. // Sides
  26928. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26929. // Result
  26930. var vertexData = new VertexData();
  26931. vertexData.indices = indices;
  26932. vertexData.positions = positions;
  26933. vertexData.normals = normals;
  26934. vertexData.uvs = uvs;
  26935. return vertexData;
  26936. };
  26937. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26938. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26939. var positions = [];
  26940. var indices = [];
  26941. var normals = [];
  26942. var uvs = [];
  26943. // positions and uvs
  26944. positions.push(0, 0, 0); // disc center first
  26945. uvs.push(0.5, 0.5);
  26946. var step = Math.PI * 2 / tessellation;
  26947. for (var a = 0; a < Math.PI * 2; a += step) {
  26948. var x = Math.cos(a);
  26949. var y = Math.sin(a);
  26950. var u = (x + 1) / 2;
  26951. var v = (1 - y) / 2;
  26952. positions.push(radius * x, radius * y, 0);
  26953. uvs.push(u, v);
  26954. }
  26955. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26956. uvs.push(uvs[2], uvs[3]);
  26957. //indices
  26958. var vertexNb = positions.length / 3;
  26959. for (var i = 1; i < vertexNb - 1; i++) {
  26960. indices.push(i + 1, 0, i);
  26961. }
  26962. // result
  26963. VertexData.ComputeNormals(positions, indices, normals);
  26964. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26965. var vertexData = new VertexData();
  26966. vertexData.indices = indices;
  26967. vertexData.positions = positions;
  26968. vertexData.normals = normals;
  26969. vertexData.uvs = uvs;
  26970. return vertexData;
  26971. };
  26972. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26973. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  26974. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26975. var indices = [];
  26976. var positions = [];
  26977. var normals = [];
  26978. var uvs = [];
  26979. radius = radius || 2;
  26980. tube = tube || 0.5;
  26981. radialSegments = radialSegments || 32;
  26982. tubularSegments = tubularSegments || 32;
  26983. p = p || 2;
  26984. q = q || 3;
  26985. // Helper
  26986. var getPos = function (angle) {
  26987. var cu = Math.cos(angle);
  26988. var su = Math.sin(angle);
  26989. var quOverP = q / p * angle;
  26990. var cs = Math.cos(quOverP);
  26991. var tx = radius * (2 + cs) * 0.5 * cu;
  26992. var ty = radius * (2 + cs) * su * 0.5;
  26993. var tz = radius * Math.sin(quOverP) * 0.5;
  26994. return new BABYLON.Vector3(tx, ty, tz);
  26995. };
  26996. // Vertices
  26997. var i;
  26998. var j;
  26999. for (i = 0; i <= radialSegments; i++) {
  27000. var modI = i % radialSegments;
  27001. var u = modI / radialSegments * 2 * p * Math.PI;
  27002. var p1 = getPos(u);
  27003. var p2 = getPos(u + 0.01);
  27004. var tang = p2.subtract(p1);
  27005. var n = p2.add(p1);
  27006. var bitan = BABYLON.Vector3.Cross(tang, n);
  27007. n = BABYLON.Vector3.Cross(bitan, tang);
  27008. bitan.normalize();
  27009. n.normalize();
  27010. for (j = 0; j < tubularSegments; j++) {
  27011. var modJ = j % tubularSegments;
  27012. var v = modJ / tubularSegments * 2 * Math.PI;
  27013. var cx = -tube * Math.cos(v);
  27014. var cy = tube * Math.sin(v);
  27015. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27016. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27017. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27018. uvs.push(i / radialSegments);
  27019. uvs.push(j / tubularSegments);
  27020. }
  27021. }
  27022. for (i = 0; i < radialSegments; i++) {
  27023. for (j = 0; j < tubularSegments; j++) {
  27024. var jNext = (j + 1) % tubularSegments;
  27025. var a = i * tubularSegments + j;
  27026. var b = (i + 1) * tubularSegments + j;
  27027. var c = (i + 1) * tubularSegments + jNext;
  27028. var d = i * tubularSegments + jNext;
  27029. indices.push(d);
  27030. indices.push(b);
  27031. indices.push(a);
  27032. indices.push(d);
  27033. indices.push(c);
  27034. indices.push(b);
  27035. }
  27036. }
  27037. // Normals
  27038. VertexData.ComputeNormals(positions, indices, normals);
  27039. // Sides
  27040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27041. // Result
  27042. var vertexData = new VertexData();
  27043. vertexData.indices = indices;
  27044. vertexData.positions = positions;
  27045. vertexData.normals = normals;
  27046. vertexData.uvs = uvs;
  27047. return vertexData;
  27048. };
  27049. // Tools
  27050. /**
  27051. * @param {any} - positions (number[] or Float32Array)
  27052. * @param {any} - indices (number[] or Uint16Array)
  27053. * @param {any} - normals (number[] or Float32Array)
  27054. */
  27055. VertexData.ComputeNormals = function (positions, indices, normals) {
  27056. var index = 0;
  27057. // temp Vector3
  27058. var p1p2 = BABYLON.Vector3.Zero();
  27059. var p3p2 = BABYLON.Vector3.Zero();
  27060. var faceNormal = BABYLON.Vector3.Zero();
  27061. var vertexNormali1 = BABYLON.Vector3.Zero();
  27062. for (index = 0; index < positions.length; index++) {
  27063. normals[index] = 0.0;
  27064. }
  27065. // indice triplet = 1 face
  27066. var nbFaces = indices.length / 3;
  27067. for (index = 0; index < nbFaces; index++) {
  27068. var i1 = indices[index * 3];
  27069. var i2 = indices[index * 3 + 1];
  27070. var i3 = indices[index * 3 + 2];
  27071. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27072. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27073. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27074. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27075. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27076. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27077. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27078. faceNormal.normalize();
  27079. normals[i1 * 3] += faceNormal.x;
  27080. normals[i1 * 3 + 1] += faceNormal.y;
  27081. normals[i1 * 3 + 2] += faceNormal.z;
  27082. normals[i2 * 3] += faceNormal.x;
  27083. normals[i2 * 3 + 1] += faceNormal.y;
  27084. normals[i2 * 3 + 2] += faceNormal.z;
  27085. normals[i3 * 3] += faceNormal.x;
  27086. normals[i3 * 3 + 1] += faceNormal.y;
  27087. normals[i3 * 3 + 2] += faceNormal.z;
  27088. }
  27089. // last normalization
  27090. for (index = 0; index < normals.length / 3; index++) {
  27091. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27092. vertexNormali1.normalize();
  27093. normals[index * 3] = vertexNormali1.x;
  27094. normals[index * 3 + 1] = vertexNormali1.y;
  27095. normals[index * 3 + 2] = vertexNormali1.z;
  27096. }
  27097. };
  27098. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27099. var li = indices.length;
  27100. var ln = normals.length;
  27101. var i;
  27102. var n;
  27103. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27104. switch (sideOrientation) {
  27105. case BABYLON.Mesh.FRONTSIDE:
  27106. // nothing changed
  27107. break;
  27108. case BABYLON.Mesh.BACKSIDE:
  27109. var tmp;
  27110. // indices
  27111. for (i = 0; i < li; i += 3) {
  27112. tmp = indices[i];
  27113. indices[i] = indices[i + 2];
  27114. indices[i + 2] = tmp;
  27115. }
  27116. // normals
  27117. for (n = 0; n < ln; n++) {
  27118. normals[n] = -normals[n];
  27119. }
  27120. break;
  27121. case BABYLON.Mesh.DOUBLESIDE:
  27122. // positions
  27123. var lp = positions.length;
  27124. var l = lp / 3;
  27125. for (var p = 0; p < lp; p++) {
  27126. positions[lp + p] = positions[p];
  27127. }
  27128. // indices
  27129. for (i = 0; i < li; i += 3) {
  27130. indices[i + li] = indices[i + 2] + l;
  27131. indices[i + 1 + li] = indices[i + 1] + l;
  27132. indices[i + 2 + li] = indices[i] + l;
  27133. }
  27134. // normals
  27135. for (n = 0; n < ln; n++) {
  27136. normals[ln + n] = -normals[n];
  27137. }
  27138. // uvs
  27139. var lu = uvs.length;
  27140. for (var u = 0; u < lu; u++) {
  27141. uvs[u + lu] = uvs[u];
  27142. }
  27143. break;
  27144. }
  27145. };
  27146. return VertexData;
  27147. })();
  27148. BABYLON.VertexData = VertexData;
  27149. })(BABYLON || (BABYLON = {}));
  27150. var BABYLON;
  27151. (function (BABYLON) {
  27152. var AnaglyphPostProcess = (function (_super) {
  27153. __extends(AnaglyphPostProcess, _super);
  27154. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27155. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27156. }
  27157. return AnaglyphPostProcess;
  27158. })(BABYLON.PostProcess);
  27159. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27160. })(BABYLON || (BABYLON = {}));
  27161. var BABYLON;
  27162. (function (BABYLON) {
  27163. var Tags = (function () {
  27164. function Tags() {
  27165. }
  27166. Tags.EnableFor = function (obj) {
  27167. obj._tags = obj._tags || {};
  27168. obj.hasTags = function () {
  27169. return Tags.HasTags(obj);
  27170. };
  27171. obj.addTags = function (tagsString) {
  27172. return Tags.AddTagsTo(obj, tagsString);
  27173. };
  27174. obj.removeTags = function (tagsString) {
  27175. return Tags.RemoveTagsFrom(obj, tagsString);
  27176. };
  27177. obj.matchesTagsQuery = function (tagsQuery) {
  27178. return Tags.MatchesQuery(obj, tagsQuery);
  27179. };
  27180. };
  27181. Tags.DisableFor = function (obj) {
  27182. delete obj._tags;
  27183. delete obj.hasTags;
  27184. delete obj.addTags;
  27185. delete obj.removeTags;
  27186. delete obj.matchesTagsQuery;
  27187. };
  27188. Tags.HasTags = function (obj) {
  27189. if (!obj._tags) {
  27190. return false;
  27191. }
  27192. return !BABYLON.Tools.IsEmpty(obj._tags);
  27193. };
  27194. Tags.GetTags = function (obj) {
  27195. if (!obj._tags) {
  27196. return null;
  27197. }
  27198. return obj._tags;
  27199. };
  27200. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27201. // a tag cannot start with '||', '&&', and '!'
  27202. // it cannot contain whitespaces
  27203. Tags.AddTagsTo = function (obj, tagsString) {
  27204. if (!tagsString) {
  27205. return;
  27206. }
  27207. var tags = tagsString.split(" ");
  27208. for (var t in tags) {
  27209. Tags._AddTagTo(obj, tags[t]);
  27210. }
  27211. };
  27212. Tags._AddTagTo = function (obj, tag) {
  27213. tag = tag.trim();
  27214. if (tag === "" || tag === "true" || tag === "false") {
  27215. return;
  27216. }
  27217. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27218. return;
  27219. }
  27220. Tags.EnableFor(obj);
  27221. obj._tags[tag] = true;
  27222. };
  27223. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27224. if (!Tags.HasTags(obj)) {
  27225. return;
  27226. }
  27227. var tags = tagsString.split(" ");
  27228. for (var t in tags) {
  27229. Tags._RemoveTagFrom(obj, tags[t]);
  27230. }
  27231. };
  27232. Tags._RemoveTagFrom = function (obj, tag) {
  27233. delete obj._tags[tag];
  27234. };
  27235. Tags.MatchesQuery = function (obj, tagsQuery) {
  27236. if (tagsQuery === undefined) {
  27237. return true;
  27238. }
  27239. if (tagsQuery === "") {
  27240. return Tags.HasTags(obj);
  27241. }
  27242. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27243. };
  27244. return Tags;
  27245. })();
  27246. BABYLON.Tags = Tags;
  27247. })(BABYLON || (BABYLON = {}));
  27248. var BABYLON;
  27249. (function (BABYLON) {
  27250. var Internals;
  27251. (function (Internals) {
  27252. var AndOrNotEvaluator = (function () {
  27253. function AndOrNotEvaluator() {
  27254. }
  27255. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27256. if (!query.match(/\([^\(\)]*\)/g)) {
  27257. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27258. }
  27259. else {
  27260. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27261. // remove parenthesis
  27262. r = r.slice(1, r.length - 1);
  27263. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27264. });
  27265. }
  27266. if (query === "true") {
  27267. return true;
  27268. }
  27269. if (query === "false") {
  27270. return false;
  27271. }
  27272. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27273. };
  27274. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27275. evaluateCallback = evaluateCallback || (function (r) {
  27276. return r === "true" ? true : false;
  27277. });
  27278. var result;
  27279. var or = parenthesisContent.split("||");
  27280. for (var i in or) {
  27281. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27282. var and = ori.split("&&");
  27283. if (and.length > 1) {
  27284. for (var j = 0; j < and.length; ++j) {
  27285. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27286. if (andj !== "true" && andj !== "false") {
  27287. if (andj[0] === "!") {
  27288. result = !evaluateCallback(andj.substring(1));
  27289. }
  27290. else {
  27291. result = evaluateCallback(andj);
  27292. }
  27293. }
  27294. else {
  27295. result = andj === "true" ? true : false;
  27296. }
  27297. if (!result) {
  27298. ori = "false";
  27299. break;
  27300. }
  27301. }
  27302. }
  27303. if (result || ori === "true") {
  27304. result = true;
  27305. break;
  27306. }
  27307. // result equals false (or undefined)
  27308. if (ori !== "true" && ori !== "false") {
  27309. if (ori[0] === "!") {
  27310. result = !evaluateCallback(ori.substring(1));
  27311. }
  27312. else {
  27313. result = evaluateCallback(ori);
  27314. }
  27315. }
  27316. else {
  27317. result = ori === "true" ? true : false;
  27318. }
  27319. }
  27320. // the whole parenthesis scope is replaced by 'true' or 'false'
  27321. return result ? "true" : "false";
  27322. };
  27323. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27324. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27325. // remove whitespaces
  27326. r = r.replace(/[\s]/g, function () { return ""; });
  27327. return r.length % 2 ? "!" : "";
  27328. });
  27329. booleanString = booleanString.trim();
  27330. if (booleanString === "!true") {
  27331. booleanString = "false";
  27332. }
  27333. else if (booleanString === "!false") {
  27334. booleanString = "true";
  27335. }
  27336. return booleanString;
  27337. };
  27338. return AndOrNotEvaluator;
  27339. })();
  27340. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27341. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27342. })(BABYLON || (BABYLON = {}));
  27343. var BABYLON;
  27344. (function (BABYLON) {
  27345. var PostProcessRenderPass = (function () {
  27346. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27347. this._enabled = true;
  27348. this._refCount = 0;
  27349. this._name = name;
  27350. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27351. this.setRenderList(renderList);
  27352. this._renderTexture.onBeforeRender = beforeRender;
  27353. this._renderTexture.onAfterRender = afterRender;
  27354. this._scene = scene;
  27355. this._renderList = renderList;
  27356. }
  27357. // private
  27358. PostProcessRenderPass.prototype._incRefCount = function () {
  27359. if (this._refCount === 0) {
  27360. this._scene.customRenderTargets.push(this._renderTexture);
  27361. }
  27362. return ++this._refCount;
  27363. };
  27364. PostProcessRenderPass.prototype._decRefCount = function () {
  27365. this._refCount--;
  27366. if (this._refCount <= 0) {
  27367. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27368. }
  27369. return this._refCount;
  27370. };
  27371. PostProcessRenderPass.prototype._update = function () {
  27372. this.setRenderList(this._renderList);
  27373. };
  27374. // public
  27375. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27376. this._renderTexture.renderList = renderList;
  27377. };
  27378. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27379. return this._renderTexture;
  27380. };
  27381. return PostProcessRenderPass;
  27382. })();
  27383. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27384. })(BABYLON || (BABYLON = {}));
  27385. var BABYLON;
  27386. (function (BABYLON) {
  27387. var PostProcessRenderEffect = (function () {
  27388. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27389. this._engine = engine;
  27390. this._name = name;
  27391. this._singleInstance = singleInstance || true;
  27392. this._getPostProcess = getPostProcess;
  27393. this._cameras = [];
  27394. this._indicesForCamera = [];
  27395. this._postProcesses = {};
  27396. this._renderPasses = {};
  27397. this._renderEffectAsPasses = {};
  27398. }
  27399. PostProcessRenderEffect.prototype._update = function () {
  27400. for (var renderPassName in this._renderPasses) {
  27401. this._renderPasses[renderPassName]._update();
  27402. }
  27403. };
  27404. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27405. this._renderPasses[renderPass._name] = renderPass;
  27406. this._linkParameters();
  27407. };
  27408. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27409. delete this._renderPasses[renderPass._name];
  27410. this._linkParameters();
  27411. };
  27412. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27413. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27414. this._linkParameters();
  27415. };
  27416. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27417. for (var renderPassName in this._renderPasses) {
  27418. if (renderPassName === passName) {
  27419. return this._renderPasses[passName];
  27420. }
  27421. }
  27422. };
  27423. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27424. this._renderPasses = {};
  27425. this._linkParameters();
  27426. };
  27427. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27428. var cameraKey;
  27429. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27430. for (var i = 0; i < _cam.length; i++) {
  27431. var camera = _cam[i];
  27432. var cameraName = camera.name;
  27433. if (this._singleInstance) {
  27434. cameraKey = 0;
  27435. }
  27436. else {
  27437. cameraKey = cameraName;
  27438. }
  27439. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27440. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27441. if (!this._indicesForCamera[cameraName]) {
  27442. this._indicesForCamera[cameraName] = [];
  27443. }
  27444. this._indicesForCamera[cameraName].push(index);
  27445. if (this._cameras.indexOf(camera) === -1) {
  27446. this._cameras[cameraName] = camera;
  27447. }
  27448. for (var passName in this._renderPasses) {
  27449. this._renderPasses[passName]._incRefCount();
  27450. }
  27451. }
  27452. this._linkParameters();
  27453. };
  27454. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27455. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27456. for (var i = 0; i < _cam.length; i++) {
  27457. var camera = _cam[i];
  27458. var cameraName = camera.name;
  27459. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27460. var index = this._cameras.indexOf(cameraName);
  27461. this._indicesForCamera.splice(index, 1);
  27462. this._cameras.splice(index, 1);
  27463. for (var passName in this._renderPasses) {
  27464. this._renderPasses[passName]._decRefCount();
  27465. }
  27466. }
  27467. };
  27468. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27469. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27470. for (var i = 0; i < _cam.length; i++) {
  27471. var camera = _cam[i];
  27472. var cameraName = camera.name;
  27473. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27474. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27475. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27476. }
  27477. }
  27478. for (var passName in this._renderPasses) {
  27479. this._renderPasses[passName]._incRefCount();
  27480. }
  27481. }
  27482. };
  27483. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27484. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27485. for (var i = 0; i < _cam.length; i++) {
  27486. var camera = _cam[i];
  27487. var cameraName = camera.Name;
  27488. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27489. for (var passName in this._renderPasses) {
  27490. this._renderPasses[passName]._decRefCount();
  27491. }
  27492. }
  27493. };
  27494. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27495. if (this._singleInstance) {
  27496. return this._postProcesses[0];
  27497. }
  27498. else {
  27499. return this._postProcesses[camera.name];
  27500. }
  27501. };
  27502. PostProcessRenderEffect.prototype._linkParameters = function () {
  27503. var _this = this;
  27504. for (var index in this._postProcesses) {
  27505. if (this.applyParameters) {
  27506. this.applyParameters(this._postProcesses[index]);
  27507. }
  27508. this._postProcesses[index].onBeforeRender = function (effect) {
  27509. _this._linkTextures(effect);
  27510. };
  27511. }
  27512. };
  27513. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27514. for (var renderPassName in this._renderPasses) {
  27515. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27516. }
  27517. for (var renderEffectName in this._renderEffectAsPasses) {
  27518. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27519. }
  27520. };
  27521. return PostProcessRenderEffect;
  27522. })();
  27523. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27524. })(BABYLON || (BABYLON = {}));
  27525. var BABYLON;
  27526. (function (BABYLON) {
  27527. var PostProcessRenderPipeline = (function () {
  27528. function PostProcessRenderPipeline(engine, name) {
  27529. this._engine = engine;
  27530. this._name = name;
  27531. this._renderEffects = {};
  27532. this._renderEffectsForIsolatedPass = {};
  27533. this._cameras = [];
  27534. }
  27535. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27536. this._renderEffects[renderEffect._name] = renderEffect;
  27537. };
  27538. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27539. var renderEffects = this._renderEffects[renderEffectName];
  27540. if (!renderEffects) {
  27541. return;
  27542. }
  27543. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27544. };
  27545. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27546. var renderEffects = this._renderEffects[renderEffectName];
  27547. if (!renderEffects) {
  27548. return;
  27549. }
  27550. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27551. };
  27552. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27553. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27554. var indicesToDelete = [];
  27555. for (var i = 0; i < _cam.length; i++) {
  27556. var camera = _cam[i];
  27557. var cameraName = camera.name;
  27558. if (this._cameras.indexOf(camera) === -1) {
  27559. this._cameras[cameraName] = camera;
  27560. }
  27561. else if (unique) {
  27562. indicesToDelete.push(i);
  27563. }
  27564. }
  27565. for (var i = 0; i < indicesToDelete.length; i++) {
  27566. cameras.splice(indicesToDelete[i], 1);
  27567. }
  27568. for (var renderEffectName in this._renderEffects) {
  27569. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27570. }
  27571. };
  27572. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27573. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27574. for (var renderEffectName in this._renderEffects) {
  27575. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27576. }
  27577. for (var i = 0; i < _cam.length; i++) {
  27578. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27579. }
  27580. };
  27581. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27582. var _this = this;
  27583. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27584. var pass = null;
  27585. for (var renderEffectName in this._renderEffects) {
  27586. pass = this._renderEffects[renderEffectName].getPass(passName);
  27587. if (pass != null) {
  27588. break;
  27589. }
  27590. }
  27591. if (pass === null) {
  27592. return;
  27593. }
  27594. for (var renderEffectName in this._renderEffects) {
  27595. this._renderEffects[renderEffectName]._disable(_cam);
  27596. }
  27597. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27598. for (var i = 0; i < _cam.length; i++) {
  27599. var camera = _cam[i];
  27600. var cameraName = camera.name;
  27601. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  27602. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27603. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27604. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27605. }
  27606. };
  27607. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27608. var _this = this;
  27609. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27610. for (var i = 0; i < _cam.length; i++) {
  27611. var camera = _cam[i];
  27612. var cameraName = camera.name;
  27613. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  27614. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27615. }
  27616. for (var renderEffectName in this._renderEffects) {
  27617. this._renderEffects[renderEffectName]._enable(_cam);
  27618. }
  27619. };
  27620. PostProcessRenderPipeline.prototype._update = function () {
  27621. for (var renderEffectName in this._renderEffects) {
  27622. this._renderEffects[renderEffectName]._update();
  27623. }
  27624. for (var i = 0; i < this._cameras.length; i++) {
  27625. var cameraName = this._cameras[i].name;
  27626. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27627. this._renderEffectsForIsolatedPass[cameraName]._update();
  27628. }
  27629. }
  27630. };
  27631. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27632. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27633. return PostProcessRenderPipeline;
  27634. })();
  27635. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27636. })(BABYLON || (BABYLON = {}));
  27637. var BABYLON;
  27638. (function (BABYLON) {
  27639. var PostProcessRenderPipelineManager = (function () {
  27640. function PostProcessRenderPipelineManager() {
  27641. this._renderPipelines = {};
  27642. }
  27643. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27644. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27645. };
  27646. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27647. var renderPipeline = this._renderPipelines[renderPipelineName];
  27648. if (!renderPipeline) {
  27649. return;
  27650. }
  27651. renderPipeline._attachCameras(cameras, unique);
  27652. };
  27653. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27654. var renderPipeline = this._renderPipelines[renderPipelineName];
  27655. if (!renderPipeline) {
  27656. return;
  27657. }
  27658. renderPipeline._detachCameras(cameras);
  27659. };
  27660. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27661. var renderPipeline = this._renderPipelines[renderPipelineName];
  27662. if (!renderPipeline) {
  27663. return;
  27664. }
  27665. renderPipeline._enableEffect(renderEffectName, cameras);
  27666. };
  27667. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27668. var renderPipeline = this._renderPipelines[renderPipelineName];
  27669. if (!renderPipeline) {
  27670. return;
  27671. }
  27672. renderPipeline._disableEffect(renderEffectName, cameras);
  27673. };
  27674. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27675. var renderPipeline = this._renderPipelines[renderPipelineName];
  27676. if (!renderPipeline) {
  27677. return;
  27678. }
  27679. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27680. };
  27681. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27682. var renderPipeline = this._renderPipelines[renderPipelineName];
  27683. if (!renderPipeline) {
  27684. return;
  27685. }
  27686. renderPipeline._disableDisplayOnlyPass(cameras);
  27687. };
  27688. PostProcessRenderPipelineManager.prototype.update = function () {
  27689. for (var renderPipelineName in this._renderPipelines) {
  27690. this._renderPipelines[renderPipelineName]._update();
  27691. }
  27692. };
  27693. return PostProcessRenderPipelineManager;
  27694. })();
  27695. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27696. })(BABYLON || (BABYLON = {}));
  27697. var BABYLON;
  27698. (function (BABYLON) {
  27699. var DisplayPassPostProcess = (function (_super) {
  27700. __extends(DisplayPassPostProcess, _super);
  27701. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27702. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27703. }
  27704. return DisplayPassPostProcess;
  27705. })(BABYLON.PostProcess);
  27706. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27707. })(BABYLON || (BABYLON = {}));
  27708. var BABYLON;
  27709. (function (BABYLON) {
  27710. var BoundingBoxRenderer = (function () {
  27711. function BoundingBoxRenderer(scene) {
  27712. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27713. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27714. this.showBackLines = true;
  27715. this.renderList = new BABYLON.SmartArray(32);
  27716. this._scene = scene;
  27717. }
  27718. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27719. if (this._colorShader) {
  27720. return;
  27721. }
  27722. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27723. attributes: ["position"],
  27724. uniforms: ["worldViewProjection", "color"]
  27725. });
  27726. var engine = this._scene.getEngine();
  27727. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27728. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27729. 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]);
  27730. };
  27731. BoundingBoxRenderer.prototype.reset = function () {
  27732. this.renderList.reset();
  27733. };
  27734. BoundingBoxRenderer.prototype.render = function () {
  27735. if (this.renderList.length === 0) {
  27736. return;
  27737. }
  27738. this._prepareRessources();
  27739. if (!this._colorShader.isReady()) {
  27740. return;
  27741. }
  27742. var engine = this._scene.getEngine();
  27743. engine.setDepthWrite(false);
  27744. this._colorShader._preBind();
  27745. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27746. var boundingBox = this.renderList.data[boundingBoxIndex];
  27747. var min = boundingBox.minimum;
  27748. var max = boundingBox.maximum;
  27749. var diff = max.subtract(min);
  27750. var median = min.add(diff.scale(0.5));
  27751. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27752. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27753. .multiply(boundingBox.getWorldMatrix());
  27754. // VBOs
  27755. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27756. if (this.showBackLines) {
  27757. // Back
  27758. engine.setDepthFunctionToGreaterOrEqual();
  27759. this._scene.resetCachedMaterial();
  27760. this._colorShader.setColor4("color", this.backColor.toColor4());
  27761. this._colorShader.bind(worldMatrix);
  27762. // Draw order
  27763. engine.draw(false, 0, 24);
  27764. }
  27765. // Front
  27766. engine.setDepthFunctionToLess();
  27767. this._scene.resetCachedMaterial();
  27768. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27769. this._colorShader.bind(worldMatrix);
  27770. // Draw order
  27771. engine.draw(false, 0, 24);
  27772. }
  27773. this._colorShader.unbind();
  27774. engine.setDepthFunctionToLessOrEqual();
  27775. engine.setDepthWrite(true);
  27776. };
  27777. BoundingBoxRenderer.prototype.dispose = function () {
  27778. if (!this._colorShader) {
  27779. return;
  27780. }
  27781. this._colorShader.dispose();
  27782. this._vb.dispose();
  27783. this._scene.getEngine()._releaseBuffer(this._ib);
  27784. };
  27785. return BoundingBoxRenderer;
  27786. })();
  27787. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27788. })(BABYLON || (BABYLON = {}));
  27789. var BABYLON;
  27790. (function (BABYLON) {
  27791. var Condition = (function () {
  27792. function Condition(actionManager) {
  27793. this._actionManager = actionManager;
  27794. }
  27795. Condition.prototype.isValid = function () {
  27796. return true;
  27797. };
  27798. Condition.prototype._getProperty = function (propertyPath) {
  27799. return this._actionManager._getProperty(propertyPath);
  27800. };
  27801. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27802. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27803. };
  27804. return Condition;
  27805. })();
  27806. BABYLON.Condition = Condition;
  27807. var ValueCondition = (function (_super) {
  27808. __extends(ValueCondition, _super);
  27809. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27810. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27811. _super.call(this, actionManager);
  27812. this.propertyPath = propertyPath;
  27813. this.value = value;
  27814. this.operator = operator;
  27815. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27816. this._property = this._getProperty(this.propertyPath);
  27817. }
  27818. Object.defineProperty(ValueCondition, "IsEqual", {
  27819. get: function () {
  27820. return ValueCondition._IsEqual;
  27821. },
  27822. enumerable: true,
  27823. configurable: true
  27824. });
  27825. Object.defineProperty(ValueCondition, "IsDifferent", {
  27826. get: function () {
  27827. return ValueCondition._IsDifferent;
  27828. },
  27829. enumerable: true,
  27830. configurable: true
  27831. });
  27832. Object.defineProperty(ValueCondition, "IsGreater", {
  27833. get: function () {
  27834. return ValueCondition._IsGreater;
  27835. },
  27836. enumerable: true,
  27837. configurable: true
  27838. });
  27839. Object.defineProperty(ValueCondition, "IsLesser", {
  27840. get: function () {
  27841. return ValueCondition._IsLesser;
  27842. },
  27843. enumerable: true,
  27844. configurable: true
  27845. });
  27846. // Methods
  27847. ValueCondition.prototype.isValid = function () {
  27848. switch (this.operator) {
  27849. case ValueCondition.IsGreater:
  27850. return this._target[this._property] > this.value;
  27851. case ValueCondition.IsLesser:
  27852. return this._target[this._property] < this.value;
  27853. case ValueCondition.IsEqual:
  27854. case ValueCondition.IsDifferent:
  27855. var check;
  27856. if (this.value.equals) {
  27857. check = this.value.equals(this._target[this._property]);
  27858. }
  27859. else {
  27860. check = this.value === this._target[this._property];
  27861. }
  27862. return this.operator === ValueCondition.IsEqual ? check : !check;
  27863. }
  27864. return false;
  27865. };
  27866. // Statics
  27867. ValueCondition._IsEqual = 0;
  27868. ValueCondition._IsDifferent = 1;
  27869. ValueCondition._IsGreater = 2;
  27870. ValueCondition._IsLesser = 3;
  27871. return ValueCondition;
  27872. })(Condition);
  27873. BABYLON.ValueCondition = ValueCondition;
  27874. var PredicateCondition = (function (_super) {
  27875. __extends(PredicateCondition, _super);
  27876. function PredicateCondition(actionManager, predicate) {
  27877. _super.call(this, actionManager);
  27878. this.predicate = predicate;
  27879. }
  27880. PredicateCondition.prototype.isValid = function () {
  27881. return this.predicate();
  27882. };
  27883. return PredicateCondition;
  27884. })(Condition);
  27885. BABYLON.PredicateCondition = PredicateCondition;
  27886. var StateCondition = (function (_super) {
  27887. __extends(StateCondition, _super);
  27888. function StateCondition(actionManager, target, value) {
  27889. _super.call(this, actionManager);
  27890. this.value = value;
  27891. this._target = target;
  27892. }
  27893. // Methods
  27894. StateCondition.prototype.isValid = function () {
  27895. return this._target.state === this.value;
  27896. };
  27897. return StateCondition;
  27898. })(Condition);
  27899. BABYLON.StateCondition = StateCondition;
  27900. })(BABYLON || (BABYLON = {}));
  27901. var BABYLON;
  27902. (function (BABYLON) {
  27903. var Action = (function () {
  27904. function Action(triggerOptions, condition) {
  27905. this.triggerOptions = triggerOptions;
  27906. if (triggerOptions.parameter) {
  27907. this.trigger = triggerOptions.trigger;
  27908. this._triggerParameter = triggerOptions.parameter;
  27909. }
  27910. else {
  27911. this.trigger = triggerOptions;
  27912. }
  27913. this._nextActiveAction = this;
  27914. this._condition = condition;
  27915. }
  27916. // Methods
  27917. Action.prototype._prepare = function () {
  27918. };
  27919. Action.prototype.getTriggerParameter = function () {
  27920. return this._triggerParameter;
  27921. };
  27922. Action.prototype._executeCurrent = function (evt) {
  27923. if (this._nextActiveAction._condition) {
  27924. var condition = this._nextActiveAction._condition;
  27925. var currentRenderId = this._actionManager.getScene().getRenderId();
  27926. // We cache the current evaluation for the current frame
  27927. if (condition._evaluationId === currentRenderId) {
  27928. if (!condition._currentResult) {
  27929. return;
  27930. }
  27931. }
  27932. else {
  27933. condition._evaluationId = currentRenderId;
  27934. if (!condition.isValid()) {
  27935. condition._currentResult = false;
  27936. return;
  27937. }
  27938. condition._currentResult = true;
  27939. }
  27940. }
  27941. this._nextActiveAction.execute(evt);
  27942. if (this._nextActiveAction._child) {
  27943. if (!this._nextActiveAction._child._actionManager) {
  27944. this._nextActiveAction._child._actionManager = this._actionManager;
  27945. }
  27946. this._nextActiveAction = this._nextActiveAction._child;
  27947. }
  27948. else {
  27949. this._nextActiveAction = this;
  27950. }
  27951. };
  27952. Action.prototype.execute = function (evt) {
  27953. };
  27954. Action.prototype.then = function (action) {
  27955. this._child = action;
  27956. action._actionManager = this._actionManager;
  27957. action._prepare();
  27958. return action;
  27959. };
  27960. Action.prototype._getProperty = function (propertyPath) {
  27961. return this._actionManager._getProperty(propertyPath);
  27962. };
  27963. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27964. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27965. };
  27966. return Action;
  27967. })();
  27968. BABYLON.Action = Action;
  27969. })(BABYLON || (BABYLON = {}));
  27970. var BABYLON;
  27971. (function (BABYLON) {
  27972. /**
  27973. * ActionEvent is the event beint sent when an action is triggered.
  27974. */
  27975. var ActionEvent = (function () {
  27976. /**
  27977. * @constructor
  27978. * @param source The mesh that triggered the action.
  27979. * @param pointerX the X mouse cursor position at the time of the event
  27980. * @param pointerY the Y mouse cursor position at the time of the event
  27981. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27982. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27983. */
  27984. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27985. this.source = source;
  27986. this.pointerX = pointerX;
  27987. this.pointerY = pointerY;
  27988. this.meshUnderPointer = meshUnderPointer;
  27989. this.sourceEvent = sourceEvent;
  27990. this.additionalData = additionalData;
  27991. }
  27992. /**
  27993. * Helper function to auto-create an ActionEvent from a source mesh.
  27994. * @param source the source mesh that triggered the event
  27995. * @param evt {Event} The original (browser) event
  27996. */
  27997. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27998. var scene = source.getScene();
  27999. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28000. };
  28001. /**
  28002. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28003. * @param scene the scene where the event occurred
  28004. * @param evt {Event} The original (browser) event
  28005. */
  28006. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28007. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28008. };
  28009. return ActionEvent;
  28010. })();
  28011. BABYLON.ActionEvent = ActionEvent;
  28012. /**
  28013. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28014. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28015. */
  28016. var ActionManager = (function () {
  28017. function ActionManager(scene) {
  28018. // Members
  28019. this.actions = new Array();
  28020. this._scene = scene;
  28021. scene._actionManagers.push(this);
  28022. }
  28023. Object.defineProperty(ActionManager, "NothingTrigger", {
  28024. get: function () {
  28025. return ActionManager._NothingTrigger;
  28026. },
  28027. enumerable: true,
  28028. configurable: true
  28029. });
  28030. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28031. get: function () {
  28032. return ActionManager._OnPickTrigger;
  28033. },
  28034. enumerable: true,
  28035. configurable: true
  28036. });
  28037. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28038. get: function () {
  28039. return ActionManager._OnLeftPickTrigger;
  28040. },
  28041. enumerable: true,
  28042. configurable: true
  28043. });
  28044. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28045. get: function () {
  28046. return ActionManager._OnRightPickTrigger;
  28047. },
  28048. enumerable: true,
  28049. configurable: true
  28050. });
  28051. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28052. get: function () {
  28053. return ActionManager._OnCenterPickTrigger;
  28054. },
  28055. enumerable: true,
  28056. configurable: true
  28057. });
  28058. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28059. get: function () {
  28060. return ActionManager._OnPointerOverTrigger;
  28061. },
  28062. enumerable: true,
  28063. configurable: true
  28064. });
  28065. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28066. get: function () {
  28067. return ActionManager._OnPointerOutTrigger;
  28068. },
  28069. enumerable: true,
  28070. configurable: true
  28071. });
  28072. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28073. get: function () {
  28074. return ActionManager._OnEveryFrameTrigger;
  28075. },
  28076. enumerable: true,
  28077. configurable: true
  28078. });
  28079. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28080. get: function () {
  28081. return ActionManager._OnIntersectionEnterTrigger;
  28082. },
  28083. enumerable: true,
  28084. configurable: true
  28085. });
  28086. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28087. get: function () {
  28088. return ActionManager._OnIntersectionExitTrigger;
  28089. },
  28090. enumerable: true,
  28091. configurable: true
  28092. });
  28093. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28094. get: function () {
  28095. return ActionManager._OnKeyDownTrigger;
  28096. },
  28097. enumerable: true,
  28098. configurable: true
  28099. });
  28100. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28101. get: function () {
  28102. return ActionManager._OnKeyUpTrigger;
  28103. },
  28104. enumerable: true,
  28105. configurable: true
  28106. });
  28107. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28108. get: function () {
  28109. return ActionManager._OnPickUpTrigger;
  28110. },
  28111. enumerable: true,
  28112. configurable: true
  28113. });
  28114. // Methods
  28115. ActionManager.prototype.dispose = function () {
  28116. var index = this._scene._actionManagers.indexOf(this);
  28117. if (index > -1) {
  28118. this._scene._actionManagers.splice(index, 1);
  28119. }
  28120. };
  28121. ActionManager.prototype.getScene = function () {
  28122. return this._scene;
  28123. };
  28124. /**
  28125. * Does this action manager handles actions of any of the given triggers
  28126. * @param {number[]} triggers - the triggers to be tested
  28127. * @return {boolean} whether one (or more) of the triggers is handeled
  28128. */
  28129. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28130. for (var index = 0; index < this.actions.length; index++) {
  28131. var action = this.actions[index];
  28132. if (triggers.indexOf(action.trigger) > -1) {
  28133. return true;
  28134. }
  28135. }
  28136. return false;
  28137. };
  28138. /**
  28139. * Does this action manager handles actions of a given trigger
  28140. * @param {number} trigger - the trigger to be tested
  28141. * @return {boolean} whether the trigger is handeled
  28142. */
  28143. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28144. for (var index = 0; index < this.actions.length; index++) {
  28145. var action = this.actions[index];
  28146. if (action.trigger === trigger) {
  28147. return true;
  28148. }
  28149. }
  28150. return false;
  28151. };
  28152. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28153. /**
  28154. * Does this action manager has pointer triggers
  28155. * @return {boolean} whether or not it has pointer triggers
  28156. */
  28157. get: function () {
  28158. for (var index = 0; index < this.actions.length; index++) {
  28159. var action = this.actions[index];
  28160. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28161. return true;
  28162. }
  28163. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28164. return true;
  28165. }
  28166. }
  28167. return false;
  28168. },
  28169. enumerable: true,
  28170. configurable: true
  28171. });
  28172. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28173. /**
  28174. * Does this action manager has pick triggers
  28175. * @return {boolean} whether or not it has pick triggers
  28176. */
  28177. get: function () {
  28178. for (var index = 0; index < this.actions.length; index++) {
  28179. var action = this.actions[index];
  28180. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28181. return true;
  28182. }
  28183. }
  28184. return false;
  28185. },
  28186. enumerable: true,
  28187. configurable: true
  28188. });
  28189. /**
  28190. * Registers an action to this action manager
  28191. * @param {BABYLON.Action} action - the action to be registered
  28192. * @return {BABYLON.Action} the action amended (prepared) after registration
  28193. */
  28194. ActionManager.prototype.registerAction = function (action) {
  28195. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28196. if (this.getScene().actionManager !== this) {
  28197. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28198. return null;
  28199. }
  28200. }
  28201. this.actions.push(action);
  28202. action._actionManager = this;
  28203. action._prepare();
  28204. return action;
  28205. };
  28206. /**
  28207. * Process a specific trigger
  28208. * @param {number} trigger - the trigger to process
  28209. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28210. */
  28211. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28212. for (var index = 0; index < this.actions.length; index++) {
  28213. var action = this.actions[index];
  28214. if (action.trigger === trigger) {
  28215. if (trigger === ActionManager.OnKeyUpTrigger
  28216. || trigger === ActionManager.OnKeyDownTrigger) {
  28217. var parameter = action.getTriggerParameter();
  28218. if (parameter) {
  28219. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28220. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28221. if (actualkey !== parameter.toLowerCase()) {
  28222. continue;
  28223. }
  28224. }
  28225. }
  28226. action._executeCurrent(evt);
  28227. }
  28228. }
  28229. };
  28230. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28231. var properties = propertyPath.split(".");
  28232. for (var index = 0; index < properties.length - 1; index++) {
  28233. target = target[properties[index]];
  28234. }
  28235. return target;
  28236. };
  28237. ActionManager.prototype._getProperty = function (propertyPath) {
  28238. var properties = propertyPath.split(".");
  28239. return properties[properties.length - 1];
  28240. };
  28241. // Statics
  28242. ActionManager._NothingTrigger = 0;
  28243. ActionManager._OnPickTrigger = 1;
  28244. ActionManager._OnLeftPickTrigger = 2;
  28245. ActionManager._OnRightPickTrigger = 3;
  28246. ActionManager._OnCenterPickTrigger = 4;
  28247. ActionManager._OnPointerOverTrigger = 5;
  28248. ActionManager._OnPointerOutTrigger = 6;
  28249. ActionManager._OnEveryFrameTrigger = 7;
  28250. ActionManager._OnIntersectionEnterTrigger = 8;
  28251. ActionManager._OnIntersectionExitTrigger = 9;
  28252. ActionManager._OnKeyDownTrigger = 10;
  28253. ActionManager._OnKeyUpTrigger = 11;
  28254. ActionManager._OnPickUpTrigger = 12;
  28255. return ActionManager;
  28256. })();
  28257. BABYLON.ActionManager = ActionManager;
  28258. })(BABYLON || (BABYLON = {}));
  28259. var BABYLON;
  28260. (function (BABYLON) {
  28261. var InterpolateValueAction = (function (_super) {
  28262. __extends(InterpolateValueAction, _super);
  28263. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  28264. if (duration === void 0) { duration = 1000; }
  28265. _super.call(this, triggerOptions, condition);
  28266. this.propertyPath = propertyPath;
  28267. this.value = value;
  28268. this.duration = duration;
  28269. this.stopOtherAnimations = stopOtherAnimations;
  28270. this._target = target;
  28271. }
  28272. InterpolateValueAction.prototype._prepare = function () {
  28273. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28274. this._property = this._getProperty(this.propertyPath);
  28275. };
  28276. InterpolateValueAction.prototype.execute = function () {
  28277. var scene = this._actionManager.getScene();
  28278. var keys = [
  28279. {
  28280. frame: 0,
  28281. value: this._target[this._property]
  28282. }, {
  28283. frame: 100,
  28284. value: this.value
  28285. }
  28286. ];
  28287. var dataType;
  28288. if (typeof this.value === "number") {
  28289. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28290. }
  28291. else if (this.value instanceof BABYLON.Color3) {
  28292. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28293. }
  28294. else if (this.value instanceof BABYLON.Vector3) {
  28295. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28296. }
  28297. else if (this.value instanceof BABYLON.Matrix) {
  28298. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28299. }
  28300. else if (this.value instanceof BABYLON.Quaternion) {
  28301. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28302. }
  28303. else {
  28304. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28305. return;
  28306. }
  28307. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28308. animation.setKeys(keys);
  28309. if (this.stopOtherAnimations) {
  28310. scene.stopAnimation(this._target);
  28311. }
  28312. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28313. };
  28314. return InterpolateValueAction;
  28315. })(BABYLON.Action);
  28316. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28317. })(BABYLON || (BABYLON = {}));
  28318. var BABYLON;
  28319. (function (BABYLON) {
  28320. var SwitchBooleanAction = (function (_super) {
  28321. __extends(SwitchBooleanAction, _super);
  28322. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28323. _super.call(this, triggerOptions, condition);
  28324. this.propertyPath = propertyPath;
  28325. this._target = target;
  28326. }
  28327. SwitchBooleanAction.prototype._prepare = function () {
  28328. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28329. this._property = this._getProperty(this.propertyPath);
  28330. };
  28331. SwitchBooleanAction.prototype.execute = function () {
  28332. this._target[this._property] = !this._target[this._property];
  28333. };
  28334. return SwitchBooleanAction;
  28335. })(BABYLON.Action);
  28336. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28337. var SetStateAction = (function (_super) {
  28338. __extends(SetStateAction, _super);
  28339. function SetStateAction(triggerOptions, target, value, condition) {
  28340. _super.call(this, triggerOptions, condition);
  28341. this.value = value;
  28342. this._target = target;
  28343. }
  28344. SetStateAction.prototype.execute = function () {
  28345. this._target.state = this.value;
  28346. };
  28347. return SetStateAction;
  28348. })(BABYLON.Action);
  28349. BABYLON.SetStateAction = SetStateAction;
  28350. var SetValueAction = (function (_super) {
  28351. __extends(SetValueAction, _super);
  28352. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28353. _super.call(this, triggerOptions, condition);
  28354. this.propertyPath = propertyPath;
  28355. this.value = value;
  28356. this._target = target;
  28357. }
  28358. SetValueAction.prototype._prepare = function () {
  28359. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28360. this._property = this._getProperty(this.propertyPath);
  28361. };
  28362. SetValueAction.prototype.execute = function () {
  28363. this._target[this._property] = this.value;
  28364. };
  28365. return SetValueAction;
  28366. })(BABYLON.Action);
  28367. BABYLON.SetValueAction = SetValueAction;
  28368. var IncrementValueAction = (function (_super) {
  28369. __extends(IncrementValueAction, _super);
  28370. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28371. _super.call(this, triggerOptions, condition);
  28372. this.propertyPath = propertyPath;
  28373. this.value = value;
  28374. this._target = target;
  28375. }
  28376. IncrementValueAction.prototype._prepare = function () {
  28377. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28378. this._property = this._getProperty(this.propertyPath);
  28379. if (typeof this._target[this._property] !== "number") {
  28380. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28381. }
  28382. };
  28383. IncrementValueAction.prototype.execute = function () {
  28384. this._target[this._property] += this.value;
  28385. };
  28386. return IncrementValueAction;
  28387. })(BABYLON.Action);
  28388. BABYLON.IncrementValueAction = IncrementValueAction;
  28389. var PlayAnimationAction = (function (_super) {
  28390. __extends(PlayAnimationAction, _super);
  28391. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28392. _super.call(this, triggerOptions, condition);
  28393. this.from = from;
  28394. this.to = to;
  28395. this.loop = loop;
  28396. this._target = target;
  28397. }
  28398. PlayAnimationAction.prototype._prepare = function () {
  28399. };
  28400. PlayAnimationAction.prototype.execute = function () {
  28401. var scene = this._actionManager.getScene();
  28402. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28403. };
  28404. return PlayAnimationAction;
  28405. })(BABYLON.Action);
  28406. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28407. var StopAnimationAction = (function (_super) {
  28408. __extends(StopAnimationAction, _super);
  28409. function StopAnimationAction(triggerOptions, target, condition) {
  28410. _super.call(this, triggerOptions, condition);
  28411. this._target = target;
  28412. }
  28413. StopAnimationAction.prototype._prepare = function () {
  28414. };
  28415. StopAnimationAction.prototype.execute = function () {
  28416. var scene = this._actionManager.getScene();
  28417. scene.stopAnimation(this._target);
  28418. };
  28419. return StopAnimationAction;
  28420. })(BABYLON.Action);
  28421. BABYLON.StopAnimationAction = StopAnimationAction;
  28422. var DoNothingAction = (function (_super) {
  28423. __extends(DoNothingAction, _super);
  28424. function DoNothingAction(triggerOptions, condition) {
  28425. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28426. _super.call(this, triggerOptions, condition);
  28427. }
  28428. DoNothingAction.prototype.execute = function () {
  28429. };
  28430. return DoNothingAction;
  28431. })(BABYLON.Action);
  28432. BABYLON.DoNothingAction = DoNothingAction;
  28433. var CombineAction = (function (_super) {
  28434. __extends(CombineAction, _super);
  28435. function CombineAction(triggerOptions, children, condition) {
  28436. _super.call(this, triggerOptions, condition);
  28437. this.children = children;
  28438. }
  28439. CombineAction.prototype._prepare = function () {
  28440. for (var index = 0; index < this.children.length; index++) {
  28441. this.children[index]._actionManager = this._actionManager;
  28442. this.children[index]._prepare();
  28443. }
  28444. };
  28445. CombineAction.prototype.execute = function (evt) {
  28446. for (var index = 0; index < this.children.length; index++) {
  28447. this.children[index].execute(evt);
  28448. }
  28449. };
  28450. return CombineAction;
  28451. })(BABYLON.Action);
  28452. BABYLON.CombineAction = CombineAction;
  28453. var ExecuteCodeAction = (function (_super) {
  28454. __extends(ExecuteCodeAction, _super);
  28455. function ExecuteCodeAction(triggerOptions, func, condition) {
  28456. _super.call(this, triggerOptions, condition);
  28457. this.func = func;
  28458. }
  28459. ExecuteCodeAction.prototype.execute = function (evt) {
  28460. this.func(evt);
  28461. };
  28462. return ExecuteCodeAction;
  28463. })(BABYLON.Action);
  28464. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28465. var SetParentAction = (function (_super) {
  28466. __extends(SetParentAction, _super);
  28467. function SetParentAction(triggerOptions, target, parent, condition) {
  28468. _super.call(this, triggerOptions, condition);
  28469. this._target = target;
  28470. this._parent = parent;
  28471. }
  28472. SetParentAction.prototype._prepare = function () {
  28473. };
  28474. SetParentAction.prototype.execute = function () {
  28475. if (this._target.parent === this._parent) {
  28476. return;
  28477. }
  28478. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28479. invertParentWorldMatrix.invert();
  28480. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28481. this._target.parent = this._parent;
  28482. };
  28483. return SetParentAction;
  28484. })(BABYLON.Action);
  28485. BABYLON.SetParentAction = SetParentAction;
  28486. var PlaySoundAction = (function (_super) {
  28487. __extends(PlaySoundAction, _super);
  28488. function PlaySoundAction(triggerOptions, sound, condition) {
  28489. _super.call(this, triggerOptions, condition);
  28490. this._sound = sound;
  28491. }
  28492. PlaySoundAction.prototype._prepare = function () {
  28493. };
  28494. PlaySoundAction.prototype.execute = function () {
  28495. if (this._sound !== undefined)
  28496. this._sound.play();
  28497. };
  28498. return PlaySoundAction;
  28499. })(BABYLON.Action);
  28500. BABYLON.PlaySoundAction = PlaySoundAction;
  28501. var StopSoundAction = (function (_super) {
  28502. __extends(StopSoundAction, _super);
  28503. function StopSoundAction(triggerOptions, sound, condition) {
  28504. _super.call(this, triggerOptions, condition);
  28505. this._sound = sound;
  28506. }
  28507. StopSoundAction.prototype._prepare = function () {
  28508. };
  28509. StopSoundAction.prototype.execute = function () {
  28510. if (this._sound !== undefined)
  28511. this._sound.stop();
  28512. };
  28513. return StopSoundAction;
  28514. })(BABYLON.Action);
  28515. BABYLON.StopSoundAction = StopSoundAction;
  28516. })(BABYLON || (BABYLON = {}));
  28517. var BABYLON;
  28518. (function (BABYLON) {
  28519. var Geometry = (function () {
  28520. function Geometry(id, scene, vertexData, updatable, mesh) {
  28521. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28522. this._totalVertices = 0;
  28523. this._indices = [];
  28524. this._isDisposed = false;
  28525. this.id = id;
  28526. this._engine = scene.getEngine();
  28527. this._meshes = [];
  28528. this._scene = scene;
  28529. // vertexData
  28530. if (vertexData) {
  28531. this.setAllVerticesData(vertexData, updatable);
  28532. }
  28533. else {
  28534. this._totalVertices = 0;
  28535. this._indices = [];
  28536. }
  28537. // applyToMesh
  28538. if (mesh) {
  28539. this.applyToMesh(mesh);
  28540. mesh.computeWorldMatrix(true);
  28541. }
  28542. }
  28543. Geometry.prototype.getScene = function () {
  28544. return this._scene;
  28545. };
  28546. Geometry.prototype.getEngine = function () {
  28547. return this._engine;
  28548. };
  28549. Geometry.prototype.isReady = function () {
  28550. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28551. };
  28552. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28553. vertexData.applyToGeometry(this, updatable);
  28554. this.notifyUpdate();
  28555. };
  28556. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28557. this._vertexBuffers = this._vertexBuffers || {};
  28558. if (this._vertexBuffers[kind]) {
  28559. this._vertexBuffers[kind].dispose();
  28560. }
  28561. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28562. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28563. stride = this._vertexBuffers[kind].getStrideSize();
  28564. this._totalVertices = data.length / stride;
  28565. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28566. var meshes = this._meshes;
  28567. var numOfMeshes = meshes.length;
  28568. for (var index = 0; index < numOfMeshes; index++) {
  28569. var mesh = meshes[index];
  28570. mesh._resetPointsArrayCache();
  28571. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28572. mesh._createGlobalSubMesh();
  28573. mesh.computeWorldMatrix(true);
  28574. }
  28575. }
  28576. this.notifyUpdate(kind);
  28577. };
  28578. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28579. var vertexBuffer = this.getVertexBuffer(kind);
  28580. if (!vertexBuffer) {
  28581. return;
  28582. }
  28583. vertexBuffer.updateDirectly(data, offset);
  28584. this.notifyUpdate(kind);
  28585. };
  28586. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28587. var vertexBuffer = this.getVertexBuffer(kind);
  28588. if (!vertexBuffer) {
  28589. return;
  28590. }
  28591. vertexBuffer.update(data);
  28592. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28593. var extend;
  28594. var stride = vertexBuffer.getStrideSize();
  28595. this._totalVertices = data.length / stride;
  28596. if (updateExtends) {
  28597. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28598. }
  28599. var meshes = this._meshes;
  28600. var numOfMeshes = meshes.length;
  28601. for (var index = 0; index < numOfMeshes; index++) {
  28602. var mesh = meshes[index];
  28603. mesh._resetPointsArrayCache();
  28604. if (updateExtends) {
  28605. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28606. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28607. var subMesh = mesh.subMeshes[subIndex];
  28608. subMesh.refreshBoundingInfo();
  28609. }
  28610. }
  28611. }
  28612. }
  28613. this.notifyUpdate(kind);
  28614. };
  28615. Geometry.prototype.getTotalVertices = function () {
  28616. if (!this.isReady()) {
  28617. return 0;
  28618. }
  28619. return this._totalVertices;
  28620. };
  28621. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28622. var vertexBuffer = this.getVertexBuffer(kind);
  28623. if (!vertexBuffer) {
  28624. return null;
  28625. }
  28626. var orig = vertexBuffer.getData();
  28627. if (!copyWhenShared || this._meshes.length === 1) {
  28628. return orig;
  28629. }
  28630. else {
  28631. var len = orig.length;
  28632. var copy = [];
  28633. for (var i = 0; i < len; i++) {
  28634. copy.push(orig[i]);
  28635. }
  28636. return copy;
  28637. }
  28638. };
  28639. Geometry.prototype.getVertexBuffer = function (kind) {
  28640. if (!this.isReady()) {
  28641. return null;
  28642. }
  28643. return this._vertexBuffers[kind];
  28644. };
  28645. Geometry.prototype.getVertexBuffers = function () {
  28646. if (!this.isReady()) {
  28647. return null;
  28648. }
  28649. return this._vertexBuffers;
  28650. };
  28651. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28652. if (!this._vertexBuffers) {
  28653. if (this._delayInfo) {
  28654. return this._delayInfo.indexOf(kind) !== -1;
  28655. }
  28656. return false;
  28657. }
  28658. return this._vertexBuffers[kind] !== undefined;
  28659. };
  28660. Geometry.prototype.getVerticesDataKinds = function () {
  28661. var result = [];
  28662. if (!this._vertexBuffers && this._delayInfo) {
  28663. for (var kind in this._delayInfo) {
  28664. result.push(kind);
  28665. }
  28666. }
  28667. else {
  28668. for (kind in this._vertexBuffers) {
  28669. result.push(kind);
  28670. }
  28671. }
  28672. return result;
  28673. };
  28674. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28675. if (this._indexBuffer) {
  28676. this._engine._releaseBuffer(this._indexBuffer);
  28677. }
  28678. this._indices = indices;
  28679. if (this._meshes.length !== 0 && this._indices) {
  28680. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28681. }
  28682. if (totalVertices !== undefined) {
  28683. this._totalVertices = totalVertices;
  28684. }
  28685. var meshes = this._meshes;
  28686. var numOfMeshes = meshes.length;
  28687. for (var index = 0; index < numOfMeshes; index++) {
  28688. meshes[index]._createGlobalSubMesh();
  28689. }
  28690. this.notifyUpdate();
  28691. };
  28692. Geometry.prototype.getTotalIndices = function () {
  28693. if (!this.isReady()) {
  28694. return 0;
  28695. }
  28696. return this._indices.length;
  28697. };
  28698. Geometry.prototype.getIndices = function (copyWhenShared) {
  28699. if (!this.isReady()) {
  28700. return null;
  28701. }
  28702. var orig = this._indices;
  28703. if (!copyWhenShared || this._meshes.length === 1) {
  28704. return orig;
  28705. }
  28706. else {
  28707. var len = orig.length;
  28708. var copy = [];
  28709. for (var i = 0; i < len; i++) {
  28710. copy.push(orig[i]);
  28711. }
  28712. return copy;
  28713. }
  28714. };
  28715. Geometry.prototype.getIndexBuffer = function () {
  28716. if (!this.isReady()) {
  28717. return null;
  28718. }
  28719. return this._indexBuffer;
  28720. };
  28721. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28722. var meshes = this._meshes;
  28723. var index = meshes.indexOf(mesh);
  28724. if (index === -1) {
  28725. return;
  28726. }
  28727. for (var kind in this._vertexBuffers) {
  28728. this._vertexBuffers[kind].dispose();
  28729. }
  28730. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28731. this._indexBuffer = null;
  28732. }
  28733. meshes.splice(index, 1);
  28734. mesh._geometry = null;
  28735. if (meshes.length === 0 && shouldDispose) {
  28736. this.dispose();
  28737. }
  28738. };
  28739. Geometry.prototype.applyToMesh = function (mesh) {
  28740. if (mesh._geometry === this) {
  28741. return;
  28742. }
  28743. var previousGeometry = mesh._geometry;
  28744. if (previousGeometry) {
  28745. previousGeometry.releaseForMesh(mesh);
  28746. }
  28747. var meshes = this._meshes;
  28748. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28749. mesh._geometry = this;
  28750. this._scene.pushGeometry(this);
  28751. meshes.push(mesh);
  28752. if (this.isReady()) {
  28753. this._applyToMesh(mesh);
  28754. }
  28755. else {
  28756. mesh._boundingInfo = this._boundingInfo;
  28757. }
  28758. };
  28759. Geometry.prototype._applyToMesh = function (mesh) {
  28760. var numOfMeshes = this._meshes.length;
  28761. // vertexBuffers
  28762. for (var kind in this._vertexBuffers) {
  28763. if (numOfMeshes === 1) {
  28764. this._vertexBuffers[kind].create();
  28765. }
  28766. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28767. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28768. mesh._resetPointsArrayCache();
  28769. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28770. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28771. mesh._createGlobalSubMesh();
  28772. //bounding info was just created again, world matrix should be applied again.
  28773. mesh._updateBoundingInfo();
  28774. }
  28775. }
  28776. // indexBuffer
  28777. if (numOfMeshes === 1 && this._indices) {
  28778. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28779. }
  28780. if (this._indexBuffer) {
  28781. this._indexBuffer.references = numOfMeshes;
  28782. }
  28783. };
  28784. Geometry.prototype.notifyUpdate = function (kind) {
  28785. if (this.onGeometryUpdated) {
  28786. this.onGeometryUpdated(this, kind);
  28787. }
  28788. };
  28789. Geometry.prototype.load = function (scene, onLoaded) {
  28790. var _this = this;
  28791. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28792. return;
  28793. }
  28794. if (this.isReady()) {
  28795. if (onLoaded) {
  28796. onLoaded();
  28797. }
  28798. return;
  28799. }
  28800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28801. scene._addPendingData(this);
  28802. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28803. _this._delayLoadingFunction(JSON.parse(data), _this);
  28804. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28805. _this._delayInfo = [];
  28806. scene._removePendingData(_this);
  28807. var meshes = _this._meshes;
  28808. var numOfMeshes = meshes.length;
  28809. for (var index = 0; index < numOfMeshes; index++) {
  28810. _this._applyToMesh(meshes[index]);
  28811. }
  28812. if (onLoaded) {
  28813. onLoaded();
  28814. }
  28815. }, function () { }, scene.database);
  28816. };
  28817. Geometry.prototype.isDisposed = function () {
  28818. return this._isDisposed;
  28819. };
  28820. Geometry.prototype.dispose = function () {
  28821. var meshes = this._meshes;
  28822. var numOfMeshes = meshes.length;
  28823. var index;
  28824. for (index = 0; index < numOfMeshes; index++) {
  28825. this.releaseForMesh(meshes[index]);
  28826. }
  28827. this._meshes = [];
  28828. for (var kind in this._vertexBuffers) {
  28829. this._vertexBuffers[kind].dispose();
  28830. }
  28831. this._vertexBuffers = [];
  28832. this._totalVertices = 0;
  28833. if (this._indexBuffer) {
  28834. this._engine._releaseBuffer(this._indexBuffer);
  28835. }
  28836. this._indexBuffer = null;
  28837. this._indices = [];
  28838. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28839. this.delayLoadingFile = null;
  28840. this._delayLoadingFunction = null;
  28841. this._delayInfo = [];
  28842. this._boundingInfo = null; // todo: .dispose()
  28843. this._scene.removeGeometry(this);
  28844. this._isDisposed = true;
  28845. };
  28846. Geometry.prototype.copy = function (id) {
  28847. var vertexData = new BABYLON.VertexData();
  28848. vertexData.indices = [];
  28849. var indices = this.getIndices();
  28850. for (var index = 0; index < indices.length; index++) {
  28851. vertexData.indices.push(indices[index]);
  28852. }
  28853. var updatable = false;
  28854. var stopChecking = false;
  28855. for (var kind in this._vertexBuffers) {
  28856. // using slice() to make a copy of the array and not just reference it
  28857. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28858. if (!stopChecking) {
  28859. updatable = this.getVertexBuffer(kind).isUpdatable();
  28860. stopChecking = !updatable;
  28861. }
  28862. }
  28863. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28864. geometry.delayLoadState = this.delayLoadState;
  28865. geometry.delayLoadingFile = this.delayLoadingFile;
  28866. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28867. for (kind in this._delayInfo) {
  28868. geometry._delayInfo = geometry._delayInfo || [];
  28869. geometry._delayInfo.push(kind);
  28870. }
  28871. // Bounding info
  28872. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28873. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28874. return geometry;
  28875. };
  28876. // Statics
  28877. Geometry.ExtractFromMesh = function (mesh, id) {
  28878. var geometry = mesh._geometry;
  28879. if (!geometry) {
  28880. return null;
  28881. }
  28882. return geometry.copy(id);
  28883. };
  28884. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28885. // be aware Math.random() could cause collisions
  28886. Geometry.RandomId = function () {
  28887. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28888. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28889. return v.toString(16);
  28890. });
  28891. };
  28892. return Geometry;
  28893. })();
  28894. BABYLON.Geometry = Geometry;
  28895. /////// Primitives //////////////////////////////////////////////
  28896. var Geometry;
  28897. (function (Geometry) {
  28898. var Primitives;
  28899. (function (Primitives) {
  28900. /// Abstract class
  28901. var _Primitive = (function (_super) {
  28902. __extends(_Primitive, _super);
  28903. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28904. this._beingRegenerated = true;
  28905. this._canBeRegenerated = canBeRegenerated;
  28906. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28907. this._beingRegenerated = false;
  28908. }
  28909. _Primitive.prototype.canBeRegenerated = function () {
  28910. return this._canBeRegenerated;
  28911. };
  28912. _Primitive.prototype.regenerate = function () {
  28913. if (!this._canBeRegenerated) {
  28914. return;
  28915. }
  28916. this._beingRegenerated = true;
  28917. this.setAllVerticesData(this._regenerateVertexData(), false);
  28918. this._beingRegenerated = false;
  28919. };
  28920. _Primitive.prototype.asNewGeometry = function (id) {
  28921. return _super.prototype.copy.call(this, id);
  28922. };
  28923. // overrides
  28924. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28925. if (!this._beingRegenerated) {
  28926. return;
  28927. }
  28928. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28929. };
  28930. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28931. if (!this._beingRegenerated) {
  28932. return;
  28933. }
  28934. _super.prototype.setVerticesData.call(this, kind, data, false);
  28935. };
  28936. // to override
  28937. // protected
  28938. _Primitive.prototype._regenerateVertexData = function () {
  28939. throw new Error("Abstract method");
  28940. };
  28941. _Primitive.prototype.copy = function (id) {
  28942. throw new Error("Must be overriden in sub-classes.");
  28943. };
  28944. return _Primitive;
  28945. })(Geometry);
  28946. Primitives._Primitive = _Primitive;
  28947. var Ribbon = (function (_super) {
  28948. __extends(Ribbon, _super);
  28949. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28950. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28951. this.pathArray = pathArray;
  28952. this.closeArray = closeArray;
  28953. this.closePath = closePath;
  28954. this.offset = offset;
  28955. this.side = side;
  28956. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28957. }
  28958. Ribbon.prototype._regenerateVertexData = function () {
  28959. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28960. };
  28961. Ribbon.prototype.copy = function (id) {
  28962. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28963. };
  28964. return Ribbon;
  28965. })(_Primitive);
  28966. Primitives.Ribbon = Ribbon;
  28967. var Box = (function (_super) {
  28968. __extends(Box, _super);
  28969. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28970. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28971. this.size = size;
  28972. this.side = side;
  28973. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28974. }
  28975. Box.prototype._regenerateVertexData = function () {
  28976. return BABYLON.VertexData.CreateBox(this.size, this.side);
  28977. };
  28978. Box.prototype.copy = function (id) {
  28979. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28980. };
  28981. return Box;
  28982. })(_Primitive);
  28983. Primitives.Box = Box;
  28984. var Sphere = (function (_super) {
  28985. __extends(Sphere, _super);
  28986. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28987. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28988. this.segments = segments;
  28989. this.diameter = diameter;
  28990. this.side = side;
  28991. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28992. }
  28993. Sphere.prototype._regenerateVertexData = function () {
  28994. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  28995. };
  28996. Sphere.prototype.copy = function (id) {
  28997. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28998. };
  28999. return Sphere;
  29000. })(_Primitive);
  29001. Primitives.Sphere = Sphere;
  29002. var Cylinder = (function (_super) {
  29003. __extends(Cylinder, _super);
  29004. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29005. if (subdivisions === void 0) { subdivisions = 1; }
  29006. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29007. this.height = height;
  29008. this.diameterTop = diameterTop;
  29009. this.diameterBottom = diameterBottom;
  29010. this.tessellation = tessellation;
  29011. this.subdivisions = subdivisions;
  29012. this.side = side;
  29013. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29014. }
  29015. Cylinder.prototype._regenerateVertexData = function () {
  29016. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  29017. };
  29018. Cylinder.prototype.copy = function (id) {
  29019. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29020. };
  29021. return Cylinder;
  29022. })(_Primitive);
  29023. Primitives.Cylinder = Cylinder;
  29024. var Torus = (function (_super) {
  29025. __extends(Torus, _super);
  29026. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29027. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29028. this.diameter = diameter;
  29029. this.thickness = thickness;
  29030. this.tessellation = tessellation;
  29031. this.side = side;
  29032. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29033. }
  29034. Torus.prototype._regenerateVertexData = function () {
  29035. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  29036. };
  29037. Torus.prototype.copy = function (id) {
  29038. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29039. };
  29040. return Torus;
  29041. })(_Primitive);
  29042. Primitives.Torus = Torus;
  29043. var Ground = (function (_super) {
  29044. __extends(Ground, _super);
  29045. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29046. this.width = width;
  29047. this.height = height;
  29048. this.subdivisions = subdivisions;
  29049. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29050. }
  29051. Ground.prototype._regenerateVertexData = function () {
  29052. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  29053. };
  29054. Ground.prototype.copy = function (id) {
  29055. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29056. };
  29057. return Ground;
  29058. })(_Primitive);
  29059. Primitives.Ground = Ground;
  29060. var TiledGround = (function (_super) {
  29061. __extends(TiledGround, _super);
  29062. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29063. this.xmin = xmin;
  29064. this.zmin = zmin;
  29065. this.xmax = xmax;
  29066. this.zmax = zmax;
  29067. this.subdivisions = subdivisions;
  29068. this.precision = precision;
  29069. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29070. }
  29071. TiledGround.prototype._regenerateVertexData = function () {
  29072. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  29073. };
  29074. TiledGround.prototype.copy = function (id) {
  29075. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29076. };
  29077. return TiledGround;
  29078. })(_Primitive);
  29079. Primitives.TiledGround = TiledGround;
  29080. var Plane = (function (_super) {
  29081. __extends(Plane, _super);
  29082. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29083. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29084. this.size = size;
  29085. this.side = side;
  29086. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29087. }
  29088. Plane.prototype._regenerateVertexData = function () {
  29089. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  29090. };
  29091. Plane.prototype.copy = function (id) {
  29092. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29093. };
  29094. return Plane;
  29095. })(_Primitive);
  29096. Primitives.Plane = Plane;
  29097. var TorusKnot = (function (_super) {
  29098. __extends(TorusKnot, _super);
  29099. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29100. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29101. this.radius = radius;
  29102. this.tube = tube;
  29103. this.radialSegments = radialSegments;
  29104. this.tubularSegments = tubularSegments;
  29105. this.p = p;
  29106. this.q = q;
  29107. this.side = side;
  29108. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29109. }
  29110. TorusKnot.prototype._regenerateVertexData = function () {
  29111. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  29112. };
  29113. TorusKnot.prototype.copy = function (id) {
  29114. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29115. };
  29116. return TorusKnot;
  29117. })(_Primitive);
  29118. Primitives.TorusKnot = TorusKnot;
  29119. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29120. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29121. })(BABYLON || (BABYLON = {}));
  29122. var BABYLON;
  29123. (function (BABYLON) {
  29124. var GroundMesh = (function (_super) {
  29125. __extends(GroundMesh, _super);
  29126. function GroundMesh(name, scene) {
  29127. _super.call(this, name, scene);
  29128. this.generateOctree = false;
  29129. this._worldInverse = new BABYLON.Matrix();
  29130. }
  29131. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29132. get: function () {
  29133. return this._subdivisions;
  29134. },
  29135. enumerable: true,
  29136. configurable: true
  29137. });
  29138. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29139. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29140. this._subdivisions = chunksCount;
  29141. this.subdivide(this._subdivisions);
  29142. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29143. };
  29144. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29145. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29146. this.getWorldMatrix().invertToRef(this._worldInverse);
  29147. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29148. var pickInfo = this.intersects(ray);
  29149. if (pickInfo.hit) {
  29150. return pickInfo.pickedPoint.y;
  29151. }
  29152. return 0;
  29153. };
  29154. return GroundMesh;
  29155. })(BABYLON.Mesh);
  29156. BABYLON.GroundMesh = GroundMesh;
  29157. })(BABYLON || (BABYLON = {}));
  29158. var BABYLON;
  29159. (function (BABYLON) {
  29160. var LinesMesh = (function (_super) {
  29161. __extends(LinesMesh, _super);
  29162. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29163. if (parent === void 0) { parent = null; }
  29164. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29165. this.color = new BABYLON.Color3(1, 1, 1);
  29166. this.alpha = 1;
  29167. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29168. attributes: ["position"],
  29169. uniforms: ["worldViewProjection", "color"],
  29170. needAlphaBlending: true
  29171. });
  29172. }
  29173. Object.defineProperty(LinesMesh.prototype, "material", {
  29174. get: function () {
  29175. return this._colorShader;
  29176. },
  29177. enumerable: true,
  29178. configurable: true
  29179. });
  29180. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29181. get: function () {
  29182. return false;
  29183. },
  29184. enumerable: true,
  29185. configurable: true
  29186. });
  29187. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29188. get: function () {
  29189. return false;
  29190. },
  29191. enumerable: true,
  29192. configurable: true
  29193. });
  29194. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29195. var engine = this.getScene().getEngine();
  29196. var indexToBind = this._geometry.getIndexBuffer();
  29197. // VBOs
  29198. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29199. // Color
  29200. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29201. };
  29202. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29203. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29204. return;
  29205. }
  29206. var engine = this.getScene().getEngine();
  29207. // Draw order
  29208. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29209. };
  29210. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29211. return null;
  29212. };
  29213. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29214. this._colorShader.dispose();
  29215. _super.prototype.dispose.call(this, doNotRecurse);
  29216. };
  29217. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29218. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29219. };
  29220. return LinesMesh;
  29221. })(BABYLON.Mesh);
  29222. BABYLON.LinesMesh = LinesMesh;
  29223. })(BABYLON || (BABYLON = {}));
  29224. var BABYLON;
  29225. (function (BABYLON) {
  29226. var OutlineRenderer = (function () {
  29227. function OutlineRenderer(scene) {
  29228. this._scene = scene;
  29229. }
  29230. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29231. var _this = this;
  29232. if (useOverlay === void 0) { useOverlay = false; }
  29233. var scene = this._scene;
  29234. var engine = this._scene.getEngine();
  29235. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29236. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29237. return;
  29238. }
  29239. var mesh = subMesh.getRenderingMesh();
  29240. var material = subMesh.getMaterial();
  29241. engine.enableEffect(this._effect);
  29242. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29243. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29244. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29245. // Bones
  29246. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29247. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29248. }
  29249. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29250. // Alpha test
  29251. if (material && material.needAlphaTesting()) {
  29252. var alphaTexture = material.getAlphaTestTexture();
  29253. this._effect.setTexture("diffuseSampler", alphaTexture);
  29254. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29255. }
  29256. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29257. };
  29258. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29259. var defines = [];
  29260. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29261. var mesh = subMesh.getMesh();
  29262. var material = subMesh.getMaterial();
  29263. // Alpha test
  29264. if (material && material.needAlphaTesting()) {
  29265. defines.push("#define ALPHATEST");
  29266. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29267. attribs.push(BABYLON.VertexBuffer.UVKind);
  29268. defines.push("#define UV1");
  29269. }
  29270. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29271. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29272. defines.push("#define UV2");
  29273. }
  29274. }
  29275. // Bones
  29276. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29277. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29278. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29279. defines.push("#define BONES");
  29280. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29281. }
  29282. // Instances
  29283. if (useInstances) {
  29284. defines.push("#define INSTANCES");
  29285. attribs.push("world0");
  29286. attribs.push("world1");
  29287. attribs.push("world2");
  29288. attribs.push("world3");
  29289. }
  29290. // Get correct effect
  29291. var join = defines.join("\n");
  29292. if (this._cachedDefines !== join) {
  29293. this._cachedDefines = join;
  29294. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29295. }
  29296. return this._effect.isReady();
  29297. };
  29298. return OutlineRenderer;
  29299. })();
  29300. BABYLON.OutlineRenderer = OutlineRenderer;
  29301. })(BABYLON || (BABYLON = {}));
  29302. var BABYLON;
  29303. (function (BABYLON) {
  29304. var MeshAssetTask = (function () {
  29305. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29306. this.name = name;
  29307. this.meshesNames = meshesNames;
  29308. this.rootUrl = rootUrl;
  29309. this.sceneFilename = sceneFilename;
  29310. this.isCompleted = false;
  29311. }
  29312. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29313. var _this = this;
  29314. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29315. _this.loadedMeshes = meshes;
  29316. _this.loadedParticleSystems = particleSystems;
  29317. _this.loadedSkeletons = skeletons;
  29318. _this.isCompleted = true;
  29319. if (_this.onSuccess) {
  29320. _this.onSuccess(_this);
  29321. }
  29322. onSuccess();
  29323. }, null, function () {
  29324. if (_this.onError) {
  29325. _this.onError(_this);
  29326. }
  29327. onError();
  29328. });
  29329. };
  29330. return MeshAssetTask;
  29331. })();
  29332. BABYLON.MeshAssetTask = MeshAssetTask;
  29333. var TextFileAssetTask = (function () {
  29334. function TextFileAssetTask(name, url) {
  29335. this.name = name;
  29336. this.url = url;
  29337. this.isCompleted = false;
  29338. }
  29339. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29340. var _this = this;
  29341. BABYLON.Tools.LoadFile(this.url, function (data) {
  29342. _this.text = data;
  29343. _this.isCompleted = true;
  29344. if (_this.onSuccess) {
  29345. _this.onSuccess(_this);
  29346. }
  29347. onSuccess();
  29348. }, null, scene.database, false, function () {
  29349. if (_this.onError) {
  29350. _this.onError(_this);
  29351. }
  29352. onError();
  29353. });
  29354. };
  29355. return TextFileAssetTask;
  29356. })();
  29357. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29358. var BinaryFileAssetTask = (function () {
  29359. function BinaryFileAssetTask(name, url) {
  29360. this.name = name;
  29361. this.url = url;
  29362. this.isCompleted = false;
  29363. }
  29364. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29365. var _this = this;
  29366. BABYLON.Tools.LoadFile(this.url, function (data) {
  29367. _this.data = data;
  29368. _this.isCompleted = true;
  29369. if (_this.onSuccess) {
  29370. _this.onSuccess(_this);
  29371. }
  29372. onSuccess();
  29373. }, null, scene.database, true, function () {
  29374. if (_this.onError) {
  29375. _this.onError(_this);
  29376. }
  29377. onError();
  29378. });
  29379. };
  29380. return BinaryFileAssetTask;
  29381. })();
  29382. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29383. var ImageAssetTask = (function () {
  29384. function ImageAssetTask(name, url) {
  29385. this.name = name;
  29386. this.url = url;
  29387. this.isCompleted = false;
  29388. }
  29389. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29390. var _this = this;
  29391. var img = new Image();
  29392. img.onload = function () {
  29393. _this.image = img;
  29394. _this.isCompleted = true;
  29395. if (_this.onSuccess) {
  29396. _this.onSuccess(_this);
  29397. }
  29398. onSuccess();
  29399. };
  29400. img.onerror = function () {
  29401. if (_this.onError) {
  29402. _this.onError(_this);
  29403. }
  29404. onError();
  29405. };
  29406. img.src = this.url;
  29407. };
  29408. return ImageAssetTask;
  29409. })();
  29410. BABYLON.ImageAssetTask = ImageAssetTask;
  29411. var TextureAssetTask = (function () {
  29412. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29414. this.name = name;
  29415. this.url = url;
  29416. this.noMipmap = noMipmap;
  29417. this.invertY = invertY;
  29418. this.samplingMode = samplingMode;
  29419. this.isCompleted = false;
  29420. }
  29421. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29422. var _this = this;
  29423. var onload = function () {
  29424. _this.isCompleted = true;
  29425. if (_this.onSuccess) {
  29426. _this.onSuccess(_this);
  29427. }
  29428. onSuccess();
  29429. };
  29430. var onerror = function () {
  29431. if (_this.onError) {
  29432. _this.onError(_this);
  29433. }
  29434. onError();
  29435. };
  29436. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29437. };
  29438. return TextureAssetTask;
  29439. })();
  29440. BABYLON.TextureAssetTask = TextureAssetTask;
  29441. var AssetsManager = (function () {
  29442. function AssetsManager(scene) {
  29443. this._tasks = new Array();
  29444. this._waitingTasksCount = 0;
  29445. this.useDefaultLoadingScreen = true;
  29446. this._scene = scene;
  29447. }
  29448. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29449. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29450. this._tasks.push(task);
  29451. return task;
  29452. };
  29453. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29454. var task = new TextFileAssetTask(taskName, url);
  29455. this._tasks.push(task);
  29456. return task;
  29457. };
  29458. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29459. var task = new BinaryFileAssetTask(taskName, url);
  29460. this._tasks.push(task);
  29461. return task;
  29462. };
  29463. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29464. var task = new ImageAssetTask(taskName, url);
  29465. this._tasks.push(task);
  29466. return task;
  29467. };
  29468. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29470. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29471. this._tasks.push(task);
  29472. return task;
  29473. };
  29474. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29475. this._waitingTasksCount--;
  29476. if (this._waitingTasksCount === 0) {
  29477. if (this.onFinish) {
  29478. this.onFinish(this._tasks);
  29479. }
  29480. this._scene.getEngine().hideLoadingUI();
  29481. }
  29482. };
  29483. AssetsManager.prototype._runTask = function (task) {
  29484. var _this = this;
  29485. task.run(this._scene, function () {
  29486. if (_this.onTaskSuccess) {
  29487. _this.onTaskSuccess(task);
  29488. }
  29489. _this._decreaseWaitingTasksCount();
  29490. }, function () {
  29491. if (_this.onTaskError) {
  29492. _this.onTaskError(task);
  29493. }
  29494. _this._decreaseWaitingTasksCount();
  29495. });
  29496. };
  29497. AssetsManager.prototype.reset = function () {
  29498. this._tasks = new Array();
  29499. return this;
  29500. };
  29501. AssetsManager.prototype.load = function () {
  29502. this._waitingTasksCount = this._tasks.length;
  29503. if (this._waitingTasksCount === 0) {
  29504. if (this.onFinish) {
  29505. this.onFinish(this._tasks);
  29506. }
  29507. return this;
  29508. }
  29509. if (this.useDefaultLoadingScreen) {
  29510. this._scene.getEngine().displayLoadingUI();
  29511. }
  29512. for (var index = 0; index < this._tasks.length; index++) {
  29513. var task = this._tasks[index];
  29514. this._runTask(task);
  29515. }
  29516. return this;
  29517. };
  29518. return AssetsManager;
  29519. })();
  29520. BABYLON.AssetsManager = AssetsManager;
  29521. })(BABYLON || (BABYLON = {}));
  29522. var BABYLON;
  29523. (function (BABYLON) {
  29524. var VRDeviceOrientationFreeCamera = (function (_super) {
  29525. __extends(VRDeviceOrientationFreeCamera, _super);
  29526. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29527. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29528. _super.call(this, name, position, scene);
  29529. this._alpha = 0;
  29530. this._beta = 0;
  29531. this._gamma = 0;
  29532. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29533. metrics.compensateDistorsion = compensateDistorsion;
  29534. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29535. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29536. }
  29537. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29538. this._alpha = +evt.alpha | 0;
  29539. this._beta = +evt.beta | 0;
  29540. this._gamma = +evt.gamma | 0;
  29541. if (this._gamma < 0) {
  29542. this._gamma = 90 + this._gamma;
  29543. }
  29544. else {
  29545. // Incline it in the correct angle.
  29546. this._gamma = 270 - this._gamma;
  29547. }
  29548. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29549. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29550. this.rotation.z = this._beta / 180.0 * Math.PI;
  29551. };
  29552. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29553. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29554. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29555. };
  29556. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29557. _super.prototype.detachControl.call(this, element);
  29558. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29559. };
  29560. return VRDeviceOrientationFreeCamera;
  29561. })(BABYLON.FreeCamera);
  29562. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29563. })(BABYLON || (BABYLON = {}));
  29564. var BABYLON;
  29565. (function (BABYLON) {
  29566. var WebVRFreeCamera = (function (_super) {
  29567. __extends(WebVRFreeCamera, _super);
  29568. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29569. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29570. _super.call(this, name, position, scene);
  29571. this._hmdDevice = null;
  29572. this._sensorDevice = null;
  29573. this._cacheState = null;
  29574. this._cacheQuaternion = new BABYLON.Quaternion();
  29575. this._cacheRotation = BABYLON.Vector3.Zero();
  29576. this._vrEnabled = false;
  29577. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29578. metrics.compensateDistorsion = compensateDistorsion;
  29579. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29580. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29581. }
  29582. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29583. var size = devices.length;
  29584. var i = 0;
  29585. // Reset devices.
  29586. this._sensorDevice = null;
  29587. this._hmdDevice = null;
  29588. // Search for a HmdDevice.
  29589. while (i < size && this._hmdDevice === null) {
  29590. if (devices[i] instanceof HMDVRDevice) {
  29591. this._hmdDevice = devices[i];
  29592. }
  29593. i++;
  29594. }
  29595. i = 0;
  29596. while (i < size && this._sensorDevice === null) {
  29597. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29598. this._sensorDevice = devices[i];
  29599. }
  29600. i++;
  29601. }
  29602. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29603. };
  29604. WebVRFreeCamera.prototype._checkInputs = function () {
  29605. if (this._vrEnabled) {
  29606. this._cacheState = this._sensorDevice.getState();
  29607. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29608. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29609. this.rotation.x = -this._cacheRotation.z;
  29610. this.rotation.y = -this._cacheRotation.y;
  29611. this.rotation.z = this._cacheRotation.x;
  29612. }
  29613. _super.prototype._checkInputs.call(this);
  29614. };
  29615. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29616. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29617. if (navigator.getVRDevices) {
  29618. navigator.getVRDevices().then(this._getWebVRDevices);
  29619. }
  29620. else if (navigator.mozGetVRDevices) {
  29621. navigator.mozGetVRDevices(this._getWebVRDevices);
  29622. }
  29623. };
  29624. WebVRFreeCamera.prototype.detachControl = function (element) {
  29625. _super.prototype.detachControl.call(this, element);
  29626. this._vrEnabled = false;
  29627. };
  29628. return WebVRFreeCamera;
  29629. })(BABYLON.FreeCamera);
  29630. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29631. })(BABYLON || (BABYLON = {}));
  29632. var BABYLON;
  29633. (function (BABYLON) {
  29634. // Standard optimizations
  29635. var SceneOptimization = (function () {
  29636. function SceneOptimization(priority) {
  29637. if (priority === void 0) { priority = 0; }
  29638. this.priority = priority;
  29639. this.apply = function (scene) {
  29640. return true; // Return true if everything that can be done was applied
  29641. };
  29642. }
  29643. return SceneOptimization;
  29644. })();
  29645. BABYLON.SceneOptimization = SceneOptimization;
  29646. var TextureOptimization = (function (_super) {
  29647. __extends(TextureOptimization, _super);
  29648. function TextureOptimization(priority, maximumSize) {
  29649. var _this = this;
  29650. if (priority === void 0) { priority = 0; }
  29651. if (maximumSize === void 0) { maximumSize = 1024; }
  29652. _super.call(this, priority);
  29653. this.priority = priority;
  29654. this.maximumSize = maximumSize;
  29655. this.apply = function (scene) {
  29656. var allDone = true;
  29657. for (var index = 0; index < scene.textures.length; index++) {
  29658. var texture = scene.textures[index];
  29659. if (!texture.canRescale) {
  29660. continue;
  29661. }
  29662. var currentSize = texture.getSize();
  29663. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29664. if (maxDimension > _this.maximumSize) {
  29665. texture.scale(0.5);
  29666. allDone = false;
  29667. }
  29668. }
  29669. return allDone;
  29670. };
  29671. }
  29672. return TextureOptimization;
  29673. })(SceneOptimization);
  29674. BABYLON.TextureOptimization = TextureOptimization;
  29675. var HardwareScalingOptimization = (function (_super) {
  29676. __extends(HardwareScalingOptimization, _super);
  29677. function HardwareScalingOptimization(priority, maximumScale) {
  29678. var _this = this;
  29679. if (priority === void 0) { priority = 0; }
  29680. if (maximumScale === void 0) { maximumScale = 2; }
  29681. _super.call(this, priority);
  29682. this.priority = priority;
  29683. this.maximumScale = maximumScale;
  29684. this._currentScale = 1;
  29685. this.apply = function (scene) {
  29686. _this._currentScale++;
  29687. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29688. return _this._currentScale >= _this.maximumScale;
  29689. };
  29690. }
  29691. return HardwareScalingOptimization;
  29692. })(SceneOptimization);
  29693. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29694. var ShadowsOptimization = (function (_super) {
  29695. __extends(ShadowsOptimization, _super);
  29696. function ShadowsOptimization() {
  29697. _super.apply(this, arguments);
  29698. this.apply = function (scene) {
  29699. scene.shadowsEnabled = false;
  29700. return true;
  29701. };
  29702. }
  29703. return ShadowsOptimization;
  29704. })(SceneOptimization);
  29705. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29706. var PostProcessesOptimization = (function (_super) {
  29707. __extends(PostProcessesOptimization, _super);
  29708. function PostProcessesOptimization() {
  29709. _super.apply(this, arguments);
  29710. this.apply = function (scene) {
  29711. scene.postProcessesEnabled = false;
  29712. return true;
  29713. };
  29714. }
  29715. return PostProcessesOptimization;
  29716. })(SceneOptimization);
  29717. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29718. var LensFlaresOptimization = (function (_super) {
  29719. __extends(LensFlaresOptimization, _super);
  29720. function LensFlaresOptimization() {
  29721. _super.apply(this, arguments);
  29722. this.apply = function (scene) {
  29723. scene.lensFlaresEnabled = false;
  29724. return true;
  29725. };
  29726. }
  29727. return LensFlaresOptimization;
  29728. })(SceneOptimization);
  29729. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29730. var ParticlesOptimization = (function (_super) {
  29731. __extends(ParticlesOptimization, _super);
  29732. function ParticlesOptimization() {
  29733. _super.apply(this, arguments);
  29734. this.apply = function (scene) {
  29735. scene.particlesEnabled = false;
  29736. return true;
  29737. };
  29738. }
  29739. return ParticlesOptimization;
  29740. })(SceneOptimization);
  29741. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29742. var RenderTargetsOptimization = (function (_super) {
  29743. __extends(RenderTargetsOptimization, _super);
  29744. function RenderTargetsOptimization() {
  29745. _super.apply(this, arguments);
  29746. this.apply = function (scene) {
  29747. scene.renderTargetsEnabled = false;
  29748. return true;
  29749. };
  29750. }
  29751. return RenderTargetsOptimization;
  29752. })(SceneOptimization);
  29753. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29754. var MergeMeshesOptimization = (function (_super) {
  29755. __extends(MergeMeshesOptimization, _super);
  29756. function MergeMeshesOptimization() {
  29757. var _this = this;
  29758. _super.apply(this, arguments);
  29759. this._canBeMerged = function (abstractMesh) {
  29760. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29761. return false;
  29762. }
  29763. var mesh = abstractMesh;
  29764. if (!mesh.isVisible || !mesh.isEnabled()) {
  29765. return false;
  29766. }
  29767. if (mesh.instances.length > 0) {
  29768. return false;
  29769. }
  29770. if (mesh.skeleton || mesh.hasLODLevels) {
  29771. return false;
  29772. }
  29773. return true;
  29774. };
  29775. this.apply = function (scene, updateSelectionTree) {
  29776. var globalPool = scene.meshes.slice(0);
  29777. var globalLength = globalPool.length;
  29778. for (var index = 0; index < globalLength; index++) {
  29779. var currentPool = new Array();
  29780. var current = globalPool[index];
  29781. // Checks
  29782. if (!_this._canBeMerged(current)) {
  29783. continue;
  29784. }
  29785. currentPool.push(current);
  29786. // Find compatible meshes
  29787. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29788. var otherMesh = globalPool[subIndex];
  29789. if (!_this._canBeMerged(otherMesh)) {
  29790. continue;
  29791. }
  29792. if (otherMesh.material !== current.material) {
  29793. continue;
  29794. }
  29795. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29796. continue;
  29797. }
  29798. currentPool.push(otherMesh);
  29799. globalLength--;
  29800. globalPool.splice(subIndex, 1);
  29801. subIndex--;
  29802. }
  29803. if (currentPool.length < 2) {
  29804. continue;
  29805. }
  29806. // Merge meshes
  29807. BABYLON.Mesh.MergeMeshes(currentPool);
  29808. }
  29809. if (updateSelectionTree != undefined) {
  29810. if (updateSelectionTree) {
  29811. scene.createOrUpdateSelectionOctree();
  29812. }
  29813. }
  29814. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29815. scene.createOrUpdateSelectionOctree();
  29816. }
  29817. return true;
  29818. };
  29819. }
  29820. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29821. get: function () {
  29822. return MergeMeshesOptimization._UpdateSelectionTree;
  29823. },
  29824. set: function (value) {
  29825. MergeMeshesOptimization._UpdateSelectionTree = value;
  29826. },
  29827. enumerable: true,
  29828. configurable: true
  29829. });
  29830. MergeMeshesOptimization._UpdateSelectionTree = false;
  29831. return MergeMeshesOptimization;
  29832. })(SceneOptimization);
  29833. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29834. // Options
  29835. var SceneOptimizerOptions = (function () {
  29836. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29837. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29838. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29839. this.targetFrameRate = targetFrameRate;
  29840. this.trackerDuration = trackerDuration;
  29841. this.optimizations = new Array();
  29842. }
  29843. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29844. var result = new SceneOptimizerOptions(targetFrameRate);
  29845. var priority = 0;
  29846. result.optimizations.push(new MergeMeshesOptimization(priority));
  29847. result.optimizations.push(new ShadowsOptimization(priority));
  29848. result.optimizations.push(new LensFlaresOptimization(priority));
  29849. // Next priority
  29850. priority++;
  29851. result.optimizations.push(new PostProcessesOptimization(priority));
  29852. result.optimizations.push(new ParticlesOptimization(priority));
  29853. // Next priority
  29854. priority++;
  29855. result.optimizations.push(new TextureOptimization(priority, 1024));
  29856. return result;
  29857. };
  29858. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29859. var result = new SceneOptimizerOptions(targetFrameRate);
  29860. var priority = 0;
  29861. result.optimizations.push(new MergeMeshesOptimization(priority));
  29862. result.optimizations.push(new ShadowsOptimization(priority));
  29863. result.optimizations.push(new LensFlaresOptimization(priority));
  29864. // Next priority
  29865. priority++;
  29866. result.optimizations.push(new PostProcessesOptimization(priority));
  29867. result.optimizations.push(new ParticlesOptimization(priority));
  29868. // Next priority
  29869. priority++;
  29870. result.optimizations.push(new TextureOptimization(priority, 512));
  29871. // Next priority
  29872. priority++;
  29873. result.optimizations.push(new RenderTargetsOptimization(priority));
  29874. // Next priority
  29875. priority++;
  29876. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29877. return result;
  29878. };
  29879. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29880. var result = new SceneOptimizerOptions(targetFrameRate);
  29881. var priority = 0;
  29882. result.optimizations.push(new MergeMeshesOptimization(priority));
  29883. result.optimizations.push(new ShadowsOptimization(priority));
  29884. result.optimizations.push(new LensFlaresOptimization(priority));
  29885. // Next priority
  29886. priority++;
  29887. result.optimizations.push(new PostProcessesOptimization(priority));
  29888. result.optimizations.push(new ParticlesOptimization(priority));
  29889. // Next priority
  29890. priority++;
  29891. result.optimizations.push(new TextureOptimization(priority, 256));
  29892. // Next priority
  29893. priority++;
  29894. result.optimizations.push(new RenderTargetsOptimization(priority));
  29895. // Next priority
  29896. priority++;
  29897. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29898. return result;
  29899. };
  29900. return SceneOptimizerOptions;
  29901. })();
  29902. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29903. // Scene optimizer tool
  29904. var SceneOptimizer = (function () {
  29905. function SceneOptimizer() {
  29906. }
  29907. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29908. // TODO: add an epsilon
  29909. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29910. if (onSuccess) {
  29911. onSuccess();
  29912. }
  29913. return;
  29914. }
  29915. // Apply current level of optimizations
  29916. var allDone = true;
  29917. var noOptimizationApplied = true;
  29918. for (var index = 0; index < options.optimizations.length; index++) {
  29919. var optimization = options.optimizations[index];
  29920. if (optimization.priority === currentPriorityLevel) {
  29921. noOptimizationApplied = false;
  29922. allDone = allDone && optimization.apply(scene);
  29923. }
  29924. }
  29925. // If no optimization was applied, this is a failure :(
  29926. if (noOptimizationApplied) {
  29927. if (onFailure) {
  29928. onFailure();
  29929. }
  29930. return;
  29931. }
  29932. // If all optimizations were done, move to next level
  29933. if (allDone) {
  29934. currentPriorityLevel++;
  29935. }
  29936. // Let's the system running for a specific amount of time before checking FPS
  29937. scene.executeWhenReady(function () {
  29938. setTimeout(function () {
  29939. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29940. }, options.trackerDuration);
  29941. });
  29942. };
  29943. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29944. if (!options) {
  29945. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29946. }
  29947. // Let's the system running for a specific amount of time before checking FPS
  29948. scene.executeWhenReady(function () {
  29949. setTimeout(function () {
  29950. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29951. }, options.trackerDuration);
  29952. });
  29953. };
  29954. return SceneOptimizer;
  29955. })();
  29956. BABYLON.SceneOptimizer = SceneOptimizer;
  29957. })(BABYLON || (BABYLON = {}));
  29958. var BABYLON;
  29959. (function (BABYLON) {
  29960. var Internals;
  29961. (function (Internals) {
  29962. var MeshLODLevel = (function () {
  29963. function MeshLODLevel(distance, mesh) {
  29964. this.distance = distance;
  29965. this.mesh = mesh;
  29966. }
  29967. return MeshLODLevel;
  29968. })();
  29969. Internals.MeshLODLevel = MeshLODLevel;
  29970. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29971. })(BABYLON || (BABYLON = {}));
  29972. var BABYLON;
  29973. (function (BABYLON) {
  29974. var AudioEngine = (function () {
  29975. function AudioEngine() {
  29976. this._audioContext = null;
  29977. this._audioContextInitialized = false;
  29978. this.canUseWebAudio = false;
  29979. this.WarnedWebAudioUnsupported = false;
  29980. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29981. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29982. this.canUseWebAudio = true;
  29983. }
  29984. }
  29985. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29986. get: function () {
  29987. if (!this._audioContextInitialized) {
  29988. this._initializeAudioContext();
  29989. }
  29990. return this._audioContext;
  29991. },
  29992. enumerable: true,
  29993. configurable: true
  29994. });
  29995. AudioEngine.prototype._initializeAudioContext = function () {
  29996. try {
  29997. if (this.canUseWebAudio) {
  29998. this._audioContext = new AudioContext();
  29999. // create a global volume gain node
  30000. this.masterGain = this._audioContext.createGain();
  30001. this.masterGain.gain.value = 1;
  30002. this.masterGain.connect(this._audioContext.destination);
  30003. this._audioContextInitialized = true;
  30004. }
  30005. }
  30006. catch (e) {
  30007. this.canUseWebAudio = false;
  30008. BABYLON.Tools.Error("Web Audio: " + e.message);
  30009. }
  30010. };
  30011. AudioEngine.prototype.dispose = function () {
  30012. if (this.canUseWebAudio && this._audioContextInitialized) {
  30013. if (this._connectedAnalyser) {
  30014. this._connectedAnalyser.stopDebugCanvas();
  30015. this._connectedAnalyser.dispose();
  30016. this.masterGain.disconnect();
  30017. this.masterGain.connect(this._audioContext.destination);
  30018. this._connectedAnalyser = null;
  30019. }
  30020. this.masterGain.gain.value = 1;
  30021. }
  30022. this.WarnedWebAudioUnsupported = false;
  30023. };
  30024. AudioEngine.prototype.getGlobalVolume = function () {
  30025. if (this.canUseWebAudio && this._audioContextInitialized) {
  30026. return this.masterGain.gain.value;
  30027. }
  30028. else {
  30029. return -1;
  30030. }
  30031. };
  30032. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  30033. if (this.canUseWebAudio && this._audioContextInitialized) {
  30034. this.masterGain.gain.value = newVolume;
  30035. }
  30036. };
  30037. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  30038. if (this._connectedAnalyser) {
  30039. this._connectedAnalyser.stopDebugCanvas();
  30040. }
  30041. if (this.canUseWebAudio && this._audioContextInitialized) {
  30042. this._connectedAnalyser = analyser;
  30043. this.masterGain.disconnect();
  30044. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  30045. }
  30046. };
  30047. return AudioEngine;
  30048. })();
  30049. BABYLON.AudioEngine = AudioEngine;
  30050. })(BABYLON || (BABYLON = {}));
  30051. var BABYLON;
  30052. (function (BABYLON) {
  30053. var Sound = (function () {
  30054. /**
  30055. * Create a sound and attach it to a scene
  30056. * @param name Name of your sound
  30057. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  30058. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  30059. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  30060. */
  30061. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  30062. var _this = this;
  30063. this.autoplay = false;
  30064. this.loop = false;
  30065. this.useCustomAttenuation = false;
  30066. this.spatialSound = false;
  30067. this.refDistance = 1;
  30068. this.rolloffFactor = 1;
  30069. this.maxDistance = 100;
  30070. this.distanceModel = "linear";
  30071. this._panningModel = "equalpower";
  30072. this._playbackRate = 1;
  30073. this._startTime = 0;
  30074. this._startOffset = 0;
  30075. this._position = BABYLON.Vector3.Zero();
  30076. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30077. this._volume = 1;
  30078. this._isLoaded = false;
  30079. this._isReadyToPlay = false;
  30080. this.isPlaying = false;
  30081. this.isPaused = false;
  30082. this._isDirectional = false;
  30083. // Used if you'd like to create a directional sound.
  30084. // If not set, the sound will be omnidirectional
  30085. this._coneInnerAngle = 360;
  30086. this._coneOuterAngle = 360;
  30087. this._coneOuterGain = 0;
  30088. this._isOutputConnected = false;
  30089. this.name = name;
  30090. this._scene = scene;
  30091. this._readyToPlayCallback = readyToPlayCallback;
  30092. // Default custom attenuation function is a linear attenuation
  30093. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30094. if (currentDistance < maxDistance) {
  30095. return currentVolume * (1 - currentDistance / maxDistance);
  30096. }
  30097. else {
  30098. return 0;
  30099. }
  30100. };
  30101. if (options) {
  30102. this.autoplay = options.autoplay || false;
  30103. this.loop = options.loop || false;
  30104. // if volume === 0, we need another way to check this option
  30105. if (options.volume !== undefined) {
  30106. this._volume = options.volume;
  30107. }
  30108. this.spatialSound = options.spatialSound || false;
  30109. this.maxDistance = options.maxDistance || 100;
  30110. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30111. this.rolloffFactor = options.rolloffFactor || 1;
  30112. this.refDistance = options.refDistance || 1;
  30113. this.distanceModel = options.distanceModel || "linear";
  30114. this._playbackRate = options.playbackRate || 1;
  30115. }
  30116. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30117. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30118. this._soundGain.gain.value = this._volume;
  30119. this._inputAudioNode = this._soundGain;
  30120. this._ouputAudioNode = this._soundGain;
  30121. if (this.spatialSound) {
  30122. this._createSpatialParameters();
  30123. }
  30124. this._scene.mainSoundTrack.AddSound(this);
  30125. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30126. if (urlOrArrayBuffer) {
  30127. // If it's an URL
  30128. if (typeof (urlOrArrayBuffer) === "string") {
  30129. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30130. }
  30131. else {
  30132. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30133. this._soundLoaded(urlOrArrayBuffer);
  30134. }
  30135. else {
  30136. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30137. }
  30138. }
  30139. }
  30140. }
  30141. else {
  30142. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30143. this._scene.mainSoundTrack.AddSound(this);
  30144. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30145. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30146. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30147. }
  30148. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30149. if (this._readyToPlayCallback) {
  30150. window.setTimeout(function () {
  30151. _this._readyToPlayCallback();
  30152. }, 1000);
  30153. }
  30154. }
  30155. }
  30156. Sound.prototype.dispose = function () {
  30157. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30158. if (this.isPlaying) {
  30159. this.stop();
  30160. }
  30161. this._isReadyToPlay = false;
  30162. if (this.soundTrackId === -1) {
  30163. this._scene.mainSoundTrack.RemoveSound(this);
  30164. }
  30165. else {
  30166. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30167. }
  30168. if (this._soundGain) {
  30169. this._soundGain.disconnect();
  30170. this._soundGain = null;
  30171. }
  30172. if (this._soundPanner) {
  30173. this._soundPanner.disconnect();
  30174. this._soundPanner = null;
  30175. }
  30176. if (this._soundSource) {
  30177. this._soundSource.disconnect();
  30178. this._soundSource = null;
  30179. }
  30180. this._audioBuffer = null;
  30181. if (this._connectedMesh) {
  30182. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30183. this._connectedMesh = null;
  30184. }
  30185. }
  30186. };
  30187. Sound.prototype._soundLoaded = function (audioData) {
  30188. var _this = this;
  30189. this._isLoaded = true;
  30190. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30191. _this._audioBuffer = buffer;
  30192. _this._isReadyToPlay = true;
  30193. if (_this.autoplay) {
  30194. _this.play();
  30195. }
  30196. if (_this._readyToPlayCallback) {
  30197. _this._readyToPlayCallback();
  30198. }
  30199. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30200. };
  30201. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30202. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30203. this._audioBuffer = audioBuffer;
  30204. this._isReadyToPlay = true;
  30205. }
  30206. };
  30207. Sound.prototype.updateOptions = function (options) {
  30208. if (options) {
  30209. this.loop = options.loop || this.loop;
  30210. this.maxDistance = options.maxDistance || this.maxDistance;
  30211. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30212. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30213. this.refDistance = options.refDistance || this.refDistance;
  30214. this.distanceModel = options.distanceModel || this.distanceModel;
  30215. this._playbackRate = options.playbackRate || this._playbackRate;
  30216. this._updateSpatialParameters();
  30217. if (this.isPlaying) {
  30218. this._soundSource.playbackRate.value = this._playbackRate;
  30219. }
  30220. }
  30221. };
  30222. Sound.prototype._createSpatialParameters = function () {
  30223. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30224. if (this._scene.headphone) {
  30225. this._panningModel = "HRTF";
  30226. }
  30227. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30228. this._updateSpatialParameters();
  30229. this._soundPanner.connect(this._ouputAudioNode);
  30230. this._inputAudioNode = this._soundPanner;
  30231. }
  30232. };
  30233. Sound.prototype._updateSpatialParameters = function () {
  30234. if (this.spatialSound) {
  30235. if (this.useCustomAttenuation) {
  30236. // Tricks to disable in a way embedded Web Audio attenuation
  30237. this._soundPanner.distanceModel = "linear";
  30238. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30239. this._soundPanner.refDistance = 1;
  30240. this._soundPanner.rolloffFactor = 1;
  30241. this._soundPanner.panningModel = this._panningModel;
  30242. }
  30243. else {
  30244. this._soundPanner.distanceModel = this.distanceModel;
  30245. this._soundPanner.maxDistance = this.maxDistance;
  30246. this._soundPanner.refDistance = this.refDistance;
  30247. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30248. this._soundPanner.panningModel = this._panningModel;
  30249. }
  30250. }
  30251. };
  30252. Sound.prototype.switchPanningModelToHRTF = function () {
  30253. this._panningModel = "HRTF";
  30254. this._switchPanningModel();
  30255. };
  30256. Sound.prototype.switchPanningModelToEqualPower = function () {
  30257. this._panningModel = "equalpower";
  30258. this._switchPanningModel();
  30259. };
  30260. Sound.prototype._switchPanningModel = function () {
  30261. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30262. this._soundPanner.panningModel = this._panningModel;
  30263. }
  30264. };
  30265. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30266. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30267. if (this._isOutputConnected) {
  30268. this._ouputAudioNode.disconnect();
  30269. }
  30270. this._ouputAudioNode.connect(soundTrackAudioNode);
  30271. this._isOutputConnected = true;
  30272. }
  30273. };
  30274. /**
  30275. * Transform this sound into a directional source
  30276. * @param coneInnerAngle Size of the inner cone in degree
  30277. * @param coneOuterAngle Size of the outer cone in degree
  30278. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30279. */
  30280. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30281. if (coneOuterAngle < coneInnerAngle) {
  30282. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30283. return;
  30284. }
  30285. this._coneInnerAngle = coneInnerAngle;
  30286. this._coneOuterAngle = coneOuterAngle;
  30287. this._coneOuterGain = coneOuterGain;
  30288. this._isDirectional = true;
  30289. if (this.isPlaying && this.loop) {
  30290. this.stop();
  30291. this.play();
  30292. }
  30293. };
  30294. Sound.prototype.setPosition = function (newPosition) {
  30295. this._position = newPosition;
  30296. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30297. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30298. }
  30299. };
  30300. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30301. this._localDirection = newLocalDirection;
  30302. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30303. this._updateDirection();
  30304. }
  30305. };
  30306. Sound.prototype._updateDirection = function () {
  30307. var mat = this._connectedMesh.getWorldMatrix();
  30308. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30309. direction.normalize();
  30310. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30311. };
  30312. Sound.prototype.updateDistanceFromListener = function () {
  30313. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30314. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30315. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30316. }
  30317. };
  30318. Sound.prototype.setAttenuationFunction = function (callback) {
  30319. this._customAttenuationFunction = callback;
  30320. };
  30321. /**
  30322. * Play the sound
  30323. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30324. */
  30325. Sound.prototype.play = function (time) {
  30326. var _this = this;
  30327. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30328. try {
  30329. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30330. if (!this._soundSource) {
  30331. if (this.spatialSound) {
  30332. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30333. if (this._isDirectional) {
  30334. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30335. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30336. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30337. if (this._connectedMesh) {
  30338. this._updateDirection();
  30339. }
  30340. else {
  30341. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30342. }
  30343. }
  30344. }
  30345. }
  30346. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30347. this._soundSource.buffer = this._audioBuffer;
  30348. this._soundSource.connect(this._inputAudioNode);
  30349. this._soundSource.loop = this.loop;
  30350. this._soundSource.playbackRate.value = this._playbackRate;
  30351. this._startTime = startTime;
  30352. this._soundSource.onended = function () { _this._onended(); };
  30353. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30354. this.isPlaying = true;
  30355. this.isPaused = false;
  30356. }
  30357. catch (ex) {
  30358. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30359. }
  30360. }
  30361. };
  30362. Sound.prototype._onended = function () {
  30363. this.isPlaying = false;
  30364. if (this.onended) {
  30365. this.onended();
  30366. }
  30367. };
  30368. /**
  30369. * Stop the sound
  30370. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30371. */
  30372. Sound.prototype.stop = function (time) {
  30373. if (this.isPlaying) {
  30374. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30375. this._soundSource.stop(stopTime);
  30376. this.isPlaying = false;
  30377. }
  30378. };
  30379. Sound.prototype.pause = function () {
  30380. if (this.isPlaying) {
  30381. this.stop(0);
  30382. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30383. this.isPaused = true;
  30384. }
  30385. };
  30386. Sound.prototype.setVolume = function (newVolume, time) {
  30387. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30388. if (time) {
  30389. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30390. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30391. }
  30392. else {
  30393. this._soundGain.gain.value = newVolume;
  30394. }
  30395. }
  30396. this._volume = newVolume;
  30397. };
  30398. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30399. this._playbackRate = newPlaybackRate;
  30400. if (this.isPlaying) {
  30401. this._soundSource.playbackRate.value = this._playbackRate;
  30402. }
  30403. };
  30404. Sound.prototype.getVolume = function () {
  30405. return this._volume;
  30406. };
  30407. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30408. var _this = this;
  30409. this._connectedMesh = meshToConnectTo;
  30410. if (!this.spatialSound) {
  30411. this.spatialSound = true;
  30412. this._createSpatialParameters();
  30413. if (this.isPlaying && this.loop) {
  30414. this.stop();
  30415. this.play();
  30416. }
  30417. }
  30418. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30419. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30420. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30421. };
  30422. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30423. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30424. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30425. this._updateDirection();
  30426. }
  30427. };
  30428. return Sound;
  30429. })();
  30430. BABYLON.Sound = Sound;
  30431. })(BABYLON || (BABYLON = {}));
  30432. var BABYLON;
  30433. (function (BABYLON) {
  30434. var SoundTrack = (function () {
  30435. function SoundTrack(scene, options) {
  30436. this.id = -1;
  30437. this._isMainTrack = false;
  30438. this._scene = scene;
  30439. this._audioEngine = BABYLON.Engine.audioEngine;
  30440. this.soundCollection = new Array();
  30441. if (this._audioEngine.canUseWebAudio) {
  30442. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30443. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30444. if (options) {
  30445. if (options.volume) {
  30446. this._outputAudioNode.gain.value = options.volume;
  30447. }
  30448. if (options.mainTrack) {
  30449. this._isMainTrack = options.mainTrack;
  30450. }
  30451. }
  30452. }
  30453. if (!this._isMainTrack) {
  30454. this._scene.soundTracks.push(this);
  30455. this.id = this._scene.soundTracks.length - 1;
  30456. }
  30457. }
  30458. SoundTrack.prototype.dispose = function () {
  30459. if (this._audioEngine.canUseWebAudio) {
  30460. if (this._connectedAnalyser) {
  30461. this._connectedAnalyser.stopDebugCanvas();
  30462. }
  30463. while (this.soundCollection.length) {
  30464. this.soundCollection[0].dispose();
  30465. }
  30466. if (this._outputAudioNode) {
  30467. this._outputAudioNode.disconnect();
  30468. }
  30469. this._outputAudioNode = null;
  30470. }
  30471. };
  30472. SoundTrack.prototype.AddSound = function (sound) {
  30473. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30474. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30475. }
  30476. if (sound.soundTrackId) {
  30477. if (sound.soundTrackId === -1) {
  30478. this._scene.mainSoundTrack.RemoveSound(sound);
  30479. }
  30480. else {
  30481. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30482. }
  30483. }
  30484. this.soundCollection.push(sound);
  30485. sound.soundTrackId = this.id;
  30486. };
  30487. SoundTrack.prototype.RemoveSound = function (sound) {
  30488. var index = this.soundCollection.indexOf(sound);
  30489. if (index !== -1) {
  30490. this.soundCollection.splice(index, 1);
  30491. }
  30492. };
  30493. SoundTrack.prototype.setVolume = function (newVolume) {
  30494. if (this._audioEngine.canUseWebAudio) {
  30495. this._outputAudioNode.gain.value = newVolume;
  30496. }
  30497. };
  30498. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30499. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30500. for (var i = 0; i < this.soundCollection.length; i++) {
  30501. this.soundCollection[i].switchPanningModelToHRTF();
  30502. }
  30503. }
  30504. };
  30505. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30506. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30507. for (var i = 0; i < this.soundCollection.length; i++) {
  30508. this.soundCollection[i].switchPanningModelToEqualPower();
  30509. }
  30510. }
  30511. };
  30512. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30513. if (this._connectedAnalyser) {
  30514. this._connectedAnalyser.stopDebugCanvas();
  30515. }
  30516. this._connectedAnalyser = analyser;
  30517. if (this._audioEngine.canUseWebAudio) {
  30518. this._outputAudioNode.disconnect();
  30519. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30520. }
  30521. };
  30522. return SoundTrack;
  30523. })();
  30524. BABYLON.SoundTrack = SoundTrack;
  30525. })(BABYLON || (BABYLON = {}));
  30526. var BABYLON;
  30527. (function (BABYLON) {
  30528. var DebugLayer = (function () {
  30529. function DebugLayer(scene) {
  30530. var _this = this;
  30531. this._transformationMatrix = BABYLON.Matrix.Identity();
  30532. this._enabled = false;
  30533. this._labelsEnabled = false;
  30534. this._displayStatistics = true;
  30535. this._displayTree = false;
  30536. this._displayLogs = false;
  30537. this._identityMatrix = BABYLON.Matrix.Identity();
  30538. this.axisRatio = 0.02;
  30539. this.accentColor = "orange";
  30540. this._scene = scene;
  30541. this._syncPositions = function () {
  30542. var engine = _this._scene.getEngine();
  30543. var canvasRect = engine.getRenderingCanvasClientRect();
  30544. if (_this._showUI) {
  30545. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30546. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30547. _this._statsDiv.style.width = "400px";
  30548. _this._statsDiv.style.height = "auto";
  30549. _this._statsSubsetDiv.style.maxHeight = "240px";
  30550. _this._optionsDiv.style.left = "0px";
  30551. _this._optionsDiv.style.top = "10px";
  30552. _this._optionsDiv.style.width = "200px";
  30553. _this._optionsDiv.style.height = "auto";
  30554. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30555. _this._logDiv.style.left = "0px";
  30556. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30557. _this._logDiv.style.width = "600px";
  30558. _this._logDiv.style.height = "160px";
  30559. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30560. _this._treeDiv.style.top = "10px";
  30561. _this._treeDiv.style.width = "300px";
  30562. _this._treeDiv.style.height = "auto";
  30563. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30564. }
  30565. _this._globalDiv.style.left = canvasRect.left + "px";
  30566. _this._globalDiv.style.top = canvasRect.top + "px";
  30567. _this._drawingCanvas.style.left = "0px";
  30568. _this._drawingCanvas.style.top = "0px";
  30569. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30570. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30571. var devicePixelRatio = window.devicePixelRatio || 1;
  30572. var context = _this._drawingContext;
  30573. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30574. context.mozBackingStorePixelRatio ||
  30575. context.msBackingStorePixelRatio ||
  30576. context.oBackingStorePixelRatio ||
  30577. context.backingStorePixelRatio || 1;
  30578. _this._ratio = devicePixelRatio / backingStoreRatio;
  30579. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30580. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30581. };
  30582. this._onCanvasClick = function (evt) {
  30583. _this._clickPosition = {
  30584. x: evt.clientX * _this._ratio,
  30585. y: evt.clientY * _this._ratio
  30586. };
  30587. };
  30588. this._syncUI = function () {
  30589. if (_this._showUI) {
  30590. if (_this._displayStatistics) {
  30591. _this._displayStats();
  30592. _this._statsDiv.style.display = "";
  30593. }
  30594. else {
  30595. _this._statsDiv.style.display = "none";
  30596. }
  30597. if (_this._displayLogs) {
  30598. _this._logDiv.style.display = "";
  30599. }
  30600. else {
  30601. _this._logDiv.style.display = "none";
  30602. }
  30603. if (_this._displayTree) {
  30604. _this._treeDiv.style.display = "";
  30605. if (_this._needToRefreshMeshesTree) {
  30606. _this._needToRefreshMeshesTree = false;
  30607. _this._refreshMeshesTreeContent();
  30608. }
  30609. }
  30610. else {
  30611. _this._treeDiv.style.display = "none";
  30612. }
  30613. }
  30614. };
  30615. this._syncData = function () {
  30616. if (_this._labelsEnabled || !_this._showUI) {
  30617. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30618. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30619. var engine = _this._scene.getEngine();
  30620. var viewport = _this._camera.viewport;
  30621. var globalViewport = viewport.toGlobal(engine);
  30622. // Meshes
  30623. var meshes = _this._camera.getActiveMeshes();
  30624. for (var index = 0; index < meshes.length; index++) {
  30625. var mesh = meshes.data[index];
  30626. var position = mesh.getBoundingInfo().boundingSphere.center;
  30627. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30628. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30629. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30630. }
  30631. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30632. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30633. }
  30634. }
  30635. // Cameras
  30636. var cameras = _this._scene.cameras;
  30637. for (index = 0; index < cameras.length; index++) {
  30638. var camera = cameras[index];
  30639. if (camera === _this._camera) {
  30640. continue;
  30641. }
  30642. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30643. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30644. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30645. _this._camera.detachControl(engine.getRenderingCanvas());
  30646. _this._camera = camera;
  30647. _this._camera.attachControl(engine.getRenderingCanvas());
  30648. }, function () { return "purple"; });
  30649. }
  30650. }
  30651. // Lights
  30652. var lights = _this._scene.lights;
  30653. for (index = 0; index < lights.length; index++) {
  30654. var light = lights[index];
  30655. if (light.position) {
  30656. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30657. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30658. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30659. light.setEnabled(!light.isEnabled());
  30660. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30661. }
  30662. }
  30663. }
  30664. }
  30665. _this._clickPosition = undefined;
  30666. };
  30667. }
  30668. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30669. while (this._treeSubsetDiv.hasChildNodes()) {
  30670. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30671. }
  30672. // Add meshes
  30673. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30674. sortedArray.sort(function (a, b) {
  30675. if (a.name === b.name) {
  30676. return 0;
  30677. }
  30678. return (a.name > b.name) ? 1 : -1;
  30679. });
  30680. for (var index = 0; index < sortedArray.length; index++) {
  30681. var mesh = sortedArray[index];
  30682. if (!mesh.isEnabled()) {
  30683. continue;
  30684. }
  30685. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30686. m.isVisible = element.checked;
  30687. }, mesh);
  30688. }
  30689. };
  30690. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30691. this._drawingContext.beginPath();
  30692. this._drawingContext.moveTo(zero.x, zero.y);
  30693. this._drawingContext.lineTo(unit.x, unit.y);
  30694. this._drawingContext.strokeStyle = color;
  30695. this._drawingContext.lineWidth = 4;
  30696. this._drawingContext.stroke();
  30697. this._drawingContext.font = "normal 14px Segoe UI";
  30698. this._drawingContext.fillStyle = color;
  30699. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30700. };
  30701. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30702. var position = mesh.getBoundingInfo().boundingSphere.center;
  30703. var worldMatrix = mesh.getWorldMatrix();
  30704. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30705. var unit = (unprojectedVector.subtract(position)).length();
  30706. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30707. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30708. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30709. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30710. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30711. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30712. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30713. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30714. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30715. };
  30716. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30717. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30718. this._drawingContext.font = "normal 12px Segoe UI";
  30719. var textMetrics = this._drawingContext.measureText(text);
  30720. var centerX = projectedPosition.x - textMetrics.width / 2;
  30721. var centerY = projectedPosition.y;
  30722. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30723. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30724. onClick();
  30725. }
  30726. this._drawingContext.beginPath();
  30727. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30728. this._drawingContext.fillStyle = getFillStyle();
  30729. this._drawingContext.globalAlpha = 0.5;
  30730. this._drawingContext.fill();
  30731. this._drawingContext.globalAlpha = 1.0;
  30732. this._drawingContext.strokeStyle = '#FFFFFF';
  30733. this._drawingContext.lineWidth = 1;
  30734. this._drawingContext.stroke();
  30735. this._drawingContext.fillStyle = "#FFFFFF";
  30736. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30737. this._drawingContext.beginPath();
  30738. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30739. this._drawingContext.fill();
  30740. }
  30741. };
  30742. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30743. if (!this._clickPosition) {
  30744. return false;
  30745. }
  30746. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30747. return false;
  30748. }
  30749. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30750. return false;
  30751. }
  30752. return true;
  30753. };
  30754. DebugLayer.prototype.isVisible = function () {
  30755. return this._enabled;
  30756. };
  30757. DebugLayer.prototype.hide = function () {
  30758. if (!this._enabled) {
  30759. return;
  30760. }
  30761. this._enabled = false;
  30762. var engine = this._scene.getEngine();
  30763. this._scene.unregisterBeforeRender(this._syncData);
  30764. this._scene.unregisterAfterRender(this._syncUI);
  30765. document.body.removeChild(this._globalDiv);
  30766. window.removeEventListener("resize", this._syncPositions);
  30767. this._scene.forceShowBoundingBoxes = false;
  30768. this._scene.forceWireframe = false;
  30769. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30770. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30771. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30772. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30773. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30774. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30775. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30776. this._scene.shadowsEnabled = true;
  30777. this._scene.particlesEnabled = true;
  30778. this._scene.postProcessesEnabled = true;
  30779. this._scene.collisionsEnabled = true;
  30780. this._scene.lightsEnabled = true;
  30781. this._scene.texturesEnabled = true;
  30782. this._scene.lensFlaresEnabled = true;
  30783. this._scene.proceduralTexturesEnabled = true;
  30784. this._scene.renderTargetsEnabled = true;
  30785. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30786. };
  30787. DebugLayer.prototype.show = function (showUI, camera) {
  30788. if (showUI === void 0) { showUI = true; }
  30789. if (camera === void 0) { camera = null; }
  30790. if (this._enabled) {
  30791. return;
  30792. }
  30793. this._enabled = true;
  30794. if (camera) {
  30795. this._camera = camera;
  30796. }
  30797. else {
  30798. this._camera = this._scene.activeCamera;
  30799. }
  30800. this._showUI = showUI;
  30801. var engine = this._scene.getEngine();
  30802. this._globalDiv = document.createElement("div");
  30803. document.body.appendChild(this._globalDiv);
  30804. this._generateDOMelements();
  30805. window.addEventListener("resize", this._syncPositions);
  30806. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30807. this._syncPositions();
  30808. this._scene.registerBeforeRender(this._syncData);
  30809. this._scene.registerAfterRender(this._syncUI);
  30810. };
  30811. DebugLayer.prototype._clearLabels = function () {
  30812. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30813. for (var index = 0; index < this._scene.meshes.length; index++) {
  30814. var mesh = this._scene.meshes[index];
  30815. mesh.renderOverlay = false;
  30816. }
  30817. };
  30818. DebugLayer.prototype._generateheader = function (root, text) {
  30819. var header = document.createElement("div");
  30820. header.innerHTML = text + "&nbsp;";
  30821. header.style.textAlign = "right";
  30822. header.style.width = "100%";
  30823. header.style.color = "white";
  30824. header.style.backgroundColor = "Black";
  30825. header.style.padding = "5px 5px 4px 0px";
  30826. header.style.marginLeft = "-5px";
  30827. header.style.fontWeight = "bold";
  30828. root.appendChild(header);
  30829. };
  30830. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30831. var label = document.createElement("label");
  30832. label.innerHTML = title;
  30833. label.style.color = color;
  30834. root.appendChild(label);
  30835. root.appendChild(document.createElement("br"));
  30836. };
  30837. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30838. if (tag === void 0) { tag = null; }
  30839. var label = document.createElement("label");
  30840. var boundingBoxesCheckbox = document.createElement("input");
  30841. boundingBoxesCheckbox.type = "checkbox";
  30842. boundingBoxesCheckbox.checked = initialState;
  30843. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30844. task(evt.target, tag);
  30845. });
  30846. label.appendChild(boundingBoxesCheckbox);
  30847. var container = document.createElement("span");
  30848. var leftPart = document.createElement("span");
  30849. var rightPart = document.createElement("span");
  30850. rightPart.style.cssFloat = "right";
  30851. leftPart.innerHTML = leftTitle;
  30852. rightPart.innerHTML = rightTitle;
  30853. rightPart.style.fontSize = "12px";
  30854. rightPart.style.maxWidth = "200px";
  30855. container.appendChild(leftPart);
  30856. container.appendChild(rightPart);
  30857. label.appendChild(container);
  30858. root.appendChild(label);
  30859. root.appendChild(document.createElement("br"));
  30860. };
  30861. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30862. if (tag === void 0) { tag = null; }
  30863. var label = document.createElement("label");
  30864. var checkBox = document.createElement("input");
  30865. checkBox.type = "checkbox";
  30866. checkBox.checked = initialState;
  30867. checkBox.addEventListener("change", function (evt) {
  30868. task(evt.target, tag);
  30869. });
  30870. label.appendChild(checkBox);
  30871. label.appendChild(document.createTextNode(title));
  30872. root.appendChild(label);
  30873. root.appendChild(document.createElement("br"));
  30874. };
  30875. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30876. if (tag === void 0) { tag = null; }
  30877. var button = document.createElement("button");
  30878. button.innerHTML = title;
  30879. button.style.height = "24px";
  30880. button.style.color = "#444444";
  30881. button.style.border = "1px solid white";
  30882. button.className = "debugLayerButton";
  30883. button.addEventListener("click", function (evt) {
  30884. task(evt.target, tag);
  30885. });
  30886. root.appendChild(button);
  30887. root.appendChild(document.createElement("br"));
  30888. };
  30889. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30890. if (tag === void 0) { tag = null; }
  30891. var label = document.createElement("label");
  30892. var boundingBoxesRadio = document.createElement("input");
  30893. boundingBoxesRadio.type = "radio";
  30894. boundingBoxesRadio.name = name;
  30895. boundingBoxesRadio.checked = initialState;
  30896. boundingBoxesRadio.addEventListener("change", function (evt) {
  30897. task(evt.target, tag);
  30898. });
  30899. label.appendChild(boundingBoxesRadio);
  30900. label.appendChild(document.createTextNode(title));
  30901. root.appendChild(label);
  30902. root.appendChild(document.createElement("br"));
  30903. };
  30904. DebugLayer.prototype._generateDOMelements = function () {
  30905. var _this = this;
  30906. this._globalDiv.id = "DebugLayer";
  30907. this._globalDiv.style.position = "absolute";
  30908. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30909. this._globalDiv.style.fontSize = "14px";
  30910. this._globalDiv.style.color = "white";
  30911. // Drawing canvas
  30912. this._drawingCanvas = document.createElement("canvas");
  30913. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30914. this._drawingCanvas.style.position = "absolute";
  30915. this._drawingCanvas.style.pointerEvents = "none";
  30916. this._drawingContext = this._drawingCanvas.getContext("2d");
  30917. this._globalDiv.appendChild(this._drawingCanvas);
  30918. if (this._showUI) {
  30919. var background = "rgba(128, 128, 128, 0.4)";
  30920. var border = "rgb(180, 180, 180) solid 1px";
  30921. // Stats
  30922. this._statsDiv = document.createElement("div");
  30923. this._statsDiv.id = "DebugLayerStats";
  30924. this._statsDiv.style.border = border;
  30925. this._statsDiv.style.position = "absolute";
  30926. this._statsDiv.style.background = background;
  30927. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30928. this._generateheader(this._statsDiv, "STATISTICS");
  30929. this._statsSubsetDiv = document.createElement("div");
  30930. this._statsSubsetDiv.style.paddingTop = "5px";
  30931. this._statsSubsetDiv.style.paddingBottom = "5px";
  30932. this._statsSubsetDiv.style.overflowY = "auto";
  30933. this._statsDiv.appendChild(this._statsSubsetDiv);
  30934. // Tree
  30935. this._treeDiv = document.createElement("div");
  30936. this._treeDiv.id = "DebugLayerTree";
  30937. this._treeDiv.style.border = border;
  30938. this._treeDiv.style.position = "absolute";
  30939. this._treeDiv.style.background = background;
  30940. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30941. this._treeDiv.style.display = "none";
  30942. this._generateheader(this._treeDiv, "MESHES TREE");
  30943. this._treeSubsetDiv = document.createElement("div");
  30944. this._treeSubsetDiv.style.paddingTop = "5px";
  30945. this._treeSubsetDiv.style.paddingRight = "5px";
  30946. this._treeSubsetDiv.style.overflowY = "auto";
  30947. this._treeSubsetDiv.style.maxHeight = "300px";
  30948. this._treeDiv.appendChild(this._treeSubsetDiv);
  30949. this._needToRefreshMeshesTree = true;
  30950. // Logs
  30951. this._logDiv = document.createElement("div");
  30952. this._logDiv.style.border = border;
  30953. this._logDiv.id = "DebugLayerLogs";
  30954. this._logDiv.style.position = "absolute";
  30955. this._logDiv.style.background = background;
  30956. this._logDiv.style.padding = "0px 0px 0px 5px";
  30957. this._logDiv.style.display = "none";
  30958. this._generateheader(this._logDiv, "LOGS");
  30959. this._logSubsetDiv = document.createElement("div");
  30960. this._logSubsetDiv.style.height = "127px";
  30961. this._logSubsetDiv.style.paddingTop = "5px";
  30962. this._logSubsetDiv.style.overflowY = "auto";
  30963. this._logSubsetDiv.style.fontSize = "12px";
  30964. this._logSubsetDiv.style.fontFamily = "consolas";
  30965. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30966. this._logDiv.appendChild(this._logSubsetDiv);
  30967. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30968. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30969. };
  30970. // Options
  30971. this._optionsDiv = document.createElement("div");
  30972. this._optionsDiv.id = "DebugLayerOptions";
  30973. this._optionsDiv.style.border = border;
  30974. this._optionsDiv.style.position = "absolute";
  30975. this._optionsDiv.style.background = background;
  30976. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30977. this._optionsDiv.style.overflowY = "auto";
  30978. this._generateheader(this._optionsDiv, "OPTIONS");
  30979. this._optionsSubsetDiv = document.createElement("div");
  30980. this._optionsSubsetDiv.style.paddingTop = "5px";
  30981. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30982. this._optionsSubsetDiv.style.overflowY = "auto";
  30983. this._optionsSubsetDiv.style.maxHeight = "200px";
  30984. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30985. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30986. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30987. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30988. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  30989. _this._displayTree = element.checked;
  30990. _this._needToRefreshMeshesTree = true;
  30991. });
  30992. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30993. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  30994. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  30995. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  30996. _this._labelsEnabled = element.checked;
  30997. if (!_this._labelsEnabled) {
  30998. _this._clearLabels();
  30999. }
  31000. });
  31001. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31002. if (element.checked) {
  31003. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31004. }
  31005. else {
  31006. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31007. }
  31008. });
  31009. ;
  31010. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31011. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31012. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31013. if (element.checked) {
  31014. _this._scene.forceWireframe = false;
  31015. _this._scene.forcePointsCloud = false;
  31016. }
  31017. });
  31018. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31019. if (element.checked) {
  31020. _this._scene.forceWireframe = true;
  31021. _this._scene.forcePointsCloud = false;
  31022. }
  31023. });
  31024. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31025. if (element.checked) {
  31026. _this._scene.forceWireframe = false;
  31027. _this._scene.forcePointsCloud = true;
  31028. }
  31029. });
  31030. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31031. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31032. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31033. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31034. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31035. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31036. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31037. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31038. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31039. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31040. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  31041. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31042. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31043. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31044. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31045. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31046. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31047. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31048. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31049. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31050. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31051. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31052. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31053. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31054. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31055. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31056. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31057. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31058. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31059. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31060. if (element.checked) {
  31061. _this._scene.headphone = true;
  31062. }
  31063. });
  31064. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31065. if (element.checked) {
  31066. _this._scene.headphone = false;
  31067. }
  31068. });
  31069. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31070. _this._scene.audioEnabled = !element.checked;
  31071. });
  31072. }
  31073. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31074. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31075. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31076. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31077. this._globalDiv.appendChild(this._statsDiv);
  31078. this._globalDiv.appendChild(this._logDiv);
  31079. this._globalDiv.appendChild(this._optionsDiv);
  31080. this._globalDiv.appendChild(this._treeDiv);
  31081. }
  31082. };
  31083. DebugLayer.prototype._displayStats = function () {
  31084. var scene = this._scene;
  31085. var engine = scene.getEngine();
  31086. var glInfo = engine.getGlInfo();
  31087. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31088. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31089. + "<b>Count</b><br>"
  31090. + "Total meshes: " + scene.meshes.length + "<br>"
  31091. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31092. + "Total materials: " + scene.materials.length + "<br>"
  31093. + "Total textures: " + scene.textures.length + "<br>"
  31094. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31095. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31096. + "Active bones: " + scene.getActiveBones() + "<br>"
  31097. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31098. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31099. + "<b>Duration</b><br>"
  31100. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31101. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31102. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31103. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31104. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31105. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31106. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31107. + "</div>"
  31108. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31109. + "<b>Extensions</b><br>"
  31110. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31111. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31112. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31113. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31114. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31115. + "<b>Caps.</b><br>"
  31116. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31117. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31118. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31119. + "</div><br>"
  31120. + "<b>Info</b><br>"
  31121. + glInfo.version + "<br>"
  31122. + glInfo.renderer + "<br>";
  31123. if (this.customStatsFunction) {
  31124. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31125. }
  31126. };
  31127. return DebugLayer;
  31128. })();
  31129. BABYLON.DebugLayer = DebugLayer;
  31130. })(BABYLON || (BABYLON = {}));
  31131. var BABYLON;
  31132. (function (BABYLON) {
  31133. var RawTexture = (function (_super) {
  31134. __extends(RawTexture, _super);
  31135. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31136. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31137. if (invertY === void 0) { invertY = false; }
  31138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31139. _super.call(this, null, scene, !generateMipMaps, invertY);
  31140. this.format = format;
  31141. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31142. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31143. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31144. }
  31145. RawTexture.prototype.update = function (data) {
  31146. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31147. };
  31148. // Statics
  31149. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31150. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31151. if (invertY === void 0) { invertY = false; }
  31152. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31153. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31154. };
  31155. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31156. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31157. if (invertY === void 0) { invertY = false; }
  31158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31159. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31160. };
  31161. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31162. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31163. if (invertY === void 0) { invertY = false; }
  31164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31165. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31166. };
  31167. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31168. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31169. if (invertY === void 0) { invertY = false; }
  31170. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31171. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31172. };
  31173. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31174. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31175. if (invertY === void 0) { invertY = false; }
  31176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31177. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31178. };
  31179. return RawTexture;
  31180. })(BABYLON.Texture);
  31181. BABYLON.RawTexture = RawTexture;
  31182. })(BABYLON || (BABYLON = {}));
  31183. var BABYLON;
  31184. (function (BABYLON) {
  31185. var IndexedVector2 = (function (_super) {
  31186. __extends(IndexedVector2, _super);
  31187. function IndexedVector2(original, index) {
  31188. _super.call(this, original.x, original.y);
  31189. this.index = index;
  31190. }
  31191. return IndexedVector2;
  31192. })(BABYLON.Vector2);
  31193. var PolygonPoints = (function () {
  31194. function PolygonPoints() {
  31195. this.elements = new Array();
  31196. }
  31197. PolygonPoints.prototype.add = function (originalPoints) {
  31198. var _this = this;
  31199. var result = new Array();
  31200. originalPoints.forEach(function (point) {
  31201. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31202. var newPoint = new IndexedVector2(point, _this.elements.length);
  31203. result.push(newPoint);
  31204. _this.elements.push(newPoint);
  31205. }
  31206. });
  31207. return result;
  31208. };
  31209. PolygonPoints.prototype.computeBounds = function () {
  31210. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31211. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31212. this.elements.forEach(function (point) {
  31213. // x
  31214. if (point.x < lmin.x) {
  31215. lmin.x = point.x;
  31216. }
  31217. else if (point.x > lmax.x) {
  31218. lmax.x = point.x;
  31219. }
  31220. // y
  31221. if (point.y < lmin.y) {
  31222. lmin.y = point.y;
  31223. }
  31224. else if (point.y > lmax.y) {
  31225. lmax.y = point.y;
  31226. }
  31227. });
  31228. return {
  31229. min: lmin,
  31230. max: lmax,
  31231. width: lmax.x - lmin.x,
  31232. height: lmax.y - lmin.y
  31233. };
  31234. };
  31235. return PolygonPoints;
  31236. })();
  31237. var Polygon = (function () {
  31238. function Polygon() {
  31239. }
  31240. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31241. return [
  31242. new BABYLON.Vector2(xmin, ymin),
  31243. new BABYLON.Vector2(xmax, ymin),
  31244. new BABYLON.Vector2(xmax, ymax),
  31245. new BABYLON.Vector2(xmin, ymax)
  31246. ];
  31247. };
  31248. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31249. if (cx === void 0) { cx = 0; }
  31250. if (cy === void 0) { cy = 0; }
  31251. if (numberOfSides === void 0) { numberOfSides = 32; }
  31252. var result = new Array();
  31253. var angle = 0;
  31254. var increment = (Math.PI * 2) / numberOfSides;
  31255. for (var i = 0; i < numberOfSides; i++) {
  31256. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31257. angle -= increment;
  31258. }
  31259. return result;
  31260. };
  31261. Polygon.Parse = function (input) {
  31262. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31263. var i, result = [];
  31264. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31265. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31266. }
  31267. return result;
  31268. };
  31269. Polygon.StartingAt = function (x, y) {
  31270. return BABYLON.Path2.StartingAt(x, y);
  31271. };
  31272. return Polygon;
  31273. })();
  31274. BABYLON.Polygon = Polygon;
  31275. var PolygonMeshBuilder = (function () {
  31276. function PolygonMeshBuilder(name, contours, scene) {
  31277. this._points = new PolygonPoints();
  31278. this._outlinepoints = new PolygonPoints();
  31279. this._holes = [];
  31280. if (!("poly2tri" in window)) {
  31281. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31282. }
  31283. this._name = name;
  31284. this._scene = scene;
  31285. var points;
  31286. if (contours instanceof BABYLON.Path2) {
  31287. points = contours.getPoints();
  31288. }
  31289. else {
  31290. points = contours;
  31291. }
  31292. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31293. this._outlinepoints.add(points);
  31294. }
  31295. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31296. this._swctx.addHole(this._points.add(hole));
  31297. var holepoints = new PolygonPoints();
  31298. holepoints.add(hole);
  31299. this._holes.push(holepoints);
  31300. return this;
  31301. };
  31302. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31303. var _this = this;
  31304. if (updatable === void 0) { updatable = false; }
  31305. var result = new BABYLON.Mesh(this._name, this._scene);
  31306. var normals = [];
  31307. var positions = [];
  31308. var uvs = [];
  31309. var bounds = this._points.computeBounds();
  31310. this._points.elements.forEach(function (p) {
  31311. normals.push(0, 1.0, 0);
  31312. positions.push(p.x, 0, p.y);
  31313. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31314. });
  31315. var indices = [];
  31316. this._swctx.triangulate();
  31317. this._swctx.getTriangles().forEach(function (triangle) {
  31318. triangle.getPoints().forEach(function (point) {
  31319. indices.push(point.index);
  31320. });
  31321. });
  31322. if (depth > 0) {
  31323. var positionscount = (positions.length / 3); //get the current pointcount
  31324. this._points.elements.forEach(function (p) {
  31325. normals.push(0, -1.0, 0);
  31326. positions.push(p.x, -depth, p.y);
  31327. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31328. });
  31329. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31330. var p2;
  31331. var poscounter = 0;
  31332. this._swctx.getTriangles().forEach(function (triangle) {
  31333. triangle.getPoints().forEach(function (point) {
  31334. switch (poscounter) {
  31335. case 0:
  31336. p1 = point;
  31337. break;
  31338. case 1:
  31339. p2 = point;
  31340. break;
  31341. case 2:
  31342. indices.push(point.index + positionscount);
  31343. indices.push(p2.index + positionscount);
  31344. indices.push(p1.index + positionscount);
  31345. poscounter = -1;
  31346. break;
  31347. }
  31348. poscounter++;
  31349. //indices.push((<IndexedVector2>point).index + positionscount);
  31350. });
  31351. });
  31352. //Add the sides
  31353. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31354. this._holes.forEach(function (hole) {
  31355. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31356. });
  31357. }
  31358. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31359. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31360. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31361. result.setIndices(indices);
  31362. return result;
  31363. };
  31364. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31365. var StartIndex = positions.length / 3;
  31366. var ulength = 0;
  31367. for (var i = 0; i < points.elements.length; i++) {
  31368. var p = points.elements[i];
  31369. var p1;
  31370. if ((i + 1) > points.elements.length - 1) {
  31371. p1 = points.elements[0];
  31372. }
  31373. else {
  31374. p1 = points.elements[i + 1];
  31375. }
  31376. positions.push(p.x, 0, p.y);
  31377. positions.push(p.x, -depth, p.y);
  31378. positions.push(p1.x, 0, p1.y);
  31379. positions.push(p1.x, -depth, p1.y);
  31380. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31381. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31382. var v3 = v2.subtract(v1);
  31383. var v4 = new BABYLON.Vector3(0, 1, 0);
  31384. var vn = BABYLON.Vector3.Cross(v3, v4);
  31385. vn = vn.normalize();
  31386. uvs.push(ulength / bounds.width, 0);
  31387. uvs.push(ulength / bounds.width, 1);
  31388. ulength += v3.length();
  31389. uvs.push((ulength / bounds.width), 0);
  31390. uvs.push((ulength / bounds.width), 1);
  31391. if (!flip) {
  31392. normals.push(-vn.x, -vn.y, -vn.z);
  31393. normals.push(-vn.x, -vn.y, -vn.z);
  31394. normals.push(-vn.x, -vn.y, -vn.z);
  31395. normals.push(-vn.x, -vn.y, -vn.z);
  31396. indices.push(StartIndex);
  31397. indices.push(StartIndex + 1);
  31398. indices.push(StartIndex + 2);
  31399. indices.push(StartIndex + 1);
  31400. indices.push(StartIndex + 3);
  31401. indices.push(StartIndex + 2);
  31402. }
  31403. else {
  31404. normals.push(vn.x, vn.y, vn.z);
  31405. normals.push(vn.x, vn.y, vn.z);
  31406. normals.push(vn.x, vn.y, vn.z);
  31407. normals.push(vn.x, vn.y, vn.z);
  31408. indices.push(StartIndex);
  31409. indices.push(StartIndex + 2);
  31410. indices.push(StartIndex + 1);
  31411. indices.push(StartIndex + 1);
  31412. indices.push(StartIndex + 2);
  31413. indices.push(StartIndex + 3);
  31414. }
  31415. StartIndex += 4;
  31416. }
  31417. ;
  31418. };
  31419. return PolygonMeshBuilder;
  31420. })();
  31421. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31422. })(BABYLON || (BABYLON = {}));
  31423. var BABYLON;
  31424. (function (BABYLON) {
  31425. var SimplificationSettings = (function () {
  31426. function SimplificationSettings(quality, distance, optimizeMesh) {
  31427. this.quality = quality;
  31428. this.distance = distance;
  31429. this.optimizeMesh = optimizeMesh;
  31430. }
  31431. return SimplificationSettings;
  31432. })();
  31433. BABYLON.SimplificationSettings = SimplificationSettings;
  31434. var SimplificationQueue = (function () {
  31435. function SimplificationQueue() {
  31436. this.running = false;
  31437. this._simplificationArray = [];
  31438. }
  31439. SimplificationQueue.prototype.addTask = function (task) {
  31440. this._simplificationArray.push(task);
  31441. };
  31442. SimplificationQueue.prototype.executeNext = function () {
  31443. var task = this._simplificationArray.pop();
  31444. if (task) {
  31445. this.running = true;
  31446. this.runSimplification(task);
  31447. }
  31448. else {
  31449. this.running = false;
  31450. }
  31451. };
  31452. SimplificationQueue.prototype.runSimplification = function (task) {
  31453. var _this = this;
  31454. if (task.parallelProcessing) {
  31455. //parallel simplifier
  31456. task.settings.forEach(function (setting) {
  31457. var simplifier = _this.getSimplifier(task);
  31458. simplifier.simplify(setting, function (newMesh) {
  31459. task.mesh.addLODLevel(setting.distance, newMesh);
  31460. newMesh.isVisible = true;
  31461. //check if it is the last
  31462. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31463. //all done, run the success callback.
  31464. task.successCallback();
  31465. }
  31466. _this.executeNext();
  31467. });
  31468. });
  31469. }
  31470. else {
  31471. //single simplifier.
  31472. var simplifier = this.getSimplifier(task);
  31473. var runDecimation = function (setting, callback) {
  31474. simplifier.simplify(setting, function (newMesh) {
  31475. task.mesh.addLODLevel(setting.distance, newMesh);
  31476. newMesh.isVisible = true;
  31477. //run the next quality level
  31478. callback();
  31479. });
  31480. };
  31481. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31482. runDecimation(task.settings[loop.index], function () {
  31483. loop.executeNext();
  31484. });
  31485. }, function () {
  31486. //execution ended, run the success callback.
  31487. if (task.successCallback) {
  31488. task.successCallback();
  31489. }
  31490. _this.executeNext();
  31491. });
  31492. }
  31493. };
  31494. SimplificationQueue.prototype.getSimplifier = function (task) {
  31495. switch (task.simplificationType) {
  31496. case SimplificationType.QUADRATIC:
  31497. default:
  31498. return new QuadraticErrorSimplification(task.mesh);
  31499. }
  31500. };
  31501. return SimplificationQueue;
  31502. })();
  31503. BABYLON.SimplificationQueue = SimplificationQueue;
  31504. /**
  31505. * The implemented types of simplification.
  31506. * At the moment only Quadratic Error Decimation is implemented.
  31507. */
  31508. (function (SimplificationType) {
  31509. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31510. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31511. var SimplificationType = BABYLON.SimplificationType;
  31512. var DecimationTriangle = (function () {
  31513. function DecimationTriangle(vertices) {
  31514. this.vertices = vertices;
  31515. this.error = new Array(4);
  31516. this.deleted = false;
  31517. this.isDirty = false;
  31518. this.deletePending = false;
  31519. this.borderFactor = 0;
  31520. }
  31521. return DecimationTriangle;
  31522. })();
  31523. BABYLON.DecimationTriangle = DecimationTriangle;
  31524. var DecimationVertex = (function () {
  31525. function DecimationVertex(position, id) {
  31526. this.position = position;
  31527. this.id = id;
  31528. this.isBorder = true;
  31529. this.q = new QuadraticMatrix();
  31530. this.triangleCount = 0;
  31531. this.triangleStart = 0;
  31532. this.originalOffsets = [];
  31533. }
  31534. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31535. this.position.copyFrom(newPosition);
  31536. };
  31537. return DecimationVertex;
  31538. })();
  31539. BABYLON.DecimationVertex = DecimationVertex;
  31540. var QuadraticMatrix = (function () {
  31541. function QuadraticMatrix(data) {
  31542. this.data = new Array(10);
  31543. for (var i = 0; i < 10; ++i) {
  31544. if (data && data[i]) {
  31545. this.data[i] = data[i];
  31546. }
  31547. else {
  31548. this.data[i] = 0;
  31549. }
  31550. }
  31551. }
  31552. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31553. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31554. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31555. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31556. return det;
  31557. };
  31558. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31559. for (var i = 0; i < 10; ++i) {
  31560. this.data[i] += matrix.data[i];
  31561. }
  31562. };
  31563. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31564. for (var i = 0; i < 10; ++i) {
  31565. this.data[i] += data[i];
  31566. }
  31567. };
  31568. QuadraticMatrix.prototype.add = function (matrix) {
  31569. var m = new QuadraticMatrix();
  31570. for (var i = 0; i < 10; ++i) {
  31571. m.data[i] = this.data[i] + matrix.data[i];
  31572. }
  31573. return m;
  31574. };
  31575. QuadraticMatrix.FromData = function (a, b, c, d) {
  31576. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31577. };
  31578. //returning an array to avoid garbage collection
  31579. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31580. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31581. };
  31582. return QuadraticMatrix;
  31583. })();
  31584. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31585. var Reference = (function () {
  31586. function Reference(vertexId, triangleId) {
  31587. this.vertexId = vertexId;
  31588. this.triangleId = triangleId;
  31589. }
  31590. return Reference;
  31591. })();
  31592. BABYLON.Reference = Reference;
  31593. /**
  31594. * An implementation of the Quadratic Error simplification algorithm.
  31595. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31596. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31597. * @author RaananW
  31598. */
  31599. var QuadraticErrorSimplification = (function () {
  31600. function QuadraticErrorSimplification(_mesh) {
  31601. this._mesh = _mesh;
  31602. this.initialized = false;
  31603. this.syncIterations = 5000;
  31604. this.aggressiveness = 7;
  31605. this.decimationIterations = 100;
  31606. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31607. }
  31608. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31609. var _this = this;
  31610. this.initDecimatedMesh();
  31611. //iterating through the submeshes array, one after the other.
  31612. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31613. _this.initWithMesh(loop.index, function () {
  31614. _this.runDecimation(settings, loop.index, function () {
  31615. loop.executeNext();
  31616. });
  31617. }, settings.optimizeMesh);
  31618. }, function () {
  31619. setTimeout(function () {
  31620. successCallback(_this._reconstructedMesh);
  31621. }, 0);
  31622. });
  31623. };
  31624. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31625. var _this = this;
  31626. var gCount = 0;
  31627. triangle.vertices.forEach(function (vertex) {
  31628. var count = 0;
  31629. var vPos = vertex.position;
  31630. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31631. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31632. ++count;
  31633. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31634. ++count;
  31635. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31636. ++count;
  31637. if (count > 1) {
  31638. ++gCount;
  31639. }
  31640. ;
  31641. });
  31642. if (gCount > 1) {
  31643. console.log(triangle, gCount);
  31644. }
  31645. return gCount > 1;
  31646. };
  31647. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31648. var _this = this;
  31649. var targetCount = ~~(this.triangles.length * settings.quality);
  31650. var deletedTriangles = 0;
  31651. var triangleCount = this.triangles.length;
  31652. var iterationFunction = function (iteration, callback) {
  31653. setTimeout(function () {
  31654. if (iteration % 5 === 0) {
  31655. _this.updateMesh(iteration === 0);
  31656. }
  31657. for (var i = 0; i < _this.triangles.length; ++i) {
  31658. _this.triangles[i].isDirty = false;
  31659. }
  31660. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31661. var trianglesIterator = function (i) {
  31662. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31663. var t = _this.triangles[tIdx];
  31664. if (!t)
  31665. return;
  31666. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31667. return;
  31668. }
  31669. for (var j = 0; j < 3; ++j) {
  31670. if (t.error[j] < threshold) {
  31671. var deleted0 = [];
  31672. var deleted1 = [];
  31673. var v0 = t.vertices[j];
  31674. var v1 = t.vertices[(j + 1) % 3];
  31675. if (v0.isBorder !== v1.isBorder)
  31676. continue;
  31677. var p = BABYLON.Vector3.Zero();
  31678. var n = BABYLON.Vector3.Zero();
  31679. var uv = BABYLON.Vector2.Zero();
  31680. var color = new BABYLON.Color4(0, 0, 0, 1);
  31681. _this.calculateError(v0, v1, p, n, uv, color);
  31682. var delTr = [];
  31683. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31684. continue;
  31685. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31686. continue;
  31687. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31688. continue;
  31689. var uniqueArray = [];
  31690. delTr.forEach(function (deletedT) {
  31691. if (uniqueArray.indexOf(deletedT) === -1) {
  31692. deletedT.deletePending = true;
  31693. uniqueArray.push(deletedT);
  31694. }
  31695. });
  31696. if (uniqueArray.length % 2 != 0) {
  31697. continue;
  31698. }
  31699. v0.q = v1.q.add(v0.q);
  31700. v0.updatePosition(p);
  31701. var tStart = _this.references.length;
  31702. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31703. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31704. var tCount = _this.references.length - tStart;
  31705. if (tCount <= v0.triangleCount) {
  31706. if (tCount) {
  31707. for (var c = 0; c < tCount; c++) {
  31708. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31709. }
  31710. }
  31711. }
  31712. else {
  31713. v0.triangleStart = tStart;
  31714. }
  31715. v0.triangleCount = tCount;
  31716. break;
  31717. }
  31718. }
  31719. };
  31720. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31721. }, 0);
  31722. };
  31723. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31724. if (triangleCount - deletedTriangles <= targetCount)
  31725. loop.breakLoop();
  31726. else {
  31727. iterationFunction(loop.index, function () {
  31728. loop.executeNext();
  31729. });
  31730. }
  31731. }, function () {
  31732. setTimeout(function () {
  31733. //reconstruct this part of the mesh
  31734. _this.reconstructMesh(submeshIndex);
  31735. successCallback();
  31736. }, 0);
  31737. });
  31738. };
  31739. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31740. var _this = this;
  31741. this.vertices = [];
  31742. this.triangles = [];
  31743. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31744. var indices = this._mesh.getIndices();
  31745. var submesh = this._mesh.subMeshes[submeshIndex];
  31746. var findInVertices = function (positionToSearch) {
  31747. if (optimizeMesh) {
  31748. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31749. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31750. return _this.vertices[ii];
  31751. }
  31752. }
  31753. }
  31754. return null;
  31755. };
  31756. var vertexReferences = [];
  31757. var vertexInit = function (i) {
  31758. var offset = i + submesh.verticesStart;
  31759. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31760. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31761. vertex.originalOffsets.push(offset);
  31762. if (vertex.id == _this.vertices.length) {
  31763. _this.vertices.push(vertex);
  31764. }
  31765. vertexReferences.push(vertex.id);
  31766. };
  31767. //var totalVertices = mesh.getTotalVertices();
  31768. var totalVertices = submesh.verticesCount;
  31769. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31770. var indicesInit = function (i) {
  31771. var offset = (submesh.indexStart / 3) + i;
  31772. var pos = (offset * 3);
  31773. var i0 = indices[pos + 0];
  31774. var i1 = indices[pos + 1];
  31775. var i2 = indices[pos + 2];
  31776. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31777. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31778. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31779. var triangle = new DecimationTriangle([v0, v1, v2]);
  31780. triangle.originalOffset = pos;
  31781. _this.triangles.push(triangle);
  31782. };
  31783. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31784. _this.init(callback);
  31785. });
  31786. });
  31787. };
  31788. QuadraticErrorSimplification.prototype.init = function (callback) {
  31789. var _this = this;
  31790. var triangleInit1 = function (i) {
  31791. var t = _this.triangles[i];
  31792. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31793. for (var j = 0; j < 3; j++) {
  31794. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  31795. }
  31796. };
  31797. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31798. var triangleInit2 = function (i) {
  31799. var t = _this.triangles[i];
  31800. for (var j = 0; j < 3; ++j) {
  31801. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31802. }
  31803. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31804. };
  31805. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31806. _this.initialized = true;
  31807. callback();
  31808. });
  31809. });
  31810. };
  31811. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31812. var newTriangles = [];
  31813. var i;
  31814. for (i = 0; i < this.vertices.length; ++i) {
  31815. this.vertices[i].triangleCount = 0;
  31816. }
  31817. var t;
  31818. var j;
  31819. for (i = 0; i < this.triangles.length; ++i) {
  31820. if (!this.triangles[i].deleted) {
  31821. t = this.triangles[i];
  31822. for (j = 0; j < 3; ++j) {
  31823. t.vertices[j].triangleCount = 1;
  31824. }
  31825. newTriangles.push(t);
  31826. }
  31827. }
  31828. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31829. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31830. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31831. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31832. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31833. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31834. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31835. var vertexCount = 0;
  31836. for (i = 0; i < this.vertices.length; ++i) {
  31837. var vertex = this.vertices[i];
  31838. vertex.id = vertexCount;
  31839. if (vertex.triangleCount) {
  31840. vertex.originalOffsets.forEach(function (originalOffset) {
  31841. newPositionData.push(vertex.position.x);
  31842. newPositionData.push(vertex.position.y);
  31843. newPositionData.push(vertex.position.z);
  31844. newNormalData.push(normalData[originalOffset * 3]);
  31845. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31846. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31847. if (uvs && uvs.length) {
  31848. newUVsData.push(uvs[(originalOffset * 2)]);
  31849. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31850. }
  31851. else if (colorsData && colorsData.length) {
  31852. newColorsData.push(colorsData[(originalOffset * 4)]);
  31853. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31854. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31855. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31856. }
  31857. ++vertexCount;
  31858. });
  31859. }
  31860. }
  31861. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31862. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31863. var submeshesArray = this._reconstructedMesh.subMeshes;
  31864. this._reconstructedMesh.subMeshes = [];
  31865. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31866. var originalIndices = this._mesh.getIndices();
  31867. for (i = 0; i < newTriangles.length; ++i) {
  31868. var t = newTriangles[i];
  31869. //now get the new referencing point for each vertex
  31870. [0, 1, 2].forEach(function (idx) {
  31871. var id = originalIndices[t.originalOffset + idx];
  31872. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31873. if (offset < 0)
  31874. offset = 0;
  31875. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31876. });
  31877. }
  31878. //overwriting the old vertex buffers and indices.
  31879. this._reconstructedMesh.setIndices(newIndicesArray);
  31880. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31881. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31882. if (newUVsData.length > 0)
  31883. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31884. if (newColorsData.length > 0)
  31885. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31886. //create submesh
  31887. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31888. if (submeshIndex > 0) {
  31889. this._reconstructedMesh.subMeshes = [];
  31890. submeshesArray.forEach(function (submesh) {
  31891. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31892. });
  31893. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31894. }
  31895. };
  31896. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31897. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31898. this._reconstructedMesh.material = this._mesh.material;
  31899. this._reconstructedMesh.parent = this._mesh.parent;
  31900. this._reconstructedMesh.isVisible = false;
  31901. };
  31902. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31903. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31904. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31905. if (t.deleted)
  31906. continue;
  31907. var s = this.references[vertex1.triangleStart + i].vertexId;
  31908. var v1 = t.vertices[(s + 1) % 3];
  31909. var v2 = t.vertices[(s + 2) % 3];
  31910. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31911. deletedArray[i] = true;
  31912. delTr.push(t);
  31913. continue;
  31914. }
  31915. var d1 = v1.position.subtract(point);
  31916. d1 = d1.normalize();
  31917. var d2 = v2.position.subtract(point);
  31918. d2 = d2.normalize();
  31919. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31920. return true;
  31921. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31922. deletedArray[i] = false;
  31923. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31924. return true;
  31925. }
  31926. return false;
  31927. };
  31928. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31929. var newDeleted = deletedTriangles;
  31930. for (var i = 0; i < vertex.triangleCount; ++i) {
  31931. var ref = this.references[vertex.triangleStart + i];
  31932. var t = this.triangles[ref.triangleId];
  31933. if (t.deleted)
  31934. continue;
  31935. if (deletedArray[i] && t.deletePending) {
  31936. t.deleted = true;
  31937. newDeleted++;
  31938. continue;
  31939. }
  31940. t.vertices[ref.vertexId] = origVertex;
  31941. t.isDirty = true;
  31942. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31943. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31944. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31945. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31946. this.references.push(ref);
  31947. }
  31948. return newDeleted;
  31949. };
  31950. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31951. for (var i = 0; i < this.vertices.length; ++i) {
  31952. var vCount = [];
  31953. var vId = [];
  31954. var v = this.vertices[i];
  31955. var j;
  31956. for (j = 0; j < v.triangleCount; ++j) {
  31957. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31958. for (var ii = 0; ii < 3; ii++) {
  31959. var ofs = 0;
  31960. var vv = triangle.vertices[ii];
  31961. while (ofs < vCount.length) {
  31962. if (vId[ofs] === vv.id)
  31963. break;
  31964. ++ofs;
  31965. }
  31966. if (ofs === vCount.length) {
  31967. vCount.push(1);
  31968. vId.push(vv.id);
  31969. }
  31970. else {
  31971. vCount[ofs]++;
  31972. }
  31973. }
  31974. }
  31975. for (j = 0; j < vCount.length; ++j) {
  31976. if (vCount[j] === 1) {
  31977. this.vertices[vId[j]].isBorder = true;
  31978. }
  31979. else {
  31980. this.vertices[vId[j]].isBorder = false;
  31981. }
  31982. }
  31983. }
  31984. };
  31985. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31986. if (identifyBorders === void 0) { identifyBorders = false; }
  31987. var i;
  31988. if (!identifyBorders) {
  31989. var newTrianglesVector = [];
  31990. for (i = 0; i < this.triangles.length; ++i) {
  31991. if (!this.triangles[i].deleted) {
  31992. newTrianglesVector.push(this.triangles[i]);
  31993. }
  31994. }
  31995. this.triangles = newTrianglesVector;
  31996. }
  31997. for (i = 0; i < this.vertices.length; ++i) {
  31998. this.vertices[i].triangleCount = 0;
  31999. this.vertices[i].triangleStart = 0;
  32000. }
  32001. var t;
  32002. var j;
  32003. var v;
  32004. for (i = 0; i < this.triangles.length; ++i) {
  32005. t = this.triangles[i];
  32006. for (j = 0; j < 3; ++j) {
  32007. v = t.vertices[j];
  32008. v.triangleCount++;
  32009. }
  32010. }
  32011. var tStart = 0;
  32012. for (i = 0; i < this.vertices.length; ++i) {
  32013. this.vertices[i].triangleStart = tStart;
  32014. tStart += this.vertices[i].triangleCount;
  32015. this.vertices[i].triangleCount = 0;
  32016. }
  32017. var newReferences = new Array(this.triangles.length * 3);
  32018. for (i = 0; i < this.triangles.length; ++i) {
  32019. t = this.triangles[i];
  32020. for (j = 0; j < 3; ++j) {
  32021. v = t.vertices[j];
  32022. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32023. v.triangleCount++;
  32024. }
  32025. }
  32026. this.references = newReferences;
  32027. if (identifyBorders) {
  32028. this.identifyBorder();
  32029. }
  32030. };
  32031. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32032. var x = point.x;
  32033. var y = point.y;
  32034. var z = point.z;
  32035. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  32036. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32037. };
  32038. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32039. var q = vertex1.q.add(vertex2.q);
  32040. var border = vertex1.isBorder && vertex2.isBorder;
  32041. var error = 0;
  32042. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32043. if (qDet !== 0 && !border) {
  32044. if (!pointResult) {
  32045. pointResult = BABYLON.Vector3.Zero();
  32046. }
  32047. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32048. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32049. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32050. error = this.vertexError(q, pointResult);
  32051. }
  32052. else {
  32053. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32054. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32055. var error1 = this.vertexError(q, vertex1.position);
  32056. var error2 = this.vertexError(q, vertex2.position);
  32057. var error3 = this.vertexError(q, p3);
  32058. error = Math.min(error1, error2, error3);
  32059. if (error === error1) {
  32060. if (pointResult) {
  32061. pointResult.copyFrom(vertex1.position);
  32062. }
  32063. }
  32064. else if (error === error2) {
  32065. if (pointResult) {
  32066. pointResult.copyFrom(vertex2.position);
  32067. }
  32068. }
  32069. else {
  32070. if (pointResult) {
  32071. pointResult.copyFrom(p3);
  32072. }
  32073. }
  32074. }
  32075. return error;
  32076. };
  32077. return QuadraticErrorSimplification;
  32078. })();
  32079. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32080. })(BABYLON || (BABYLON = {}));
  32081. var BABYLON;
  32082. (function (BABYLON) {
  32083. var Analyser = (function () {
  32084. function Analyser(scene) {
  32085. this.SMOOTHING = 0.75;
  32086. this.FFT_SIZE = 512;
  32087. this.BARGRAPHAMPLITUDE = 256;
  32088. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32089. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32090. this._scene = scene;
  32091. this._audioEngine = BABYLON.Engine.audioEngine;
  32092. if (this._audioEngine.canUseWebAudio) {
  32093. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32094. this._webAudioAnalyser.minDecibels = -140;
  32095. this._webAudioAnalyser.maxDecibels = 0;
  32096. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32097. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32098. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32099. }
  32100. }
  32101. Analyser.prototype.getFrequencyBinCount = function () {
  32102. if (this._audioEngine.canUseWebAudio) {
  32103. return this._webAudioAnalyser.frequencyBinCount;
  32104. }
  32105. else {
  32106. return 0;
  32107. }
  32108. };
  32109. Analyser.prototype.getByteFrequencyData = function () {
  32110. if (this._audioEngine.canUseWebAudio) {
  32111. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32112. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32113. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32114. }
  32115. return this._byteFreqs;
  32116. };
  32117. Analyser.prototype.getByteTimeDomainData = function () {
  32118. if (this._audioEngine.canUseWebAudio) {
  32119. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32120. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32121. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32122. }
  32123. return this._byteTime;
  32124. };
  32125. Analyser.prototype.getFloatFrequencyData = function () {
  32126. if (this._audioEngine.canUseWebAudio) {
  32127. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32128. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32129. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32130. }
  32131. return this._floatFreqs;
  32132. };
  32133. Analyser.prototype.drawDebugCanvas = function () {
  32134. var _this = this;
  32135. if (this._audioEngine.canUseWebAudio) {
  32136. if (!this._debugCanvas) {
  32137. this._debugCanvas = document.createElement("canvas");
  32138. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32139. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32140. this._debugCanvas.style.position = "absolute";
  32141. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32142. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32143. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32144. document.body.appendChild(this._debugCanvas);
  32145. this._registerFunc = function () {
  32146. _this.drawDebugCanvas();
  32147. };
  32148. this._scene.registerBeforeRender(this._registerFunc);
  32149. }
  32150. if (this._registerFunc) {
  32151. var workingArray = this.getByteFrequencyData();
  32152. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32153. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32154. // Draw the frequency domain chart.
  32155. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32156. var value = workingArray[i];
  32157. var percent = value / this.BARGRAPHAMPLITUDE;
  32158. var height = this.DEBUGCANVASSIZE.height * percent;
  32159. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32160. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32161. var hue = i / this.getFrequencyBinCount() * 360;
  32162. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32163. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32164. }
  32165. }
  32166. }
  32167. };
  32168. Analyser.prototype.stopDebugCanvas = function () {
  32169. if (this._debugCanvas) {
  32170. this._scene.unregisterBeforeRender(this._registerFunc);
  32171. this._registerFunc = null;
  32172. document.body.removeChild(this._debugCanvas);
  32173. this._debugCanvas = null;
  32174. this._debugCanvasContext = null;
  32175. }
  32176. };
  32177. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32178. if (this._audioEngine.canUseWebAudio) {
  32179. inputAudioNode.connect(this._webAudioAnalyser);
  32180. this._webAudioAnalyser.connect(outputAudioNode);
  32181. }
  32182. };
  32183. Analyser.prototype.dispose = function () {
  32184. if (this._audioEngine.canUseWebAudio) {
  32185. this._webAudioAnalyser.disconnect();
  32186. }
  32187. };
  32188. return Analyser;
  32189. })();
  32190. BABYLON.Analyser = Analyser;
  32191. })(BABYLON || (BABYLON = {}));
  32192. var BABYLON;
  32193. (function (BABYLON) {
  32194. var DepthRenderer = (function () {
  32195. function DepthRenderer(scene, type) {
  32196. var _this = this;
  32197. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32198. this._viewMatrix = BABYLON.Matrix.Zero();
  32199. this._projectionMatrix = BABYLON.Matrix.Zero();
  32200. this._transformMatrix = BABYLON.Matrix.Zero();
  32201. this._worldViewProjection = BABYLON.Matrix.Zero();
  32202. this._scene = scene;
  32203. var engine = scene.getEngine();
  32204. // Render target
  32205. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32206. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32207. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32208. this._depthMap.refreshRate = 1;
  32209. this._depthMap.renderParticles = false;
  32210. this._depthMap.renderList = null;
  32211. // set default depth value to 1.0 (far away)
  32212. this._depthMap.onClear = function (engine) {
  32213. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32214. };
  32215. // Custom render function
  32216. var renderSubMesh = function (subMesh) {
  32217. var mesh = subMesh.getRenderingMesh();
  32218. var scene = _this._scene;
  32219. var engine = scene.getEngine();
  32220. // Culling
  32221. engine.setState(subMesh.getMaterial().backFaceCulling);
  32222. // Managing instances
  32223. var batch = mesh._getInstancesRenderList(subMesh._id);
  32224. if (batch.mustReturn) {
  32225. return;
  32226. }
  32227. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32228. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32229. engine.enableEffect(_this._effect);
  32230. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32231. var material = subMesh.getMaterial();
  32232. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32233. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32234. // Alpha test
  32235. if (material && material.needAlphaTesting()) {
  32236. var alphaTexture = material.getAlphaTestTexture();
  32237. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32238. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32239. }
  32240. // Bones
  32241. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32242. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32243. }
  32244. // Draw
  32245. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32246. }
  32247. };
  32248. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32249. var index;
  32250. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32251. renderSubMesh(opaqueSubMeshes.data[index]);
  32252. }
  32253. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32254. renderSubMesh(alphaTestSubMeshes.data[index]);
  32255. }
  32256. };
  32257. }
  32258. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32259. var defines = [];
  32260. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32261. var mesh = subMesh.getMesh();
  32262. var scene = mesh.getScene();
  32263. var material = subMesh.getMaterial();
  32264. // Alpha test
  32265. if (material && material.needAlphaTesting()) {
  32266. defines.push("#define ALPHATEST");
  32267. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32268. attribs.push(BABYLON.VertexBuffer.UVKind);
  32269. defines.push("#define UV1");
  32270. }
  32271. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32272. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32273. defines.push("#define UV2");
  32274. }
  32275. }
  32276. // Bones
  32277. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32278. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32279. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32280. defines.push("#define BONES");
  32281. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32282. }
  32283. // Instances
  32284. if (useInstances) {
  32285. defines.push("#define INSTANCES");
  32286. attribs.push("world0");
  32287. attribs.push("world1");
  32288. attribs.push("world2");
  32289. attribs.push("world3");
  32290. }
  32291. // Get correct effect
  32292. var join = defines.join("\n");
  32293. if (this._cachedDefines !== join) {
  32294. this._cachedDefines = join;
  32295. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32296. }
  32297. return this._effect.isReady();
  32298. };
  32299. DepthRenderer.prototype.getDepthMap = function () {
  32300. return this._depthMap;
  32301. };
  32302. // Methods
  32303. DepthRenderer.prototype.dispose = function () {
  32304. this._depthMap.dispose();
  32305. };
  32306. return DepthRenderer;
  32307. })();
  32308. BABYLON.DepthRenderer = DepthRenderer;
  32309. })(BABYLON || (BABYLON = {}));
  32310. var BABYLON;
  32311. (function (BABYLON) {
  32312. var SSAORenderingPipeline = (function (_super) {
  32313. __extends(SSAORenderingPipeline, _super);
  32314. /**
  32315. * @constructor
  32316. * @param {string} name - The rendering pipeline name
  32317. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32318. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  32319. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32320. */
  32321. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32322. var _this = this;
  32323. _super.call(this, scene.getEngine(), name);
  32324. // Members
  32325. /**
  32326. * The PassPostProcess id in the pipeline that contains the original scene color
  32327. * @type {string}
  32328. */
  32329. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32330. /**
  32331. * The SSAO PostProcess id in the pipeline
  32332. * @type {string}
  32333. */
  32334. this.SSAORenderEffect = "SSAORenderEffect";
  32335. /**
  32336. * The horizontal blur PostProcess id in the pipeline
  32337. * @type {string}
  32338. */
  32339. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32340. /**
  32341. * The vertical blur PostProcess id in the pipeline
  32342. * @type {string}
  32343. */
  32344. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32345. /**
  32346. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32347. * @type {string}
  32348. */
  32349. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32350. /**
  32351. * The output strength of the SSAO post-process. Default value is 1.0.
  32352. * @type {number}
  32353. */
  32354. this.totalStrength = 1.0;
  32355. /**
  32356. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32357. * @type {number}
  32358. */
  32359. this.radius = 0.0002;
  32360. /**
  32361. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32362. * Must not be equal to fallOff and superior to fallOff.
  32363. * Default value is 0.0075
  32364. * @type {number}
  32365. */
  32366. this.area = 0.0075;
  32367. /**
  32368. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32369. * Must not be equal to area and inferior to area.
  32370. * Default value is 0.0002
  32371. * @type {number}
  32372. */
  32373. this.fallOff = 0.0002;
  32374. this._firstUpdate = true;
  32375. this._scene = scene;
  32376. // Set up assets
  32377. this._createRandomTexture();
  32378. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32379. var ssaoRatio = ratio.ssaoRatio || ratio;
  32380. var combineRatio = ratio.combineRatio || ratio;
  32381. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32382. this._createSSAOPostProcess(ssaoRatio);
  32383. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32384. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32385. this._createSSAOCombinePostProcess(combineRatio);
  32386. // Set up pipeline
  32387. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32388. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32389. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32390. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32392. // Finish
  32393. scene.postProcessRenderPipelineManager.addPipeline(this);
  32394. if (cameras)
  32395. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32396. }
  32397. // Public Methods
  32398. /**
  32399. * Returns the horizontal blur PostProcess
  32400. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32401. */
  32402. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32403. return this._blurHPostProcess;
  32404. };
  32405. /**
  32406. * Returns the vertical blur PostProcess
  32407. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32408. */
  32409. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32410. return this._blurVPostProcess;
  32411. };
  32412. /**
  32413. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32414. */
  32415. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32416. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32417. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32418. this._originalColorPostProcess = undefined;
  32419. this._ssaoPostProcess = undefined;
  32420. this._blurHPostProcess = undefined;
  32421. this._blurVPostProcess = undefined;
  32422. this._ssaoCombinePostProcess = undefined;
  32423. this._randomTexture.dispose();
  32424. if (disableDepthRender)
  32425. this._scene.disableDepthRenderer();
  32426. };
  32427. // Private Methods
  32428. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32429. var _this = this;
  32430. var sampleSphere = [
  32431. 0.5381, 0.1856, -0.4319,
  32432. 0.1379, 0.2486, 0.4430,
  32433. 0.3371, 0.5679, -0.0057,
  32434. -0.6999, -0.0451, -0.0019,
  32435. 0.0689, -0.1598, -0.8547,
  32436. 0.0560, 0.0069, -0.1843,
  32437. -0.0146, 0.1402, 0.0762,
  32438. 0.0100, -0.1924, -0.0344,
  32439. -0.3577, -0.5301, -0.4358,
  32440. -0.3169, 0.1063, 0.0158,
  32441. 0.0103, -0.5869, 0.0046,
  32442. -0.0897, -0.4940, 0.3287,
  32443. 0.7119, -0.0154, -0.0918,
  32444. -0.0533, 0.0596, -0.5411,
  32445. 0.0352, -0.0631, 0.5460,
  32446. -0.4776, 0.2847, -0.0271
  32447. ];
  32448. var samplesFactor = 1.0 / 16.0;
  32449. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32450. this._ssaoPostProcess.onApply = function (effect) {
  32451. if (_this._firstUpdate) {
  32452. effect.setArray3("sampleSphere", sampleSphere);
  32453. effect.setFloat("samplesFactor", samplesFactor);
  32454. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32455. _this._firstUpdate = false;
  32456. }
  32457. effect.setFloat("totalStrength", _this.totalStrength);
  32458. effect.setFloat("radius", _this.radius);
  32459. effect.setFloat("area", _this.area);
  32460. effect.setFloat("fallOff", _this.fallOff);
  32461. effect.setTexture("textureSampler", _this._depthTexture);
  32462. effect.setTexture("randomSampler", _this._randomTexture);
  32463. };
  32464. };
  32465. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32466. var _this = this;
  32467. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32468. this._ssaoCombinePostProcess.onApply = function (effect) {
  32469. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32470. };
  32471. };
  32472. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32473. var size = 512;
  32474. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32475. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32476. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32477. var context = this._randomTexture.getContext();
  32478. var rand = function (min, max) {
  32479. return Math.random() * (max - min) + min;
  32480. };
  32481. for (var x = 0; x < size; x++) {
  32482. for (var y = 0; y < size; y++) {
  32483. var randVector = BABYLON.Vector3.Zero();
  32484. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32485. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32486. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32487. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32488. context.fillRect(x, y, 1, 1);
  32489. }
  32490. }
  32491. this._randomTexture.update(false);
  32492. };
  32493. return SSAORenderingPipeline;
  32494. })(BABYLON.PostProcessRenderPipeline);
  32495. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32496. })(BABYLON || (BABYLON = {}));
  32497. var BABYLON;
  32498. (function (BABYLON) {
  32499. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32500. var VolumetricLightScatteringPostProcess = (function (_super) {
  32501. __extends(VolumetricLightScatteringPostProcess, _super);
  32502. /**
  32503. * @constructor
  32504. * @param {string} name - The post-process name
  32505. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  32506. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32507. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32508. * @param {number} samples - The post-process quality, default 100
  32509. * @param {number} samplingMode - The post-process filtering mode
  32510. * @param {BABYLON.Engine} engine - The babylon engine
  32511. * @param {boolean} reusable - If the post-process is reusable
  32512. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32513. */
  32514. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32515. var _this = this;
  32516. if (samples === void 0) { samples = 100; }
  32517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32518. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32519. this._screenCoordinates = BABYLON.Vector2.Zero();
  32520. /**
  32521. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32522. * @type {boolean}
  32523. */
  32524. this.useCustomMeshPosition = false;
  32525. /**
  32526. * If the post-process should inverse the light scattering direction
  32527. * @type {boolean}
  32528. */
  32529. this.invert = true;
  32530. /**
  32531. * Set to true to use the diffuseColor instead of the diffuseTexture
  32532. * @type {boolean}
  32533. */
  32534. this.useDiffuseColor = false;
  32535. /**
  32536. * Array containing the excluded meshes not rendered in the internal pass
  32537. */
  32538. this.excludedMeshes = new Array();
  32539. /**
  32540. * Controls the overall intensity of the post-process
  32541. * @type {number}
  32542. */
  32543. this.exposure = 0.3;
  32544. /**
  32545. * Dissipates each sample's contribution in range [0, 1]
  32546. * @type {number}
  32547. */
  32548. this.decay = 0.96815;
  32549. /**
  32550. * Controls the overall intensity of each sample
  32551. * @type {number}
  32552. */
  32553. this.weight = 0.58767;
  32554. /**
  32555. * Controls the density of each sample
  32556. * @type {number}
  32557. */
  32558. this.density = 0.926;
  32559. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32560. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32561. // Configure mesh
  32562. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32563. // Configure
  32564. this._createPass(scene, ratio.passRatio || ratio);
  32565. this.onApply = function (effect) {
  32566. _this._updateMeshScreenCoordinates(scene);
  32567. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32568. effect.setFloat("exposure", _this.exposure);
  32569. effect.setFloat("decay", _this.decay);
  32570. effect.setFloat("weight", _this.weight);
  32571. effect.setFloat("density", _this.density);
  32572. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32573. };
  32574. }
  32575. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32576. var mesh = subMesh.getMesh();
  32577. var defines = [];
  32578. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32579. var material = subMesh.getMaterial();
  32580. var needUV = false;
  32581. // Render this.mesh as default
  32582. if (mesh === this.mesh) {
  32583. if (this.useDiffuseColor) {
  32584. defines.push("#define DIFFUSE_COLOR_RENDER");
  32585. }
  32586. else if (material) {
  32587. if (material.diffuseTexture !== undefined) {
  32588. defines.push("#define BASIC_RENDER");
  32589. }
  32590. else {
  32591. defines.push("#define DIFFUSE_COLOR_RENDER");
  32592. }
  32593. }
  32594. defines.push("#define NEED_UV");
  32595. needUV = true;
  32596. }
  32597. // Alpha test
  32598. if (material) {
  32599. if (material.needAlphaTesting()) {
  32600. defines.push("#define ALPHATEST");
  32601. }
  32602. if (material.opacityTexture !== undefined) {
  32603. defines.push("#define OPACITY");
  32604. if (material.opacityTexture.getAlphaFromRGB) {
  32605. defines.push("#define OPACITYRGB");
  32606. }
  32607. if (!needUV) {
  32608. defines.push("#define NEED_UV");
  32609. }
  32610. }
  32611. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32612. attribs.push(BABYLON.VertexBuffer.UVKind);
  32613. defines.push("#define UV1");
  32614. }
  32615. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32616. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32617. defines.push("#define UV2");
  32618. }
  32619. }
  32620. // Bones
  32621. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32622. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32623. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32624. defines.push("#define BONES");
  32625. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32626. }
  32627. // Instances
  32628. if (useInstances) {
  32629. defines.push("#define INSTANCES");
  32630. attribs.push("world0");
  32631. attribs.push("world1");
  32632. attribs.push("world2");
  32633. attribs.push("world3");
  32634. }
  32635. // Get correct effect
  32636. var join = defines.join("\n");
  32637. if (this._cachedDefines !== join) {
  32638. this._cachedDefines = join;
  32639. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32640. }
  32641. return this._volumetricLightScatteringPass.isReady();
  32642. };
  32643. /**
  32644. * Sets the new light position for light scattering effect
  32645. * @param {BABYLON.Vector3} The new custom light position
  32646. */
  32647. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32648. this._customMeshPosition = position;
  32649. };
  32650. /**
  32651. * Returns the light position for light scattering effect
  32652. * @return {BABYLON.Vector3} The custom light position
  32653. */
  32654. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32655. return this._customMeshPosition;
  32656. };
  32657. /**
  32658. * Disposes the internal assets and detaches the post-process from the camera
  32659. */
  32660. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32661. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32662. if (rttIndex !== -1) {
  32663. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32664. }
  32665. this._volumetricLightScatteringRTT.dispose();
  32666. _super.prototype.dispose.call(this, camera);
  32667. };
  32668. /**
  32669. * Returns the render target texture used by the post-process
  32670. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32671. */
  32672. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32673. return this._volumetricLightScatteringRTT;
  32674. };
  32675. // Private methods
  32676. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32677. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32678. return true;
  32679. }
  32680. return false;
  32681. };
  32682. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32683. var _this = this;
  32684. var engine = scene.getEngine();
  32685. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32686. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32687. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32688. this._volumetricLightScatteringRTT.renderList = null;
  32689. this._volumetricLightScatteringRTT.renderParticles = false;
  32690. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32691. // Custom render function for submeshes
  32692. var renderSubMesh = function (subMesh) {
  32693. var mesh = subMesh.getRenderingMesh();
  32694. if (_this._meshExcluded(mesh)) {
  32695. return;
  32696. }
  32697. var scene = mesh.getScene();
  32698. var engine = scene.getEngine();
  32699. // Culling
  32700. engine.setState(subMesh.getMaterial().backFaceCulling);
  32701. // Managing instances
  32702. var batch = mesh._getInstancesRenderList(subMesh._id);
  32703. if (batch.mustReturn) {
  32704. return;
  32705. }
  32706. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32707. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32708. engine.enableEffect(_this._volumetricLightScatteringPass);
  32709. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32710. var material = subMesh.getMaterial();
  32711. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32712. // Alpha test
  32713. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32714. var alphaTexture = material.getAlphaTestTexture();
  32715. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32716. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32717. }
  32718. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32719. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32720. if (alphaTexture) {
  32721. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32722. }
  32723. }
  32724. if (material.opacityTexture !== undefined) {
  32725. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32726. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32727. }
  32728. }
  32729. // Bones
  32730. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32731. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32732. }
  32733. // Draw
  32734. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32735. }
  32736. };
  32737. // Render target texture callbacks
  32738. var savedSceneClearColor;
  32739. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32740. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32741. savedSceneClearColor = scene.clearColor;
  32742. scene.clearColor = sceneClearColor;
  32743. };
  32744. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32745. scene.clearColor = savedSceneClearColor;
  32746. };
  32747. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32748. var engine = scene.getEngine();
  32749. var index;
  32750. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32751. renderSubMesh(opaqueSubMeshes.data[index]);
  32752. }
  32753. engine.setAlphaTesting(true);
  32754. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32755. renderSubMesh(alphaTestSubMeshes.data[index]);
  32756. }
  32757. engine.setAlphaTesting(false);
  32758. if (transparentSubMeshes.length) {
  32759. // Sort sub meshes
  32760. for (index = 0; index < transparentSubMeshes.length; index++) {
  32761. var submesh = transparentSubMeshes.data[index];
  32762. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32763. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32764. }
  32765. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32766. sortedArray.sort(function (a, b) {
  32767. // Alpha index first
  32768. if (a._alphaIndex > b._alphaIndex) {
  32769. return 1;
  32770. }
  32771. if (a._alphaIndex < b._alphaIndex) {
  32772. return -1;
  32773. }
  32774. // Then distance to camera
  32775. if (a._distanceToCamera < b._distanceToCamera) {
  32776. return 1;
  32777. }
  32778. if (a._distanceToCamera > b._distanceToCamera) {
  32779. return -1;
  32780. }
  32781. return 0;
  32782. });
  32783. // Render sub meshes
  32784. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32785. for (index = 0; index < sortedArray.length; index++) {
  32786. renderSubMesh(sortedArray[index]);
  32787. }
  32788. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32789. }
  32790. };
  32791. };
  32792. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32793. var transform = scene.getTransformMatrix();
  32794. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32795. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32796. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32797. if (this.invert)
  32798. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32799. };
  32800. // Static methods
  32801. /**
  32802. * Creates a default mesh for the Volumeric Light Scattering post-process
  32803. * @param {string} The mesh name
  32804. * @param {BABYLON.Scene} The scene where to create the mesh
  32805. * @return {BABYLON.Mesh} the default mesh
  32806. */
  32807. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32808. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32809. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32810. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32811. return mesh;
  32812. };
  32813. return VolumetricLightScatteringPostProcess;
  32814. })(BABYLON.PostProcess);
  32815. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32816. })(BABYLON || (BABYLON = {}));
  32817. var BABYLON;
  32818. (function (BABYLON) {
  32819. var LensRenderingPipeline = (function (_super) {
  32820. __extends(LensRenderingPipeline, _super);
  32821. /**
  32822. * @constructor
  32823. *
  32824. * Effect parameters are as follow:
  32825. * {
  32826. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32827. * edge_blur: number; // from 0 to x (1 for realism)
  32828. * distortion: number; // from 0 to x (1 for realism)
  32829. * grain_amount: number; // from 0 to 1
  32830. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32831. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32832. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32833. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32834. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32835. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32836. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32837. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32838. * }
  32839. * Note: if an effect parameter is unset, effect is disabled
  32840. *
  32841. * @param {string} name - The rendering pipeline name
  32842. * @param {object} parameters - An object containing all parameters (see above)
  32843. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32844. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  32845. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32846. */
  32847. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32848. var _this = this;
  32849. if (ratio === void 0) { ratio = 1.0; }
  32850. _super.call(this, scene.getEngine(), name);
  32851. // Lens effects can be of the following:
  32852. // - chromatic aberration (slight shift of RGB colors)
  32853. // - blur on the edge of the lens
  32854. // - lens distortion
  32855. // - depth-of-field blur & highlights enhancing
  32856. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32857. // - grain effect (noise or custom texture)
  32858. // Two additional texture samplers are needed:
  32859. // - depth map (for depth-of-field)
  32860. // - grain texture
  32861. /**
  32862. * The chromatic aberration PostProcess id in the pipeline
  32863. * @type {string}
  32864. */
  32865. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32866. /**
  32867. * The highlights enhancing PostProcess id in the pipeline
  32868. * @type {string}
  32869. */
  32870. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32871. /**
  32872. * The depth-of-field PostProcess id in the pipeline
  32873. * @type {string}
  32874. */
  32875. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32876. this._scene = scene;
  32877. // Fetch texture samplers
  32878. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32879. if (parameters.grain_texture) {
  32880. this._grainTexture = parameters.grain_texture;
  32881. }
  32882. else {
  32883. this._createGrainTexture();
  32884. }
  32885. // save parameters
  32886. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32887. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32888. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32889. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32890. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32891. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32892. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32893. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32894. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32895. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32896. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32897. // Create effects
  32898. this._createChromaticAberrationPostProcess(ratio);
  32899. this._createHighlightsPostProcess(ratio);
  32900. this._createDepthOfFieldPostProcess(ratio / 4);
  32901. // Set up pipeline
  32902. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32903. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32904. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32905. if (this._highlightsGain == -1) {
  32906. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32907. }
  32908. // Finish
  32909. scene.postProcessRenderPipelineManager.addPipeline(this);
  32910. if (cameras) {
  32911. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32912. }
  32913. }
  32914. // public methods (self explanatory)
  32915. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32916. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32917. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32918. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32919. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32920. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32921. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32922. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32923. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32924. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32925. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32926. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32927. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32928. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32929. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32930. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32931. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32932. this._highlightsGain = amount;
  32933. };
  32934. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32935. if (this._highlightsGain == -1) {
  32936. this._highlightsGain = 1.0;
  32937. }
  32938. this._highlightsThreshold = amount;
  32939. };
  32940. LensRenderingPipeline.prototype.disableHighlights = function () {
  32941. this._highlightsGain = -1;
  32942. };
  32943. /**
  32944. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32945. */
  32946. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32947. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32948. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32949. this._chromaticAberrationPostProcess = undefined;
  32950. this._highlightsPostProcess = undefined;
  32951. this._depthOfFieldPostProcess = undefined;
  32952. this._grainTexture.dispose();
  32953. if (disableDepthRender)
  32954. this._scene.disableDepthRenderer();
  32955. };
  32956. // colors shifting and distortion
  32957. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32958. var _this = this;
  32959. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  32960. [], // samplers
  32961. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32962. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32963. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32964. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32965. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32966. };
  32967. };
  32968. // highlights enhancing
  32969. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  32970. var _this = this;
  32971. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  32972. [], // samplers
  32973. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32974. this._highlightsPostProcess.onApply = function (effect) {
  32975. effect.setFloat('gain', _this._highlightsGain);
  32976. effect.setFloat('threshold', _this._highlightsThreshold);
  32977. effect.setBool('pentagon', _this._dofPentagon);
  32978. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  32979. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32980. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32981. };
  32982. };
  32983. // colors shifting and distortion
  32984. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  32985. var _this = this;
  32986. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  32987. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  32988. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  32989. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32990. this._depthOfFieldPostProcess.onApply = function (effect) {
  32991. effect.setTexture("depthSampler", _this._depthTexture);
  32992. effect.setTexture("grainSampler", _this._grainTexture);
  32993. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  32994. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  32995. effect.setFloat('grain_amount', _this._grainAmount);
  32996. effect.setBool('blur_noise', _this._blurNoise);
  32997. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32998. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32999. effect.setFloat('distortion', _this._distortion);
  33000. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33001. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33002. effect.setFloat('aperture', _this._dofAperture);
  33003. effect.setFloat('darken', _this._dofDarken);
  33004. effect.setFloat('edge_blur', _this._edgeBlur);
  33005. effect.setBool('highlights', (_this._highlightsGain != -1));
  33006. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33007. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33008. };
  33009. };
  33010. // creates a black and white random noise texture, 512x512
  33011. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33012. var size = 512;
  33013. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33014. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33015. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33016. var context = this._grainTexture.getContext();
  33017. var rand = function (min, max) {
  33018. return Math.random() * (max - min) + min;
  33019. };
  33020. var value;
  33021. for (var x = 0; x < size; x++) {
  33022. for (var y = 0; y < size; y++) {
  33023. value = Math.floor(rand(0.42, 0.58) * 255);
  33024. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33025. context.fillRect(x, y, 1, 1);
  33026. }
  33027. }
  33028. this._grainTexture.update(false);
  33029. };
  33030. return LensRenderingPipeline;
  33031. })(BABYLON.PostProcessRenderPipeline);
  33032. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33033. })(BABYLON || (BABYLON = {}));
  33034. //
  33035. // This post-process allows the modification of rendered colors by using
  33036. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33037. //
  33038. // The object needs to be provided an url to a texture containing the color
  33039. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33040. // Use an image editing software to tweak the LUT to match your needs.
  33041. //
  33042. // For an example of a color LUT, see here:
  33043. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33044. // For explanations on color grading, see here:
  33045. // http://udn.epicgames.com/Three/ColorGrading.html
  33046. //
  33047. var BABYLON;
  33048. (function (BABYLON) {
  33049. var ColorCorrectionPostProcess = (function (_super) {
  33050. __extends(ColorCorrectionPostProcess, _super);
  33051. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33052. var _this = this;
  33053. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33054. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33055. this._colorTableTexture.anisotropicFilteringLevel = 1;
  33056. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33057. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33058. this.onApply = function (effect) {
  33059. effect.setTexture("colorTable", _this._colorTableTexture);
  33060. };
  33061. }
  33062. return ColorCorrectionPostProcess;
  33063. })(BABYLON.PostProcess);
  33064. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  33065. })(BABYLON || (BABYLON = {}));
  33066. var BABYLON;
  33067. (function (BABYLON) {
  33068. var AnaglyphFreeCamera = (function (_super) {
  33069. __extends(AnaglyphFreeCamera, _super);
  33070. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  33071. _super.call(this, name, position, scene);
  33072. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33073. }
  33074. return AnaglyphFreeCamera;
  33075. })(BABYLON.FreeCamera);
  33076. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33077. var AnaglyphArcRotateCamera = (function (_super) {
  33078. __extends(AnaglyphArcRotateCamera, _super);
  33079. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33080. _super.call(this, name, alpha, beta, radius, target, scene);
  33081. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33082. }
  33083. return AnaglyphArcRotateCamera;
  33084. })(BABYLON.ArcRotateCamera);
  33085. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33086. var AnaglyphGamepadCamera = (function (_super) {
  33087. __extends(AnaglyphGamepadCamera, _super);
  33088. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33089. _super.call(this, name, position, scene);
  33090. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33091. }
  33092. return AnaglyphGamepadCamera;
  33093. })(BABYLON.GamepadCamera);
  33094. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33095. var StereoscopicFreeCamera = (function (_super) {
  33096. __extends(StereoscopicFreeCamera, _super);
  33097. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33098. _super.call(this, name, position, scene);
  33099. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33100. }
  33101. return StereoscopicFreeCamera;
  33102. })(BABYLON.FreeCamera);
  33103. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33104. var StereoscopicArcRotateCamera = (function (_super) {
  33105. __extends(StereoscopicArcRotateCamera, _super);
  33106. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33107. _super.call(this, name, alpha, beta, radius, target, scene);
  33108. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33109. }
  33110. return StereoscopicArcRotateCamera;
  33111. })(BABYLON.ArcRotateCamera);
  33112. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33113. var StereoscopicGamepadCamera = (function (_super) {
  33114. __extends(StereoscopicGamepadCamera, _super);
  33115. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33116. _super.call(this, name, position, scene);
  33117. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33118. }
  33119. return StereoscopicGamepadCamera;
  33120. })(BABYLON.GamepadCamera);
  33121. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33122. })(BABYLON || (BABYLON = {}));
  33123. var BABYLON;
  33124. (function (BABYLON) {
  33125. var HDRRenderingPipeline = (function (_super) {
  33126. __extends(HDRRenderingPipeline, _super);
  33127. /**
  33128. * @constructor
  33129. * @param {string} name - The rendering pipeline name
  33130. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33131. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  33132. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33133. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33134. */
  33135. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33136. var _this = this;
  33137. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33138. _super.call(this, scene.getEngine(), name);
  33139. /**
  33140. * Public members
  33141. */
  33142. // Gaussian Blur
  33143. /**
  33144. * Gaussian blur coefficient
  33145. * @type {number}
  33146. */
  33147. this.gaussCoeff = 0.3;
  33148. /**
  33149. * Gaussian blur mean
  33150. * @type {number}
  33151. */
  33152. this.gaussMean = 1.0;
  33153. /**
  33154. * Gaussian blur standard deviation
  33155. * @type {number}
  33156. */
  33157. this.gaussStandDev = 0.8;
  33158. // HDR
  33159. /**
  33160. * Exposure, controls the overall intensity of the pipeline
  33161. * @type {number}
  33162. */
  33163. this.exposure = 1.0;
  33164. /**
  33165. * Minimum luminance that the post-process can output. Luminance is >= 0
  33166. * @type {number}
  33167. */
  33168. this.minimumLuminance = 1.0;
  33169. /**
  33170. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33171. * @type {number}
  33172. */
  33173. this.maximumLuminance = 1e20;
  33174. /**
  33175. * Increase rate for luminance: eye adaptation speed to dark
  33176. * @type {number}
  33177. */
  33178. this.luminanceIncreaserate = 0.5;
  33179. /**
  33180. * Decrease rate for luminance: eye adaptation speed to bright
  33181. * @type {number}
  33182. */
  33183. this.luminanceDecreaseRate = 0.5;
  33184. // Bright pass
  33185. /**
  33186. * Minimum luminance needed to compute HDR
  33187. * @type {number}
  33188. */
  33189. this.brightThreshold = 0.8;
  33190. this._needUpdate = true;
  33191. this._scene = scene;
  33192. // Bright pass
  33193. this._createBrightPassPostProcess(scene, ratio);
  33194. // Down sample X4
  33195. this._createDownSampleX4PostProcess(scene, ratio);
  33196. // Create gaussian blur post-processes
  33197. this._createGaussianBlurPostProcess(scene, ratio);
  33198. // Texture adder
  33199. this._createTextureAdderPostProcess(scene, ratio);
  33200. // Luminance generator
  33201. this._createLuminanceGeneratorPostProcess(scene);
  33202. // HDR
  33203. this._createHDRPostProcess(scene, ratio);
  33204. // Pass postprocess
  33205. if (originalPostProcess === null) {
  33206. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33207. }
  33208. else {
  33209. this._originalPostProcess = originalPostProcess;
  33210. }
  33211. // Configure pipeline
  33212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33216. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33217. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33218. var addDownSamplerPostProcess = function (id) {
  33219. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33220. };
  33221. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33222. addDownSamplerPostProcess(i);
  33223. }
  33224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33225. // Finish
  33226. scene.postProcessRenderPipelineManager.addPipeline(this);
  33227. if (cameras !== null) {
  33228. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33229. }
  33230. this.update();
  33231. }
  33232. /**
  33233. * Tells the pipeline to update its post-processes
  33234. */
  33235. HDRRenderingPipeline.prototype.update = function () {
  33236. this._needUpdate = true;
  33237. };
  33238. /**
  33239. * Returns the current calculated luminance
  33240. */
  33241. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33242. return this._hdrCurrentLuminance;
  33243. };
  33244. /**
  33245. * Returns the currently drawn luminance
  33246. */
  33247. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33248. return this._hdrOutputLuminance;
  33249. };
  33250. /**
  33251. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33252. */
  33253. HDRRenderingPipeline.prototype.dispose = function () {
  33254. this._originalPostProcess = undefined;
  33255. this._brightPassPostProcess = undefined;
  33256. this._downSampleX4PostProcess = undefined;
  33257. this._guassianBlurHPostProcess = undefined;
  33258. this._guassianBlurVPostProcess = undefined;
  33259. this._textureAdderPostProcess = undefined;
  33260. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33261. this._downSamplePostProcesses[i] = undefined;
  33262. }
  33263. this._hdrPostProcess = undefined;
  33264. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33265. };
  33266. /**
  33267. * Creates the HDR post-process and computes the luminance adaptation
  33268. */
  33269. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33270. var _this = this;
  33271. var hdrLastLuminance = 0.0;
  33272. this._hdrOutputLuminance = -1.0;
  33273. this._hdrCurrentLuminance = 1.0;
  33274. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33275. this._hdrPostProcess.onApply = function (effect) {
  33276. if (_this._hdrOutputLuminance < 0.0) {
  33277. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33278. }
  33279. else {
  33280. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33281. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33282. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33283. }
  33284. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33285. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33286. }
  33287. else {
  33288. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33289. }
  33290. }
  33291. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33292. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33293. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33294. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33295. effect.setFloat("exposure", _this.exposure);
  33296. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33297. _this._needUpdate = false;
  33298. };
  33299. };
  33300. /**
  33301. * Texture Adder post-process
  33302. */
  33303. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33304. var _this = this;
  33305. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33306. this._textureAdderPostProcess.onApply = function (effect) {
  33307. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33308. };
  33309. };
  33310. /**
  33311. * Down sample X4 post-process
  33312. */
  33313. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33314. var _this = this;
  33315. var downSampleX4Offsets = new Array(32);
  33316. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33317. this._downSampleX4PostProcess.onApply = function (effect) {
  33318. if (_this._needUpdate) {
  33319. var id = 0;
  33320. for (var i = -2; i < 2; i++) {
  33321. for (var j = -2; j < 2; j++) {
  33322. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33323. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33324. id += 2;
  33325. }
  33326. }
  33327. }
  33328. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33329. };
  33330. };
  33331. /**
  33332. * Bright pass post-process
  33333. */
  33334. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33335. var _this = this;
  33336. var brightOffsets = new Array(8);
  33337. var brightPassCallback = function (effect) {
  33338. if (_this._needUpdate) {
  33339. var sU = (1.0 / _this._brightPassPostProcess.width);
  33340. var sV = (1.0 / _this._brightPassPostProcess.height);
  33341. brightOffsets[0] = -0.5 * sU;
  33342. brightOffsets[1] = 0.5 * sV;
  33343. brightOffsets[2] = 0.5 * sU;
  33344. brightOffsets[3] = 0.5 * sV;
  33345. brightOffsets[4] = -0.5 * sU;
  33346. brightOffsets[5] = -0.5 * sV;
  33347. brightOffsets[6] = 0.5 * sU;
  33348. brightOffsets[7] = -0.5 * sV;
  33349. }
  33350. effect.setArray2("dsOffsets", brightOffsets);
  33351. effect.setFloat("brightThreshold", _this.brightThreshold);
  33352. };
  33353. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33354. this._brightPassPostProcess.onApply = brightPassCallback;
  33355. };
  33356. /**
  33357. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33358. */
  33359. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33360. var _this = this;
  33361. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33362. var luminanceOffsets = new Array(8);
  33363. var downSampleOffsets = new Array(18);
  33364. var halfDestPixelSize;
  33365. this._downSamplePostProcesses = new Array(lumSteps);
  33366. // Utils for luminance
  33367. var luminanceUpdateSourceOffsets = function (width, height) {
  33368. var sU = (1.0 / width);
  33369. var sV = (1.0 / height);
  33370. luminanceOffsets[0] = -0.5 * sU;
  33371. luminanceOffsets[1] = 0.5 * sV;
  33372. luminanceOffsets[2] = 0.5 * sU;
  33373. luminanceOffsets[3] = 0.5 * sV;
  33374. luminanceOffsets[4] = -0.5 * sU;
  33375. luminanceOffsets[5] = -0.5 * sV;
  33376. luminanceOffsets[6] = 0.5 * sU;
  33377. luminanceOffsets[7] = -0.5 * sV;
  33378. };
  33379. var luminanceUpdateDestOffsets = function (width, height) {
  33380. var id = 0;
  33381. for (var x = -1; x < 2; x++) {
  33382. for (var y = -1; y < 2; y++) {
  33383. downSampleOffsets[id] = (x) / width;
  33384. downSampleOffsets[id + 1] = (y) / height;
  33385. id += 2;
  33386. }
  33387. }
  33388. };
  33389. // Luminance callback
  33390. var luminanceCallback = function (effect) {
  33391. if (_this._needUpdate) {
  33392. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33393. }
  33394. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33395. effect.setArray2("lumOffsets", luminanceOffsets);
  33396. };
  33397. // Down sample callbacks
  33398. var downSampleCallback = function (indice) {
  33399. var i = indice;
  33400. return function (effect) {
  33401. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33402. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33403. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33404. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33405. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33406. effect.setArray2("dsOffsets", downSampleOffsets);
  33407. };
  33408. };
  33409. var downSampleAfterRenderCallback = function (effect) {
  33410. // Unpack result
  33411. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33412. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  33413. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33414. };
  33415. // Create luminance post-process
  33416. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33417. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  33418. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33419. // Create down sample post-processes
  33420. for (var i = lumSteps - 2; i >= 0; i--) {
  33421. var length = Math.pow(3, i);
  33422. ratio = { width: length, height: length };
  33423. var defines = "#define DOWN_SAMPLE\n";
  33424. if (i === 0) {
  33425. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33426. }
  33427. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33428. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33429. if (i === 0) {
  33430. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33431. }
  33432. }
  33433. };
  33434. /**
  33435. * Gaussian blur post-processes. Horizontal and Vertical
  33436. */
  33437. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33438. var _this = this;
  33439. var blurOffsetsW = new Array(9);
  33440. var blurOffsetsH = new Array(9);
  33441. var blurWeights = new Array(9);
  33442. var uniforms = ["blurOffsets", "blurWeights"];
  33443. // Utils for gaussian blur
  33444. var calculateBlurOffsets = function (height) {
  33445. var lastOutputDimensions = {
  33446. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33447. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33448. };
  33449. for (var i = 0; i < 9; i++) {
  33450. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33451. if (height) {
  33452. blurOffsetsH[i] = value;
  33453. }
  33454. else {
  33455. blurOffsetsW[i] = value;
  33456. }
  33457. }
  33458. };
  33459. var calculateWeights = function () {
  33460. var x = 0.0;
  33461. for (var i = 0; i < 9; i++) {
  33462. x = (i - 4.0) / 4.0;
  33463. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  33464. }
  33465. };
  33466. // Callback
  33467. var gaussianBlurCallback = function (height) {
  33468. return function (effect) {
  33469. if (_this._needUpdate) {
  33470. calculateWeights();
  33471. calculateBlurOffsets(height);
  33472. }
  33473. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33474. effect.setArray("blurWeights", blurWeights);
  33475. };
  33476. };
  33477. // Create horizontal gaussian blur post-processes
  33478. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33479. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33480. // Create vertical gaussian blur post-process
  33481. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33482. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33483. };
  33484. // Luminance generator
  33485. HDRRenderingPipeline.LUM_STEPS = 6;
  33486. return HDRRenderingPipeline;
  33487. })(BABYLON.PostProcessRenderPipeline);
  33488. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33489. })(BABYLON || (BABYLON = {}));
  33490. var BABYLON;
  33491. (function (BABYLON) {
  33492. var FaceAdjacencies = (function () {
  33493. function FaceAdjacencies() {
  33494. this.edges = new Array();
  33495. this.edgesConnectedCount = 0;
  33496. }
  33497. return FaceAdjacencies;
  33498. })();
  33499. var EdgesRenderer = (function () {
  33500. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33501. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33502. if (epsilon === void 0) { epsilon = 0.95; }
  33503. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33504. this._linesPositions = new Array();
  33505. this._linesNormals = new Array();
  33506. this._linesIndices = new Array();
  33507. this._buffers = new Array();
  33508. this._checkVerticesInsteadOfIndices = false;
  33509. this._source = source;
  33510. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  33511. this._epsilon = epsilon;
  33512. this._prepareRessources();
  33513. this._generateEdgesLines();
  33514. }
  33515. EdgesRenderer.prototype._prepareRessources = function () {
  33516. if (this._lineShader) {
  33517. return;
  33518. }
  33519. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  33520. attributes: ["position", "normal"],
  33521. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  33522. });
  33523. this._lineShader.disableDepthWrite = true;
  33524. this._lineShader.backFaceCulling = false;
  33525. };
  33526. EdgesRenderer.prototype.dispose = function () {
  33527. this._vb0.dispose();
  33528. this._vb1.dispose();
  33529. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  33530. this._lineShader.dispose();
  33531. };
  33532. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  33533. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  33534. return 0;
  33535. }
  33536. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  33537. return 1;
  33538. }
  33539. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  33540. return 2;
  33541. }
  33542. return -1;
  33543. };
  33544. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  33545. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  33546. return 0;
  33547. }
  33548. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  33549. return 1;
  33550. }
  33551. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  33552. return 2;
  33553. }
  33554. return -1;
  33555. };
  33556. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  33557. var needToCreateLine;
  33558. if (edge === undefined) {
  33559. needToCreateLine = true;
  33560. }
  33561. else {
  33562. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  33563. needToCreateLine = dotProduct < this._epsilon;
  33564. }
  33565. if (needToCreateLine) {
  33566. var offset = this._linesPositions.length / 3;
  33567. var normal = p0.subtract(p1);
  33568. normal.normalize();
  33569. // Positions
  33570. this._linesPositions.push(p0.x);
  33571. this._linesPositions.push(p0.y);
  33572. this._linesPositions.push(p0.z);
  33573. this._linesPositions.push(p0.x);
  33574. this._linesPositions.push(p0.y);
  33575. this._linesPositions.push(p0.z);
  33576. this._linesPositions.push(p1.x);
  33577. this._linesPositions.push(p1.y);
  33578. this._linesPositions.push(p1.z);
  33579. this._linesPositions.push(p1.x);
  33580. this._linesPositions.push(p1.y);
  33581. this._linesPositions.push(p1.z);
  33582. // Normals
  33583. this._linesNormals.push(p1.x);
  33584. this._linesNormals.push(p1.y);
  33585. this._linesNormals.push(p1.z);
  33586. this._linesNormals.push(-1);
  33587. this._linesNormals.push(p1.x);
  33588. this._linesNormals.push(p1.y);
  33589. this._linesNormals.push(p1.z);
  33590. this._linesNormals.push(1);
  33591. this._linesNormals.push(p0.x);
  33592. this._linesNormals.push(p0.y);
  33593. this._linesNormals.push(p0.z);
  33594. this._linesNormals.push(-1);
  33595. this._linesNormals.push(p0.x);
  33596. this._linesNormals.push(p0.y);
  33597. this._linesNormals.push(p0.z);
  33598. this._linesNormals.push(1);
  33599. // Indices
  33600. this._linesIndices.push(offset);
  33601. this._linesIndices.push(offset + 1);
  33602. this._linesIndices.push(offset + 2);
  33603. this._linesIndices.push(offset);
  33604. this._linesIndices.push(offset + 2);
  33605. this._linesIndices.push(offset + 3);
  33606. }
  33607. };
  33608. EdgesRenderer.prototype._generateEdgesLines = function () {
  33609. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33610. var indices = this._source.getIndices();
  33611. // First let's find adjacencies
  33612. var adjacencies = new Array();
  33613. var faceNormals = new Array();
  33614. var index;
  33615. var faceAdjacencies;
  33616. // Prepare faces
  33617. for (index = 0; index < indices.length; index += 3) {
  33618. faceAdjacencies = new FaceAdjacencies();
  33619. var p0Index = indices[index];
  33620. var p1Index = indices[index + 1];
  33621. var p2Index = indices[index + 2];
  33622. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  33623. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  33624. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  33625. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  33626. faceNormal.normalize();
  33627. faceNormals.push(faceNormal);
  33628. adjacencies.push(faceAdjacencies);
  33629. }
  33630. // Scan
  33631. for (index = 0; index < adjacencies.length; index++) {
  33632. faceAdjacencies = adjacencies[index];
  33633. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  33634. var otherFaceAdjacencies = adjacencies[otherIndex];
  33635. if (faceAdjacencies.edgesConnectedCount === 3) {
  33636. break;
  33637. }
  33638. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  33639. continue;
  33640. }
  33641. var otherP0 = indices[otherIndex * 3];
  33642. var otherP1 = indices[otherIndex * 3 + 1];
  33643. var otherP2 = indices[otherIndex * 3 + 2];
  33644. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  33645. var otherEdgeIndex;
  33646. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  33647. continue;
  33648. }
  33649. switch (edgeIndex) {
  33650. case 0:
  33651. if (this._checkVerticesInsteadOfIndices) {
  33652. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33653. }
  33654. else {
  33655. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  33656. }
  33657. break;
  33658. case 1:
  33659. if (this._checkVerticesInsteadOfIndices) {
  33660. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33661. }
  33662. else {
  33663. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  33664. }
  33665. break;
  33666. case 2:
  33667. if (this._checkVerticesInsteadOfIndices) {
  33668. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33669. }
  33670. else {
  33671. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  33672. }
  33673. break;
  33674. }
  33675. if (otherEdgeIndex === -1) {
  33676. continue;
  33677. }
  33678. faceAdjacencies.edges[edgeIndex] = otherIndex;
  33679. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  33680. faceAdjacencies.edgesConnectedCount++;
  33681. otherFaceAdjacencies.edgesConnectedCount++;
  33682. if (faceAdjacencies.edgesConnectedCount === 3) {
  33683. break;
  33684. }
  33685. }
  33686. }
  33687. }
  33688. // Create lines
  33689. for (index = 0; index < adjacencies.length; index++) {
  33690. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  33691. var current = adjacencies[index];
  33692. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  33693. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  33694. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  33695. }
  33696. // Merge into a single mesh
  33697. var engine = this._source.getScene().getEngine();
  33698. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  33699. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  33700. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  33701. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  33702. this._ib = engine.createIndexBuffer(this._linesIndices);
  33703. this._indicesCount = this._linesIndices.length;
  33704. };
  33705. EdgesRenderer.prototype.render = function () {
  33706. if (!this._lineShader.isReady()) {
  33707. return;
  33708. }
  33709. var scene = this._source.getScene();
  33710. var engine = scene.getEngine();
  33711. this._lineShader._preBind();
  33712. // VBOs
  33713. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  33714. scene.resetCachedMaterial();
  33715. this._lineShader.setColor4("color", this._source.edgesColor);
  33716. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  33717. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  33718. this._lineShader.bind(this._source.getWorldMatrix());
  33719. // Draw order
  33720. engine.draw(true, 0, this._indicesCount);
  33721. this._lineShader.unbind();
  33722. engine.setDepthWrite(true);
  33723. };
  33724. return EdgesRenderer;
  33725. })();
  33726. BABYLON.EdgesRenderer = EdgesRenderer;
  33727. })(BABYLON || (BABYLON = {}));
  33728. var BABYLON;
  33729. (function (BABYLON) {
  33730. (function (TonemappingOperator) {
  33731. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  33732. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  33733. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  33734. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  33735. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  33736. var TonemappingOperator = BABYLON.TonemappingOperator;
  33737. ;
  33738. var TonemapPostProcess = (function (_super) {
  33739. __extends(TonemapPostProcess, _super);
  33740. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  33741. var _this = this;
  33742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33743. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33744. this._operator = operator;
  33745. this._exposureAdjustment = exposureAdjustment;
  33746. var params = ["_ExposureAdjustment"];
  33747. var defines = "#define ";
  33748. if (operator === TonemappingOperator.Hable)
  33749. defines += "HABLE_TONEMAPPING";
  33750. else if (operator === TonemappingOperator.Reinhard)
  33751. defines += "REINHARD_TONEMAPPING";
  33752. else if (operator === TonemappingOperator.HejiDawson)
  33753. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  33754. else if (operator === TonemappingOperator.Photographic)
  33755. defines += "PHOTOGRAPHIC_TONEMAPPING";
  33756. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  33757. this.onApply = function (effect) {
  33758. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  33759. };
  33760. }
  33761. return TonemapPostProcess;
  33762. })(BABYLON.PostProcess);
  33763. BABYLON.TonemapPostProcess = TonemapPostProcess;
  33764. })(BABYLON || (BABYLON = {}));
  33765. var BABYLON;
  33766. (function (BABYLON) {
  33767. var DefaultLoadingScreen = (function () {
  33768. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33769. var _this = this;
  33770. if (_loadingText === void 0) { _loadingText = ""; }
  33771. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33772. this._renderingCanvas = _renderingCanvas;
  33773. this._loadingText = _loadingText;
  33774. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33775. // Resize
  33776. this._resizeLoadingUI = function () {
  33777. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33778. _this._loadingDiv.style.position = "absolute";
  33779. _this._loadingDiv.style.left = canvasRect.left + "px";
  33780. _this._loadingDiv.style.top = canvasRect.top + "px";
  33781. _this._loadingDiv.style.width = canvasRect.width + "px";
  33782. _this._loadingDiv.style.height = canvasRect.height + "px";
  33783. };
  33784. }
  33785. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33786. var _this = this;
  33787. this._loadingDiv = document.createElement("div");
  33788. this._loadingDiv.style.opacity = "0";
  33789. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33790. // Loading text
  33791. this._loadingTextDiv = document.createElement("div");
  33792. this._loadingTextDiv.style.position = "absolute";
  33793. this._loadingTextDiv.style.left = "0";
  33794. this._loadingTextDiv.style.top = "50%";
  33795. this._loadingTextDiv.style.marginTop = "80px";
  33796. this._loadingTextDiv.style.width = "100%";
  33797. this._loadingTextDiv.style.height = "20px";
  33798. this._loadingTextDiv.style.fontFamily = "Arial";
  33799. this._loadingTextDiv.style.fontSize = "14px";
  33800. this._loadingTextDiv.style.color = "white";
  33801. this._loadingTextDiv.style.textAlign = "center";
  33802. this._loadingTextDiv.innerHTML = "Loading";
  33803. this._loadingDiv.appendChild(this._loadingTextDiv);
  33804. //set the predefined text
  33805. this._loadingTextDiv.innerHTML = this._loadingText;
  33806. // Loading img
  33807. var imgBack = new Image();
  33808. 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==";
  33809. imgBack.style.position = "absolute";
  33810. imgBack.style.left = "50%";
  33811. imgBack.style.top = "50%";
  33812. imgBack.style.marginLeft = "-50px";
  33813. imgBack.style.marginTop = "-50px";
  33814. imgBack.style.transition = "transform 1.0s ease";
  33815. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33816. var deg = 360;
  33817. var onTransitionEnd = function () {
  33818. deg += 360;
  33819. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33820. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33821. };
  33822. imgBack.addEventListener("transitionend", onTransitionEnd);
  33823. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33824. this._loadingDiv.appendChild(imgBack);
  33825. // front image
  33826. var imgFront = new Image();
  33827. 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=";
  33828. imgFront.style.position = "absolute";
  33829. imgFront.style.left = "50%";
  33830. imgFront.style.top = "50%";
  33831. imgFront.style.marginLeft = "-50px";
  33832. imgFront.style.marginTop = "-50px";
  33833. this._loadingDiv.appendChild(imgFront);
  33834. this._resizeLoadingUI();
  33835. window.addEventListener("resize", this._resizeLoadingUI);
  33836. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33837. document.body.appendChild(this._loadingDiv);
  33838. setTimeout(function () {
  33839. _this._loadingDiv.style.opacity = "1";
  33840. imgBack.style.transform = "rotateZ(360deg)";
  33841. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33842. }, 0);
  33843. };
  33844. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33845. var _this = this;
  33846. if (!this._loadingDiv) {
  33847. return;
  33848. }
  33849. var onTransitionEnd = function () {
  33850. if (!_this._loadingDiv) {
  33851. return;
  33852. }
  33853. document.body.removeChild(_this._loadingDiv);
  33854. window.removeEventListener("resize", _this._resizeLoadingUI);
  33855. _this._loadingDiv = null;
  33856. };
  33857. this._loadingDiv.style.opacity = "0";
  33858. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33859. };
  33860. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33861. set: function (text) {
  33862. this._loadingText = text;
  33863. if (this._loadingTextDiv) {
  33864. this._loadingTextDiv.innerHTML = this._loadingText;
  33865. }
  33866. },
  33867. enumerable: true,
  33868. configurable: true
  33869. });
  33870. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33871. get: function () {
  33872. return this._loadingDivBackgroundColor;
  33873. },
  33874. set: function (color) {
  33875. this._loadingDivBackgroundColor = color;
  33876. if (!this._loadingDiv) {
  33877. return;
  33878. }
  33879. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33880. },
  33881. enumerable: true,
  33882. configurable: true
  33883. });
  33884. return DefaultLoadingScreen;
  33885. })();
  33886. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33887. })(BABYLON || (BABYLON = {}));
  33888. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\n#ifdef ROUGHNESS\r\nuniform float roughness;\r\n#endif\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = glossiness * specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\t\tbias = roughness;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n vec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\tfloat lightmapIllum = clamp(dot(lightmapColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n\r\n\tif (lightmapIllum > vLightmapInfos.z)\r\n\t{\r\n\t\tcolor.rgb += vec3(lightmapIllum, lightmapIllum, lightmapIllum);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcolor.rgb *= lightmapIllum;\r\n\t}\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  33889. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert();var u=new i(o.x/n*2-1,-(o.y/r*2-1),o.z),l=i.TransformCoordinates(u,h),m=u.x*h.m[3]+u.y*h.m[7]+u.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(l=l.scale(1/m)),l},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(t,o,n){var r=i.Zero();return i.RotationFromAxisToRef(t,o,n,r),r},i.RotationFromAxisToRef=function(o,n,r,s){var e,a,h,u=i.Normalize(o),l=i.Normalize(r),m=f.X,x=f.Y,y=0,c=0,p=0,z=0,M=0,w=0,d=0,I=-1,D=0,S=0;t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?w=1:t.Tools.WithinEpsilon(l.x,0,t.Engine.Epsilon)?z=1:(d=l.z/l.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),a=new i(z,M,w),a.normalize(),h=i.Cross(l,a),h.normalize(),e=i.Cross(u,a),e.normalize(),i.Dot(l,e)<0&&(I=1),S=i.Dot(u,a),S=Math.min(1,Math.max(-1,S)),p=Math.acos(S)*I,i.Dot(a,m)<0&&(p=Math.PI+p,a=a.scaleInPlace(-1),h=h.scaleInPlace(-1),D++);var v,g;z=0,M=0,w=0,I=-1,t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?z=1:(d=a.z/a.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),v=new i(z,M,w),v.normalize(),g=i.Cross(v,a),g.normalize(),e=i.Cross(l,v),e.normalize(),i.Dot(a,e)<0&&(I=1),S=i.Dot(l,v),S=Math.min(1,Math.max(-1,S)),c=Math.acos(S)*I,i.Dot(g,x)<0&&(c=Math.PI+c,g=g.scaleInPlace(-1),v=v.scaleInPlace(-1),D++),I=-1,e=i.Cross(m,a),e.normalize(),i.Dot(e,x)<0&&(I=1),S=i.Dot(a,m),S=Math.min(1,Math.max(-1,S)),y=-Math.acos(S)*I,0>S&&2>D&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return i.normalize(),n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\n\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o,n,r,s,e=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(o=1/this.direction.x,n=(t.x-this.origin.x)*o,r=(i.x-this.origin.x)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(o=1/this.direction.y,n=(t.y-this.origin.y)*o,r=(i.y-this.origin.y)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(o=1/this.direction.z,n=(t.z-this.origin.z)*o,r=(i.z-this.origin.z)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function i(t,i,o){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=o||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),a=this._tangents[u],h=this._binormals[u-1],this._normals[u]=r.Cross(h,a),this._raw||this._normals[u].normalize(),this._binormals[u]=r.Cross(a,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0===o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},i.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0===o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},i.prototype._normalVector=function(i,o,n){var s;if(void 0===n||null===n){var e;t.Tools.WithinEpsilon(o.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.z,1,t.Engine.Epsilon)||(e=new r(0,0,1)):e=new r(1,0,0):e=new r(0,-1,0),s=r.Cross(o,e)}else s=r.Cross(o,n),r.CrossToRef(s,o,s);return s.normalize(),s},i}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=d;var I=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_}(BABYLON||(BABYLON={}));";
  33890. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33891. module.exports = BABYLON;
  33892. };