babylon.max.js 1.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256
  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 result = Matrix.Zero();
  1989. Matrix.RotationAxisToRef(axis, angle, result);
  1990. return result;
  1991. };
  1992. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1993. var s = Math.sin(-angle);
  1994. var c = Math.cos(-angle);
  1995. var c1 = 1 - c;
  1996. axis.normalize();
  1997. result.m[0] = (axis.x * axis.x) * c1 + c;
  1998. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1999. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2000. result.m[3] = 0.0;
  2001. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2002. result.m[5] = (axis.y * axis.y) * c1 + c;
  2003. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2004. result.m[7] = 0.0;
  2005. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2006. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2007. result.m[10] = (axis.z * axis.z) * c1 + c;
  2008. result.m[11] = 0.0;
  2009. result.m[15] = 1.0;
  2010. };
  2011. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2012. var result = new Matrix();
  2013. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2014. return result;
  2015. };
  2016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2018. this._tempQuaternion.toRotationMatrix(result);
  2019. };
  2020. Matrix.Scaling = function (x, y, z) {
  2021. var result = Matrix.Zero();
  2022. Matrix.ScalingToRef(x, y, z, result);
  2023. return result;
  2024. };
  2025. Matrix.ScalingToRef = function (x, y, z, result) {
  2026. result.m[0] = x;
  2027. result.m[1] = 0;
  2028. result.m[2] = 0;
  2029. result.m[3] = 0;
  2030. result.m[4] = 0;
  2031. result.m[5] = y;
  2032. result.m[6] = 0;
  2033. result.m[7] = 0;
  2034. result.m[8] = 0;
  2035. result.m[9] = 0;
  2036. result.m[10] = z;
  2037. result.m[11] = 0;
  2038. result.m[12] = 0;
  2039. result.m[13] = 0;
  2040. result.m[14] = 0;
  2041. result.m[15] = 1.0;
  2042. };
  2043. Matrix.Translation = function (x, y, z) {
  2044. var result = Matrix.Identity();
  2045. Matrix.TranslationToRef(x, y, z, result);
  2046. return result;
  2047. };
  2048. Matrix.TranslationToRef = function (x, y, z, result) {
  2049. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2050. };
  2051. Matrix.LookAtLH = function (eye, target, up) {
  2052. var result = Matrix.Zero();
  2053. Matrix.LookAtLHToRef(eye, target, up, result);
  2054. return result;
  2055. };
  2056. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2057. // Z axis
  2058. target.subtractToRef(eye, this._zAxis);
  2059. this._zAxis.normalize();
  2060. // X axis
  2061. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2062. if (this._xAxis.lengthSquared() === 0) {
  2063. this._xAxis.x = 1.0;
  2064. }
  2065. else {
  2066. this._xAxis.normalize();
  2067. }
  2068. // Y axis
  2069. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2070. this._yAxis.normalize();
  2071. // Eye angles
  2072. var ex = -Vector3.Dot(this._xAxis, eye);
  2073. var ey = -Vector3.Dot(this._yAxis, eye);
  2074. var ez = -Vector3.Dot(this._zAxis, eye);
  2075. 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);
  2076. };
  2077. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2078. var out = result.m;
  2079. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2080. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2081. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2082. // cc.kmVec3Subtract(f, pCenter, pEye);
  2083. var f = SIMD.float32x4.sub(center, eye);
  2084. // cc.kmVec3Normalize(f, f);
  2085. var tmp = SIMD.float32x4.mul(f, f);
  2086. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2087. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2088. // cc.kmVec3Assign(up, pUp);
  2089. // cc.kmVec3Normalize(up, up);
  2090. tmp = SIMD.float32x4.mul(up, up);
  2091. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2092. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2093. // cc.kmVec3Cross(s, f, up);
  2094. 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)));
  2095. // cc.kmVec3Normalize(s, s);
  2096. tmp = SIMD.float32x4.mul(s, s);
  2097. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2098. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2099. // cc.kmVec3Cross(u, s, f);
  2100. 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)));
  2101. // cc.kmVec3Normalize(s, s);
  2102. tmp = SIMD.float32x4.mul(s, s);
  2103. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2104. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2105. var zero = SIMD.float32x4.splat(0.0);
  2106. s = SIMD.float32x4.neg(s);
  2107. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2108. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2109. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2110. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2111. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2112. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2113. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2114. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2115. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2116. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2117. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2118. var b3 = SIMD.float32x4.neg(eye);
  2119. b3 = SIMD.float32x4.withW(b3, 1.0);
  2120. 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)))));
  2121. 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)))));
  2122. 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)))));
  2123. 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)))));
  2124. };
  2125. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2126. var matrix = Matrix.Zero();
  2127. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2128. return matrix;
  2129. };
  2130. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2131. var hw = 2.0 / width;
  2132. var hh = 2.0 / height;
  2133. var id = 1.0 / (zfar - znear);
  2134. var nid = znear / (znear - zfar);
  2135. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2136. };
  2137. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2138. var matrix = Matrix.Zero();
  2139. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2140. return matrix;
  2141. };
  2142. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2143. result.m[0] = 2.0 / (right - left);
  2144. result.m[1] = result.m[2] = result.m[3] = 0;
  2145. result.m[5] = 2.0 / (top - bottom);
  2146. result.m[4] = result.m[6] = result.m[7] = 0;
  2147. result.m[10] = -1.0 / (znear - zfar);
  2148. result.m[8] = result.m[9] = result.m[11] = 0;
  2149. result.m[12] = (left + right) / (left - right);
  2150. result.m[13] = (top + bottom) / (bottom - top);
  2151. result.m[14] = znear / (znear - zfar);
  2152. result.m[15] = 1.0;
  2153. };
  2154. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2155. var matrix = Matrix.Zero();
  2156. matrix.m[0] = (2.0 * znear) / width;
  2157. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2158. matrix.m[5] = (2.0 * znear) / height;
  2159. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2160. matrix.m[10] = -zfar / (znear - zfar);
  2161. matrix.m[8] = matrix.m[9] = 0.0;
  2162. matrix.m[11] = 1.0;
  2163. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2164. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2165. return matrix;
  2166. };
  2167. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2168. var matrix = Matrix.Zero();
  2169. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2170. return matrix;
  2171. };
  2172. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2173. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2174. var tan = 1.0 / (Math.tan(fov * 0.5));
  2175. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2176. if (v_fixed) {
  2177. result.m[0] = tan / aspect;
  2178. }
  2179. else {
  2180. result.m[0] = tan;
  2181. }
  2182. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2183. if (v_fixed) {
  2184. result.m[5] = tan;
  2185. }
  2186. else {
  2187. result.m[5] = tan * aspect;
  2188. }
  2189. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2190. result.m[8] = result.m[9] = 0.0;
  2191. result.m[10] = -zfar / (znear - zfar);
  2192. result.m[11] = 1.0;
  2193. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2194. result.m[14] = (znear * zfar) / (znear - zfar);
  2195. };
  2196. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2197. var cw = viewport.width;
  2198. var ch = viewport.height;
  2199. var cx = viewport.x;
  2200. var cy = viewport.y;
  2201. 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);
  2202. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2203. };
  2204. Matrix.GetAsMatrix2x2 = function (matrix) {
  2205. return new Float32Array([
  2206. matrix.m[0], matrix.m[1],
  2207. matrix.m[4], matrix.m[5]
  2208. ]);
  2209. };
  2210. Matrix.GetAsMatrix3x3 = function (matrix) {
  2211. return new Float32Array([
  2212. matrix.m[0], matrix.m[1], matrix.m[2],
  2213. matrix.m[4], matrix.m[5], matrix.m[6],
  2214. matrix.m[8], matrix.m[9], matrix.m[10]
  2215. ]);
  2216. };
  2217. Matrix.Transpose = function (matrix) {
  2218. var result = new Matrix();
  2219. result.m[0] = matrix.m[0];
  2220. result.m[1] = matrix.m[4];
  2221. result.m[2] = matrix.m[8];
  2222. result.m[3] = matrix.m[12];
  2223. result.m[4] = matrix.m[1];
  2224. result.m[5] = matrix.m[5];
  2225. result.m[6] = matrix.m[9];
  2226. result.m[7] = matrix.m[13];
  2227. result.m[8] = matrix.m[2];
  2228. result.m[9] = matrix.m[6];
  2229. result.m[10] = matrix.m[10];
  2230. result.m[11] = matrix.m[14];
  2231. result.m[12] = matrix.m[3];
  2232. result.m[13] = matrix.m[7];
  2233. result.m[14] = matrix.m[11];
  2234. result.m[15] = matrix.m[15];
  2235. return result;
  2236. };
  2237. Matrix.Reflection = function (plane) {
  2238. var matrix = new Matrix();
  2239. Matrix.ReflectionToRef(plane, matrix);
  2240. return matrix;
  2241. };
  2242. Matrix.ReflectionToRef = function (plane, result) {
  2243. plane.normalize();
  2244. var x = plane.normal.x;
  2245. var y = plane.normal.y;
  2246. var z = plane.normal.z;
  2247. var temp = -2 * x;
  2248. var temp2 = -2 * y;
  2249. var temp3 = -2 * z;
  2250. result.m[0] = (temp * x) + 1;
  2251. result.m[1] = temp2 * x;
  2252. result.m[2] = temp3 * x;
  2253. result.m[3] = 0.0;
  2254. result.m[4] = temp * y;
  2255. result.m[5] = (temp2 * y) + 1;
  2256. result.m[6] = temp3 * y;
  2257. result.m[7] = 0.0;
  2258. result.m[8] = temp * z;
  2259. result.m[9] = temp2 * z;
  2260. result.m[10] = (temp3 * z) + 1;
  2261. result.m[11] = 0.0;
  2262. result.m[12] = temp * plane.d;
  2263. result.m[13] = temp2 * plane.d;
  2264. result.m[14] = temp3 * plane.d;
  2265. result.m[15] = 1.0;
  2266. };
  2267. Matrix._tempQuaternion = new Quaternion();
  2268. Matrix._xAxis = Vector3.Zero();
  2269. Matrix._yAxis = Vector3.Zero();
  2270. Matrix._zAxis = Vector3.Zero();
  2271. return Matrix;
  2272. })();
  2273. BABYLON.Matrix = Matrix;
  2274. var Plane = (function () {
  2275. function Plane(a, b, c, d) {
  2276. this.normal = new Vector3(a, b, c);
  2277. this.d = d;
  2278. }
  2279. Plane.prototype.asArray = function () {
  2280. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2281. };
  2282. // Methods
  2283. Plane.prototype.clone = function () {
  2284. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2285. };
  2286. Plane.prototype.normalize = function () {
  2287. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2288. var magnitude = 0;
  2289. if (norm !== 0) {
  2290. magnitude = 1.0 / norm;
  2291. }
  2292. this.normal.x *= magnitude;
  2293. this.normal.y *= magnitude;
  2294. this.normal.z *= magnitude;
  2295. this.d *= magnitude;
  2296. return this;
  2297. };
  2298. Plane.prototype.transform = function (transformation) {
  2299. var transposedMatrix = Matrix.Transpose(transformation);
  2300. var x = this.normal.x;
  2301. var y = this.normal.y;
  2302. var z = this.normal.z;
  2303. var d = this.d;
  2304. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2305. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2306. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2307. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2308. return new Plane(normalX, normalY, normalZ, finalD);
  2309. };
  2310. Plane.prototype.dotCoordinate = function (point) {
  2311. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2312. };
  2313. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2314. var x1 = point2.x - point1.x;
  2315. var y1 = point2.y - point1.y;
  2316. var z1 = point2.z - point1.z;
  2317. var x2 = point3.x - point1.x;
  2318. var y2 = point3.y - point1.y;
  2319. var z2 = point3.z - point1.z;
  2320. var yz = (y1 * z2) - (z1 * y2);
  2321. var xz = (z1 * x2) - (x1 * z2);
  2322. var xy = (x1 * y2) - (y1 * x2);
  2323. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2324. var invPyth;
  2325. if (pyth !== 0) {
  2326. invPyth = 1.0 / pyth;
  2327. }
  2328. else {
  2329. invPyth = 0;
  2330. }
  2331. this.normal.x = yz * invPyth;
  2332. this.normal.y = xz * invPyth;
  2333. this.normal.z = xy * invPyth;
  2334. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2335. return this;
  2336. };
  2337. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2338. var dot = Vector3.Dot(this.normal, direction);
  2339. return (dot <= epsilon);
  2340. };
  2341. Plane.prototype.signedDistanceTo = function (point) {
  2342. return Vector3.Dot(point, this.normal) + this.d;
  2343. };
  2344. // Statics
  2345. Plane.FromArray = function (array) {
  2346. return new Plane(array[0], array[1], array[2], array[3]);
  2347. };
  2348. Plane.FromPoints = function (point1, point2, point3) {
  2349. var result = new Plane(0, 0, 0, 0);
  2350. result.copyFromPoints(point1, point2, point3);
  2351. return result;
  2352. };
  2353. Plane.FromPositionAndNormal = function (origin, normal) {
  2354. var result = new Plane(0, 0, 0, 0);
  2355. normal.normalize();
  2356. result.normal = normal;
  2357. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2358. return result;
  2359. };
  2360. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2361. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2362. return Vector3.Dot(point, normal) + d;
  2363. };
  2364. return Plane;
  2365. })();
  2366. BABYLON.Plane = Plane;
  2367. var Viewport = (function () {
  2368. function Viewport(x, y, width, height) {
  2369. this.x = x;
  2370. this.y = y;
  2371. this.width = width;
  2372. this.height = height;
  2373. }
  2374. Viewport.prototype.toGlobal = function (engine) {
  2375. var width = engine.getRenderWidth();
  2376. var height = engine.getRenderHeight();
  2377. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2378. };
  2379. return Viewport;
  2380. })();
  2381. BABYLON.Viewport = Viewport;
  2382. var Frustum = (function () {
  2383. function Frustum() {
  2384. }
  2385. Frustum.GetPlanes = function (transform) {
  2386. var frustumPlanes = [];
  2387. for (var index = 0; index < 6; index++) {
  2388. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2389. }
  2390. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2391. return frustumPlanes;
  2392. };
  2393. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2394. // Near
  2395. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2396. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2397. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2398. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2399. frustumPlanes[0].normalize();
  2400. // Far
  2401. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2402. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2403. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2404. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2405. frustumPlanes[1].normalize();
  2406. // Left
  2407. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2408. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2409. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2410. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2411. frustumPlanes[2].normalize();
  2412. // Right
  2413. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2414. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2415. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2416. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2417. frustumPlanes[3].normalize();
  2418. // Top
  2419. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2420. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2421. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2422. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2423. frustumPlanes[4].normalize();
  2424. // Bottom
  2425. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2426. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2427. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2428. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2429. frustumPlanes[5].normalize();
  2430. };
  2431. return Frustum;
  2432. })();
  2433. BABYLON.Frustum = Frustum;
  2434. var Ray = (function () {
  2435. function Ray(origin, direction, length) {
  2436. if (length === void 0) { length = Number.MAX_VALUE; }
  2437. this.origin = origin;
  2438. this.direction = direction;
  2439. this.length = length;
  2440. }
  2441. // Methods
  2442. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2443. var d = 0.0;
  2444. var maxValue = Number.MAX_VALUE;
  2445. var inv;
  2446. var min;
  2447. var max;
  2448. var temp;
  2449. if (Math.abs(this.direction.x) < 0.0000001) {
  2450. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2451. return false;
  2452. }
  2453. }
  2454. else {
  2455. inv = 1.0 / this.direction.x;
  2456. min = (minimum.x - this.origin.x) * inv;
  2457. max = (maximum.x - this.origin.x) * inv;
  2458. if (max === -Infinity) {
  2459. max = Infinity;
  2460. }
  2461. if (min > max) {
  2462. temp = min;
  2463. min = max;
  2464. max = temp;
  2465. }
  2466. d = Math.max(min, d);
  2467. maxValue = Math.min(max, maxValue);
  2468. if (d > maxValue) {
  2469. return false;
  2470. }
  2471. }
  2472. if (Math.abs(this.direction.y) < 0.0000001) {
  2473. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2474. return false;
  2475. }
  2476. }
  2477. else {
  2478. inv = 1.0 / this.direction.y;
  2479. min = (minimum.y - this.origin.y) * inv;
  2480. max = (maximum.y - this.origin.y) * inv;
  2481. if (max === -Infinity) {
  2482. max = Infinity;
  2483. }
  2484. if (min > max) {
  2485. temp = min;
  2486. min = max;
  2487. max = temp;
  2488. }
  2489. d = Math.max(min, d);
  2490. maxValue = Math.min(max, maxValue);
  2491. if (d > maxValue) {
  2492. return false;
  2493. }
  2494. }
  2495. if (Math.abs(this.direction.z) < 0.0000001) {
  2496. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2497. return false;
  2498. }
  2499. }
  2500. else {
  2501. inv = 1.0 / this.direction.z;
  2502. min = (minimum.z - this.origin.z) * inv;
  2503. max = (maximum.z - this.origin.z) * inv;
  2504. if (max === -Infinity) {
  2505. max = Infinity;
  2506. }
  2507. if (min > max) {
  2508. temp = min;
  2509. min = max;
  2510. max = temp;
  2511. }
  2512. d = Math.max(min, d);
  2513. maxValue = Math.min(max, maxValue);
  2514. if (d > maxValue) {
  2515. return false;
  2516. }
  2517. }
  2518. return true;
  2519. };
  2520. Ray.prototype.intersectsBox = function (box) {
  2521. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2522. };
  2523. Ray.prototype.intersectsSphere = function (sphere) {
  2524. var x = sphere.center.x - this.origin.x;
  2525. var y = sphere.center.y - this.origin.y;
  2526. var z = sphere.center.z - this.origin.z;
  2527. var pyth = (x * x) + (y * y) + (z * z);
  2528. var rr = sphere.radius * sphere.radius;
  2529. if (pyth <= rr) {
  2530. return true;
  2531. }
  2532. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2533. if (dot < 0.0) {
  2534. return false;
  2535. }
  2536. var temp = pyth - (dot * dot);
  2537. return temp <= rr;
  2538. };
  2539. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2540. if (!this._edge1) {
  2541. this._edge1 = Vector3.Zero();
  2542. this._edge2 = Vector3.Zero();
  2543. this._pvec = Vector3.Zero();
  2544. this._tvec = Vector3.Zero();
  2545. this._qvec = Vector3.Zero();
  2546. }
  2547. vertex1.subtractToRef(vertex0, this._edge1);
  2548. vertex2.subtractToRef(vertex0, this._edge2);
  2549. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2550. var det = Vector3.Dot(this._edge1, this._pvec);
  2551. if (det === 0) {
  2552. return null;
  2553. }
  2554. var invdet = 1 / det;
  2555. this.origin.subtractToRef(vertex0, this._tvec);
  2556. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2557. if (bu < 0 || bu > 1.0) {
  2558. return null;
  2559. }
  2560. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2561. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2562. if (bv < 0 || bu + bv > 1.0) {
  2563. return null;
  2564. }
  2565. //check if the distance is longer than the predefined length.
  2566. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2567. if (distance > this.length) {
  2568. return null;
  2569. }
  2570. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2571. };
  2572. // Statics
  2573. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2574. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2575. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2576. var direction = end.subtract(start);
  2577. direction.normalize();
  2578. return new Ray(start, direction);
  2579. };
  2580. /**
  2581. * 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
  2582. * transformed to the given world matrix.
  2583. * @param origin The origin point
  2584. * @param end The end point
  2585. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2586. */
  2587. Ray.CreateNewFromTo = function (origin, end, world) {
  2588. if (world === void 0) { world = Matrix.Identity(); }
  2589. var direction = end.subtract(origin);
  2590. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2591. direction.normalize();
  2592. return Ray.Transform(new Ray(origin, direction, length), world);
  2593. };
  2594. Ray.Transform = function (ray, matrix) {
  2595. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2596. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2597. return new Ray(newOrigin, newDirection, ray.length);
  2598. };
  2599. return Ray;
  2600. })();
  2601. BABYLON.Ray = Ray;
  2602. (function (Space) {
  2603. Space[Space["LOCAL"] = 0] = "LOCAL";
  2604. Space[Space["WORLD"] = 1] = "WORLD";
  2605. })(BABYLON.Space || (BABYLON.Space = {}));
  2606. var Space = BABYLON.Space;
  2607. var Axis = (function () {
  2608. function Axis() {
  2609. }
  2610. Axis.X = new Vector3(1, 0, 0);
  2611. Axis.Y = new Vector3(0, 1, 0);
  2612. Axis.Z = new Vector3(0, 0, 1);
  2613. return Axis;
  2614. })();
  2615. BABYLON.Axis = Axis;
  2616. ;
  2617. var BezierCurve = (function () {
  2618. function BezierCurve() {
  2619. }
  2620. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2621. // Extract X (which is equal to time here)
  2622. var f0 = 1 - 3 * x2 + 3 * x1;
  2623. var f1 = 3 * x2 - 6 * x1;
  2624. var f2 = 3 * x1;
  2625. var refinedT = t;
  2626. for (var i = 0; i < 5; i++) {
  2627. var refinedT2 = refinedT * refinedT;
  2628. var refinedT3 = refinedT2 * refinedT;
  2629. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2630. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2631. refinedT -= (x - t) * slope;
  2632. refinedT = Math.min(1, Math.max(0, refinedT));
  2633. }
  2634. // Resolve cubic bezier for the given x
  2635. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2636. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2637. Math.pow(refinedT, 3);
  2638. };
  2639. return BezierCurve;
  2640. })();
  2641. BABYLON.BezierCurve = BezierCurve;
  2642. (function (Orientation) {
  2643. Orientation[Orientation["CW"] = 0] = "CW";
  2644. Orientation[Orientation["CCW"] = 1] = "CCW";
  2645. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2646. var Orientation = BABYLON.Orientation;
  2647. var Angle = (function () {
  2648. function Angle(radians) {
  2649. var _this = this;
  2650. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2651. this.radians = function () { return _this._radians; };
  2652. this._radians = radians;
  2653. if (this._radians < 0)
  2654. this._radians += (2 * Math.PI);
  2655. }
  2656. Angle.BetweenTwoPoints = function (a, b) {
  2657. var delta = b.subtract(a);
  2658. var theta = Math.atan2(delta.y, delta.x);
  2659. return new Angle(theta);
  2660. };
  2661. Angle.FromRadians = function (radians) {
  2662. return new Angle(radians);
  2663. };
  2664. Angle.FromDegrees = function (degrees) {
  2665. return new Angle(degrees * Math.PI / 180);
  2666. };
  2667. return Angle;
  2668. })();
  2669. BABYLON.Angle = Angle;
  2670. var Arc2 = (function () {
  2671. function Arc2(startPoint, midPoint, endPoint) {
  2672. this.startPoint = startPoint;
  2673. this.midPoint = midPoint;
  2674. this.endPoint = endPoint;
  2675. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2676. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2677. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2678. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2679. 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);
  2680. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2681. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2682. var a1 = this.startAngle.degrees();
  2683. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2684. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2685. // angles correction
  2686. if (a2 - a1 > +180.0)
  2687. a2 -= 360.0;
  2688. if (a2 - a1 < -180.0)
  2689. a2 += 360.0;
  2690. if (a3 - a2 > +180.0)
  2691. a3 -= 360.0;
  2692. if (a3 - a2 < -180.0)
  2693. a3 += 360.0;
  2694. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2695. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2696. }
  2697. return Arc2;
  2698. })();
  2699. BABYLON.Arc2 = Arc2;
  2700. var PathCursor = (function () {
  2701. function PathCursor(path) {
  2702. this.path = path;
  2703. this._onchange = new Array();
  2704. this.value = 0;
  2705. this.animations = new Array();
  2706. }
  2707. PathCursor.prototype.getPoint = function () {
  2708. var point = this.path.getPointAtLengthPosition(this.value);
  2709. return new Vector3(point.x, 0, point.y);
  2710. };
  2711. PathCursor.prototype.moveAhead = function (step) {
  2712. if (step === void 0) { step = 0.002; }
  2713. this.move(step);
  2714. return this;
  2715. };
  2716. PathCursor.prototype.moveBack = function (step) {
  2717. if (step === void 0) { step = 0.002; }
  2718. this.move(-step);
  2719. return this;
  2720. };
  2721. PathCursor.prototype.move = function (step) {
  2722. if (Math.abs(step) > 1) {
  2723. throw "step size should be less than 1.";
  2724. }
  2725. this.value += step;
  2726. this.ensureLimits();
  2727. this.raiseOnChange();
  2728. return this;
  2729. };
  2730. PathCursor.prototype.ensureLimits = function () {
  2731. while (this.value > 1) {
  2732. this.value -= 1;
  2733. }
  2734. while (this.value < 0) {
  2735. this.value += 1;
  2736. }
  2737. return this;
  2738. };
  2739. // used by animation engine
  2740. PathCursor.prototype.markAsDirty = function (propertyName) {
  2741. this.ensureLimits();
  2742. this.raiseOnChange();
  2743. return this;
  2744. };
  2745. PathCursor.prototype.raiseOnChange = function () {
  2746. var _this = this;
  2747. this._onchange.forEach(function (f) { return f(_this); });
  2748. return this;
  2749. };
  2750. PathCursor.prototype.onchange = function (f) {
  2751. this._onchange.push(f);
  2752. return this;
  2753. };
  2754. return PathCursor;
  2755. })();
  2756. BABYLON.PathCursor = PathCursor;
  2757. var Path2 = (function () {
  2758. function Path2(x, y) {
  2759. this._points = new Array();
  2760. this._length = 0;
  2761. this.closed = false;
  2762. this._points.push(new Vector2(x, y));
  2763. }
  2764. Path2.prototype.addLineTo = function (x, y) {
  2765. if (closed) {
  2766. BABYLON.Tools.Error("cannot add lines to closed paths");
  2767. return this;
  2768. }
  2769. var newPoint = new Vector2(x, y);
  2770. var previousPoint = this._points[this._points.length - 1];
  2771. this._points.push(newPoint);
  2772. this._length += newPoint.subtract(previousPoint).length();
  2773. return this;
  2774. };
  2775. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2776. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2777. if (closed) {
  2778. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2779. return this;
  2780. }
  2781. var startPoint = this._points[this._points.length - 1];
  2782. var midPoint = new Vector2(midX, midY);
  2783. var endPoint = new Vector2(endX, endY);
  2784. var arc = new Arc2(startPoint, midPoint, endPoint);
  2785. var increment = arc.angle.radians() / numberOfSegments;
  2786. if (arc.orientation === Orientation.CW)
  2787. increment *= -1;
  2788. var currentAngle = arc.startAngle.radians() + increment;
  2789. for (var i = 0; i < numberOfSegments; i++) {
  2790. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2791. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2792. this.addLineTo(x, y);
  2793. currentAngle += increment;
  2794. }
  2795. return this;
  2796. };
  2797. Path2.prototype.close = function () {
  2798. this.closed = true;
  2799. return this;
  2800. };
  2801. Path2.prototype.length = function () {
  2802. var result = this._length;
  2803. if (!this.closed) {
  2804. var lastPoint = this._points[this._points.length - 1];
  2805. var firstPoint = this._points[0];
  2806. result += (firstPoint.subtract(lastPoint).length());
  2807. }
  2808. return result;
  2809. };
  2810. Path2.prototype.getPoints = function () {
  2811. return this._points;
  2812. };
  2813. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2814. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2815. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2816. return Vector2.Zero();
  2817. }
  2818. var lengthPosition = normalizedLengthPosition * this.length();
  2819. var previousOffset = 0;
  2820. for (var i = 0; i < this._points.length; i++) {
  2821. var j = (i + 1) % this._points.length;
  2822. var a = this._points[i];
  2823. var b = this._points[j];
  2824. var bToA = b.subtract(a);
  2825. var nextOffset = (bToA.length() + previousOffset);
  2826. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2827. var dir = bToA.normalize();
  2828. var localOffset = lengthPosition - previousOffset;
  2829. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2830. }
  2831. previousOffset = nextOffset;
  2832. }
  2833. BABYLON.Tools.Error("internal error");
  2834. return Vector2.Zero();
  2835. };
  2836. Path2.StartingAt = function (x, y) {
  2837. return new Path2(x, y);
  2838. };
  2839. return Path2;
  2840. })();
  2841. BABYLON.Path2 = Path2;
  2842. var Path3D = (function () {
  2843. /**
  2844. * new Path3D(path, normal, raw)
  2845. * path : an array of Vector3, the curve axis of the Path3D
  2846. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2847. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2848. */
  2849. function Path3D(path, firstNormal, raw) {
  2850. this.path = path;
  2851. this._curve = new Array();
  2852. this._distances = new Array();
  2853. this._tangents = new Array();
  2854. this._normals = new Array();
  2855. this._binormals = new Array();
  2856. for (var p = 0; p < path.length; p++) {
  2857. this._curve[p] = path[p].clone(); // hard copy
  2858. }
  2859. this._raw = raw || false;
  2860. this._compute(firstNormal);
  2861. }
  2862. Path3D.prototype.getCurve = function () {
  2863. return this._curve;
  2864. };
  2865. Path3D.prototype.getTangents = function () {
  2866. return this._tangents;
  2867. };
  2868. Path3D.prototype.getNormals = function () {
  2869. return this._normals;
  2870. };
  2871. Path3D.prototype.getBinormals = function () {
  2872. return this._binormals;
  2873. };
  2874. Path3D.prototype.getDistances = function () {
  2875. return this._distances;
  2876. };
  2877. Path3D.prototype.update = function (path, firstNormal) {
  2878. for (var p = 0; p < path.length; p++) {
  2879. this._curve[p].x = path[p].x;
  2880. this._curve[p].y = path[p].y;
  2881. this._curve[p].z = path[p].z;
  2882. }
  2883. this._compute(firstNormal);
  2884. return this;
  2885. };
  2886. // private function compute() : computes tangents, normals and binormals
  2887. Path3D.prototype._compute = function (firstNormal) {
  2888. var l = this._curve.length;
  2889. // first and last tangents
  2890. this._tangents[0] = this._getFirstNonNullVector(0);
  2891. if (!this._raw) {
  2892. this._tangents[0].normalize();
  2893. }
  2894. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2895. if (!this._raw) {
  2896. this._tangents[l - 1].normalize();
  2897. }
  2898. // normals and binormals at first point : arbitrary vector with _normalVector()
  2899. var tg0 = this._tangents[0];
  2900. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2901. this._normals[0] = pp0;
  2902. if (!this._raw) {
  2903. this._normals[0].normalize();
  2904. }
  2905. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2906. if (!this._raw) {
  2907. this._binormals[0].normalize();
  2908. }
  2909. this._distances[0] = 0;
  2910. // normals and binormals : next points
  2911. var prev; // previous vector (segment)
  2912. var cur; // current vector (segment)
  2913. var curTang; // current tangent
  2914. // previous normal
  2915. var prevBinor; // previous binormal
  2916. for (var i = 1; i < l; i++) {
  2917. // tangents
  2918. prev = this._getLastNonNullVector(i);
  2919. if (i < l - 1) {
  2920. cur = this._getFirstNonNullVector(i);
  2921. this._tangents[i] = prev.add(cur);
  2922. this._tangents[i].normalize();
  2923. }
  2924. this._distances[i] = this._distances[i - 1] + prev.length();
  2925. // normals and binormals
  2926. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2927. curTang = this._tangents[i];
  2928. prevBinor = this._binormals[i - 1];
  2929. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2930. if (!this._raw) {
  2931. this._normals[i].normalize();
  2932. }
  2933. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2934. if (!this._raw) {
  2935. this._binormals[i].normalize();
  2936. }
  2937. }
  2938. };
  2939. // private function getFirstNonNullVector(index)
  2940. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2941. Path3D.prototype._getFirstNonNullVector = function (index) {
  2942. var i = 1;
  2943. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2944. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2945. i++;
  2946. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2947. }
  2948. return nNVector;
  2949. };
  2950. // private function getLastNonNullVector(index)
  2951. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2952. Path3D.prototype._getLastNonNullVector = function (index) {
  2953. var i = 1;
  2954. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2955. while (nLVector.length() === 0 && index > i + 1) {
  2956. i++;
  2957. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2958. }
  2959. return nLVector;
  2960. };
  2961. // private function normalVector(v0, vt, va) :
  2962. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2963. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2964. Path3D.prototype._normalVector = function (v0, vt, va) {
  2965. var normal0;
  2966. if (va === undefined || va === null) {
  2967. var point;
  2968. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2969. point = new Vector3(0, -1, 0);
  2970. }
  2971. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2972. point = new Vector3(1, 0, 0);
  2973. }
  2974. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2975. point = new Vector3(0, 0, 1);
  2976. }
  2977. normal0 = Vector3.Cross(vt, point);
  2978. }
  2979. else {
  2980. normal0 = Vector3.Cross(vt, va);
  2981. Vector3.CrossToRef(normal0, vt, normal0);
  2982. }
  2983. normal0.normalize();
  2984. return normal0;
  2985. };
  2986. return Path3D;
  2987. })();
  2988. BABYLON.Path3D = Path3D;
  2989. var Curve3 = (function () {
  2990. function Curve3(points) {
  2991. this._length = 0;
  2992. this._points = points;
  2993. this._length = this._computeLength(points);
  2994. }
  2995. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2996. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2997. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2998. var bez = new Array();
  2999. var equation = function (t, val0, val1, val2) {
  3000. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  3001. return res;
  3002. };
  3003. for (var i = 0; i <= nbPoints; i++) {
  3004. 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)));
  3005. }
  3006. return new Curve3(bez);
  3007. };
  3008. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  3009. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3010. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3011. var bez = new Array();
  3012. var equation = function (t, val0, val1, val2, val3) {
  3013. 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;
  3014. return res;
  3015. };
  3016. for (var i = 0; i <= nbPoints; i++) {
  3017. 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)));
  3018. }
  3019. return new Curve3(bez);
  3020. };
  3021. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  3022. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3023. var hermite = new Array();
  3024. var step = 1 / nbPoints;
  3025. for (var i = 0; i <= nbPoints; i++) {
  3026. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3027. }
  3028. return new Curve3(hermite);
  3029. };
  3030. Curve3.prototype.getPoints = function () {
  3031. return this._points;
  3032. };
  3033. Curve3.prototype.length = function () {
  3034. return this._length;
  3035. };
  3036. Curve3.prototype.continue = function (curve) {
  3037. var lastPoint = this._points[this._points.length - 1];
  3038. var continuedPoints = this._points.slice();
  3039. var curvePoints = curve.getPoints();
  3040. for (var i = 1; i < curvePoints.length; i++) {
  3041. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3042. }
  3043. var continuedCurve = new Curve3(continuedPoints);
  3044. return continuedCurve;
  3045. };
  3046. Curve3.prototype._computeLength = function (path) {
  3047. var l = 0;
  3048. for (var i = 1; i < path.length; i++) {
  3049. l += (path[i].subtract(path[i - 1])).length();
  3050. }
  3051. return l;
  3052. };
  3053. return Curve3;
  3054. })();
  3055. BABYLON.Curve3 = Curve3;
  3056. // Vertex formats
  3057. var PositionNormalVertex = (function () {
  3058. function PositionNormalVertex(position, normal) {
  3059. if (position === void 0) { position = Vector3.Zero(); }
  3060. if (normal === void 0) { normal = Vector3.Up(); }
  3061. this.position = position;
  3062. this.normal = normal;
  3063. }
  3064. PositionNormalVertex.prototype.clone = function () {
  3065. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3066. };
  3067. return PositionNormalVertex;
  3068. })();
  3069. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3070. var PositionNormalTextureVertex = (function () {
  3071. function PositionNormalTextureVertex(position, normal, uv) {
  3072. if (position === void 0) { position = Vector3.Zero(); }
  3073. if (normal === void 0) { normal = Vector3.Up(); }
  3074. if (uv === void 0) { uv = Vector2.Zero(); }
  3075. this.position = position;
  3076. this.normal = normal;
  3077. this.uv = uv;
  3078. }
  3079. PositionNormalTextureVertex.prototype.clone = function () {
  3080. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3081. };
  3082. return PositionNormalTextureVertex;
  3083. })();
  3084. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3085. // SIMD
  3086. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3087. var previousInvertToRef = Matrix.prototype.invertToRef;
  3088. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3089. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3090. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3091. var SIMDHelper = (function () {
  3092. function SIMDHelper() {
  3093. }
  3094. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3095. get: function () {
  3096. return SIMDHelper._isEnabled;
  3097. },
  3098. enumerable: true,
  3099. configurable: true
  3100. });
  3101. SIMDHelper.DisableSIMD = function () {
  3102. // Replace functions
  3103. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3104. Matrix.prototype.invertToRef = previousInvertToRef;
  3105. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3106. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3107. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3108. SIMDHelper._isEnabled = false;
  3109. };
  3110. SIMDHelper.EnableSIMD = function () {
  3111. if (window.SIMD === undefined) {
  3112. return;
  3113. }
  3114. // Replace functions
  3115. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3116. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3117. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3118. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3119. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3120. Object.defineProperty(Vector3.prototype, "x", {
  3121. get: function () { return this._data[0]; },
  3122. set: function (value) {
  3123. if (!this._data) {
  3124. this._data = new Float32Array(3);
  3125. }
  3126. this._data[0] = value;
  3127. }
  3128. });
  3129. Object.defineProperty(Vector3.prototype, "y", {
  3130. get: function () { return this._data[1]; },
  3131. set: function (value) {
  3132. this._data[1] = value;
  3133. }
  3134. });
  3135. Object.defineProperty(Vector3.prototype, "z", {
  3136. get: function () { return this._data[2]; },
  3137. set: function (value) {
  3138. this._data[2] = value;
  3139. }
  3140. });
  3141. SIMDHelper._isEnabled = true;
  3142. };
  3143. SIMDHelper._isEnabled = false;
  3144. return SIMDHelper;
  3145. })();
  3146. BABYLON.SIMDHelper = SIMDHelper;
  3147. })(BABYLON || (BABYLON = {}));
  3148. var BABYLON;
  3149. (function (BABYLON) {
  3150. var Database = (function () {
  3151. function Database(urlToScene, callbackManifestChecked) {
  3152. // Handling various flavors of prefixed version of IndexedDB
  3153. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3154. this.callbackManifestChecked = callbackManifestChecked;
  3155. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3156. this.db = null;
  3157. this.enableSceneOffline = false;
  3158. this.enableTexturesOffline = false;
  3159. this.manifestVersionFound = 0;
  3160. this.mustUpdateRessources = false;
  3161. this.hasReachedQuota = false;
  3162. if (!Database.IDBStorageEnabled) {
  3163. this.callbackManifestChecked(true);
  3164. }
  3165. else {
  3166. this.checkManifestFile();
  3167. }
  3168. }
  3169. Database.prototype.checkManifestFile = function () {
  3170. var _this = this;
  3171. function noManifestFile() {
  3172. that.enableSceneOffline = false;
  3173. that.enableTexturesOffline = false;
  3174. that.callbackManifestChecked(false);
  3175. }
  3176. var that = this;
  3177. var manifestURL = this.currentSceneUrl + ".manifest";
  3178. var xhr = new XMLHttpRequest();
  3179. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3180. xhr.open("GET", manifestURLTimeStamped, true);
  3181. xhr.addEventListener("load", function () {
  3182. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3183. try {
  3184. var manifestFile = JSON.parse(xhr.response);
  3185. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3186. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3187. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3188. _this.manifestVersionFound = manifestFile.version;
  3189. }
  3190. if (_this.callbackManifestChecked) {
  3191. _this.callbackManifestChecked(true);
  3192. }
  3193. }
  3194. catch (ex) {
  3195. noManifestFile();
  3196. }
  3197. }
  3198. else {
  3199. noManifestFile();
  3200. }
  3201. }, false);
  3202. xhr.addEventListener("error", function (event) {
  3203. noManifestFile();
  3204. }, false);
  3205. try {
  3206. xhr.send();
  3207. }
  3208. catch (ex) {
  3209. BABYLON.Tools.Error("Error on XHR send request.");
  3210. that.callbackManifestChecked(false);
  3211. }
  3212. };
  3213. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3214. var _this = this;
  3215. function handleError() {
  3216. that.isSupported = false;
  3217. if (errorCallback)
  3218. errorCallback();
  3219. }
  3220. var that = this;
  3221. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3222. // Your browser doesn't support IndexedDB
  3223. this.isSupported = false;
  3224. if (errorCallback)
  3225. errorCallback();
  3226. }
  3227. else {
  3228. // If the DB hasn't been opened or created yet
  3229. if (!this.db) {
  3230. this.hasReachedQuota = false;
  3231. this.isSupported = true;
  3232. var request = this.idbFactory.open("babylonjs", 1);
  3233. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3234. request.onerror = function (event) {
  3235. handleError();
  3236. };
  3237. // executes when a version change transaction cannot complete due to other active transactions
  3238. request.onblocked = function (event) {
  3239. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3240. handleError();
  3241. };
  3242. // DB has been opened successfully
  3243. request.onsuccess = function (event) {
  3244. _this.db = request.result;
  3245. successCallback();
  3246. };
  3247. // Initialization of the DB. Creating Scenes & Textures stores
  3248. request.onupgradeneeded = function (event) {
  3249. _this.db = (event.target).result;
  3250. try {
  3251. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3252. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3253. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3254. }
  3255. catch (ex) {
  3256. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3257. handleError();
  3258. }
  3259. };
  3260. }
  3261. else {
  3262. if (successCallback)
  3263. successCallback();
  3264. }
  3265. }
  3266. };
  3267. Database.prototype.loadImageFromDB = function (url, image) {
  3268. var _this = this;
  3269. var completeURL = Database.ReturnFullUrlLocation(url);
  3270. var saveAndLoadImage = function () {
  3271. if (!_this.hasReachedQuota && _this.db !== null) {
  3272. // the texture is not yet in the DB, let's try to save it
  3273. _this._saveImageIntoDBAsync(completeURL, image);
  3274. }
  3275. else {
  3276. image.src = url;
  3277. }
  3278. };
  3279. if (!this.mustUpdateRessources) {
  3280. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3281. }
  3282. else {
  3283. saveAndLoadImage();
  3284. }
  3285. };
  3286. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3287. if (this.isSupported && this.db !== null) {
  3288. var texture;
  3289. var transaction = this.db.transaction(["textures"]);
  3290. transaction.onabort = function (event) {
  3291. image.src = url;
  3292. };
  3293. transaction.oncomplete = function (event) {
  3294. var blobTextureURL;
  3295. if (texture) {
  3296. var URL = window.URL || window.webkitURL;
  3297. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3298. image.onerror = function () {
  3299. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3300. image.src = url;
  3301. };
  3302. image.src = blobTextureURL;
  3303. }
  3304. else {
  3305. notInDBCallback();
  3306. }
  3307. };
  3308. var getRequest = transaction.objectStore("textures").get(url);
  3309. getRequest.onsuccess = function (event) {
  3310. texture = (event.target).result;
  3311. };
  3312. getRequest.onerror = function (event) {
  3313. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3314. image.src = url;
  3315. };
  3316. }
  3317. else {
  3318. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3319. image.src = url;
  3320. }
  3321. };
  3322. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3323. var _this = this;
  3324. if (this.isSupported) {
  3325. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3326. var generateBlobUrl = function () {
  3327. var blobTextureURL;
  3328. if (blob) {
  3329. var URL = window.URL || window.webkitURL;
  3330. try {
  3331. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3332. }
  3333. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3334. catch (ex) {
  3335. blobTextureURL = URL.createObjectURL(blob);
  3336. }
  3337. }
  3338. image.src = blobTextureURL;
  3339. };
  3340. if (Database.IsUASupportingBlobStorage) {
  3341. var xhr = new XMLHttpRequest(), blob;
  3342. xhr.open("GET", url, true);
  3343. xhr.responseType = "blob";
  3344. xhr.addEventListener("load", function () {
  3345. if (xhr.status === 200) {
  3346. // Blob as response (XHR2)
  3347. blob = xhr.response;
  3348. var transaction = _this.db.transaction(["textures"], "readwrite");
  3349. // the transaction could abort because of a QuotaExceededError error
  3350. transaction.onabort = function (event) {
  3351. try {
  3352. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3353. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3354. this.hasReachedQuota = true;
  3355. }
  3356. }
  3357. catch (ex) { }
  3358. generateBlobUrl();
  3359. };
  3360. transaction.oncomplete = function (event) {
  3361. generateBlobUrl();
  3362. };
  3363. var newTexture = { textureUrl: url, data: blob };
  3364. try {
  3365. // Put the blob into the dabase
  3366. var addRequest = transaction.objectStore("textures").put(newTexture);
  3367. addRequest.onsuccess = function (event) {
  3368. };
  3369. addRequest.onerror = function (event) {
  3370. generateBlobUrl();
  3371. };
  3372. }
  3373. catch (ex) {
  3374. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3375. if (ex.code === 25) {
  3376. Database.IsUASupportingBlobStorage = false;
  3377. }
  3378. image.src = url;
  3379. }
  3380. }
  3381. else {
  3382. image.src = url;
  3383. }
  3384. }, false);
  3385. xhr.addEventListener("error", function (event) {
  3386. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3387. image.src = url;
  3388. }, false);
  3389. xhr.send();
  3390. }
  3391. else {
  3392. image.src = url;
  3393. }
  3394. }
  3395. else {
  3396. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3397. image.src = url;
  3398. }
  3399. };
  3400. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3401. var _this = this;
  3402. var updateVersion = function (event) {
  3403. // the version is not yet in the DB or we need to update it
  3404. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3405. };
  3406. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3407. };
  3408. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3409. var _this = this;
  3410. if (this.isSupported) {
  3411. var version;
  3412. try {
  3413. var transaction = this.db.transaction(["versions"]);
  3414. transaction.oncomplete = function (event) {
  3415. if (version) {
  3416. // If the version in the JSON file is > than the version in DB
  3417. if (_this.manifestVersionFound > version.data) {
  3418. _this.mustUpdateRessources = true;
  3419. updateInDBCallback();
  3420. }
  3421. else {
  3422. callback(version.data);
  3423. }
  3424. }
  3425. else {
  3426. _this.mustUpdateRessources = true;
  3427. updateInDBCallback();
  3428. }
  3429. };
  3430. transaction.onabort = function (event) {
  3431. callback(-1);
  3432. };
  3433. var getRequest = transaction.objectStore("versions").get(url);
  3434. getRequest.onsuccess = function (event) {
  3435. version = (event.target).result;
  3436. };
  3437. getRequest.onerror = function (event) {
  3438. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3439. callback(-1);
  3440. };
  3441. }
  3442. catch (ex) {
  3443. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3444. callback(-1);
  3445. }
  3446. }
  3447. else {
  3448. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3449. callback(-1);
  3450. }
  3451. };
  3452. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3453. var _this = this;
  3454. if (this.isSupported && !this.hasReachedQuota) {
  3455. try {
  3456. // Open a transaction to the database
  3457. var transaction = this.db.transaction(["versions"], "readwrite");
  3458. // the transaction could abort because of a QuotaExceededError error
  3459. transaction.onabort = function (event) {
  3460. try {
  3461. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3462. _this.hasReachedQuota = true;
  3463. }
  3464. }
  3465. catch (ex) { }
  3466. callback(-1);
  3467. };
  3468. transaction.oncomplete = function (event) {
  3469. callback(_this.manifestVersionFound);
  3470. };
  3471. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3472. // Put the scene into the database
  3473. var addRequest = transaction.objectStore("versions").put(newVersion);
  3474. addRequest.onsuccess = function (event) {
  3475. };
  3476. addRequest.onerror = function (event) {
  3477. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3478. };
  3479. }
  3480. catch (ex) {
  3481. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3482. callback(-1);
  3483. }
  3484. }
  3485. else {
  3486. callback(-1);
  3487. }
  3488. };
  3489. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3490. var _this = this;
  3491. var completeUrl = Database.ReturnFullUrlLocation(url);
  3492. var saveAndLoadFile = function (event) {
  3493. // the scene is not yet in the DB, let's try to save it
  3494. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3495. };
  3496. this._checkVersionFromDB(completeUrl, function (version) {
  3497. if (version !== -1) {
  3498. if (!_this.mustUpdateRessources) {
  3499. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3500. }
  3501. else {
  3502. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3503. }
  3504. }
  3505. else {
  3506. errorCallback();
  3507. }
  3508. });
  3509. };
  3510. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3511. if (this.isSupported) {
  3512. var targetStore;
  3513. if (url.indexOf(".babylon") !== -1) {
  3514. targetStore = "scenes";
  3515. }
  3516. else {
  3517. targetStore = "textures";
  3518. }
  3519. var file;
  3520. var transaction = this.db.transaction([targetStore]);
  3521. transaction.oncomplete = function (event) {
  3522. if (file) {
  3523. callback(file.data);
  3524. }
  3525. else {
  3526. notInDBCallback();
  3527. }
  3528. };
  3529. transaction.onabort = function (event) {
  3530. notInDBCallback();
  3531. };
  3532. var getRequest = transaction.objectStore(targetStore).get(url);
  3533. getRequest.onsuccess = function (event) {
  3534. file = (event.target).result;
  3535. };
  3536. getRequest.onerror = function (event) {
  3537. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3538. notInDBCallback();
  3539. };
  3540. }
  3541. else {
  3542. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3543. callback();
  3544. }
  3545. };
  3546. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3547. var _this = this;
  3548. if (this.isSupported) {
  3549. var targetStore;
  3550. if (url.indexOf(".babylon") !== -1) {
  3551. targetStore = "scenes";
  3552. }
  3553. else {
  3554. targetStore = "textures";
  3555. }
  3556. // Create XHR
  3557. var xhr = new XMLHttpRequest(), fileData;
  3558. xhr.open("GET", url, true);
  3559. if (useArrayBuffer) {
  3560. xhr.responseType = "arraybuffer";
  3561. }
  3562. xhr.onprogress = progressCallback;
  3563. xhr.addEventListener("load", function () {
  3564. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3565. // Blob as response (XHR2)
  3566. //fileData = xhr.responseText;
  3567. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3568. if (!_this.hasReachedQuota) {
  3569. // Open a transaction to the database
  3570. var transaction = _this.db.transaction([targetStore], "readwrite");
  3571. // the transaction could abort because of a QuotaExceededError error
  3572. transaction.onabort = function (event) {
  3573. try {
  3574. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3575. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3576. this.hasReachedQuota = true;
  3577. }
  3578. }
  3579. catch (ex) { }
  3580. callback(fileData);
  3581. };
  3582. transaction.oncomplete = function (event) {
  3583. callback(fileData);
  3584. };
  3585. var newFile;
  3586. if (targetStore === "scenes") {
  3587. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3588. }
  3589. else {
  3590. newFile = { textureUrl: url, data: fileData };
  3591. }
  3592. try {
  3593. // Put the scene into the database
  3594. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3595. addRequest.onsuccess = function (event) {
  3596. };
  3597. addRequest.onerror = function (event) {
  3598. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3599. };
  3600. }
  3601. catch (ex) {
  3602. callback(fileData);
  3603. }
  3604. }
  3605. else {
  3606. callback(fileData);
  3607. }
  3608. }
  3609. else {
  3610. callback();
  3611. }
  3612. }, false);
  3613. xhr.addEventListener("error", function (event) {
  3614. BABYLON.Tools.Error("error on XHR request.");
  3615. callback();
  3616. }, false);
  3617. xhr.send();
  3618. }
  3619. else {
  3620. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3621. callback();
  3622. }
  3623. };
  3624. Database.IsUASupportingBlobStorage = true;
  3625. Database.IDBStorageEnabled = true;
  3626. Database.parseURL = function (url) {
  3627. var a = document.createElement('a');
  3628. a.href = url;
  3629. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3630. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3631. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3632. return absLocation;
  3633. };
  3634. Database.ReturnFullUrlLocation = function (url) {
  3635. if (url.indexOf("http:/") === -1) {
  3636. return (Database.parseURL(window.location.href) + url);
  3637. }
  3638. else {
  3639. return url;
  3640. }
  3641. };
  3642. return Database;
  3643. })();
  3644. BABYLON.Database = Database;
  3645. })(BABYLON || (BABYLON = {}));
  3646. var BABYLON;
  3647. (function (BABYLON) {
  3648. var Internals;
  3649. (function (Internals) {
  3650. /*
  3651. * Based on jsTGALoader - Javascript loader for TGA file
  3652. * By Vincent Thibault
  3653. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3654. */
  3655. var TGATools = (function () {
  3656. function TGATools() {
  3657. }
  3658. TGATools.GetTGAHeader = function (data) {
  3659. var offset = 0;
  3660. var header = {
  3661. id_length: data[offset++],
  3662. colormap_type: data[offset++],
  3663. image_type: data[offset++],
  3664. colormap_index: data[offset++] | data[offset++] << 8,
  3665. colormap_length: data[offset++] | data[offset++] << 8,
  3666. colormap_size: data[offset++],
  3667. origin: [
  3668. data[offset++] | data[offset++] << 8,
  3669. data[offset++] | data[offset++] << 8
  3670. ],
  3671. width: data[offset++] | data[offset++] << 8,
  3672. height: data[offset++] | data[offset++] << 8,
  3673. pixel_size: data[offset++],
  3674. flags: data[offset++]
  3675. };
  3676. return header;
  3677. };
  3678. TGATools.UploadContent = function (gl, data) {
  3679. // Not enough data to contain header ?
  3680. if (data.length < 19) {
  3681. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3682. return;
  3683. }
  3684. // Read Header
  3685. var offset = 18;
  3686. var header = TGATools.GetTGAHeader(data);
  3687. // Assume it's a valid Targa file.
  3688. if (header.id_length + offset > data.length) {
  3689. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3690. return;
  3691. }
  3692. // Skip not needed data
  3693. offset += header.id_length;
  3694. var use_rle = false;
  3695. var use_pal = false;
  3696. var use_rgb = false;
  3697. var use_grey = false;
  3698. // Get some informations.
  3699. switch (header.image_type) {
  3700. case TGATools._TYPE_RLE_INDEXED:
  3701. use_rle = true;
  3702. case TGATools._TYPE_INDEXED:
  3703. use_pal = true;
  3704. break;
  3705. case TGATools._TYPE_RLE_RGB:
  3706. use_rle = true;
  3707. case TGATools._TYPE_RGB:
  3708. use_rgb = true;
  3709. break;
  3710. case TGATools._TYPE_RLE_GREY:
  3711. use_rle = true;
  3712. case TGATools._TYPE_GREY:
  3713. use_grey = true;
  3714. break;
  3715. }
  3716. var pixel_data;
  3717. var numAlphaBits = header.flags & 0xf;
  3718. var pixel_size = header.pixel_size >> 3;
  3719. var pixel_total = header.width * header.height * pixel_size;
  3720. // Read palettes
  3721. var palettes;
  3722. if (use_pal) {
  3723. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3724. }
  3725. // Read LRE
  3726. if (use_rle) {
  3727. pixel_data = new Uint8Array(pixel_total);
  3728. var c, count, i;
  3729. var localOffset = 0;
  3730. var pixels = new Uint8Array(pixel_size);
  3731. while (offset < pixel_total && localOffset < pixel_total) {
  3732. c = data[offset++];
  3733. count = (c & 0x7f) + 1;
  3734. // RLE pixels
  3735. if (c & 0x80) {
  3736. // Bind pixel tmp array
  3737. for (i = 0; i < pixel_size; ++i) {
  3738. pixels[i] = data[offset++];
  3739. }
  3740. // Copy pixel array
  3741. for (i = 0; i < count; ++i) {
  3742. pixel_data.set(pixels, localOffset + i * pixel_size);
  3743. }
  3744. localOffset += pixel_size * count;
  3745. }
  3746. else {
  3747. count *= pixel_size;
  3748. for (i = 0; i < count; ++i) {
  3749. pixel_data[localOffset + i] = data[offset++];
  3750. }
  3751. localOffset += count;
  3752. }
  3753. }
  3754. }
  3755. else {
  3756. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3757. }
  3758. // Load to texture
  3759. var x_start, y_start, x_step, y_step, y_end, x_end;
  3760. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3761. default:
  3762. case TGATools._ORIGIN_UL:
  3763. x_start = 0;
  3764. x_step = 1;
  3765. x_end = header.width;
  3766. y_start = 0;
  3767. y_step = 1;
  3768. y_end = header.height;
  3769. break;
  3770. case TGATools._ORIGIN_BL:
  3771. x_start = 0;
  3772. x_step = 1;
  3773. x_end = header.width;
  3774. y_start = header.height - 1;
  3775. y_step = -1;
  3776. y_end = -1;
  3777. break;
  3778. case TGATools._ORIGIN_UR:
  3779. x_start = header.width - 1;
  3780. x_step = -1;
  3781. x_end = -1;
  3782. y_start = 0;
  3783. y_step = 1;
  3784. y_end = header.height;
  3785. break;
  3786. case TGATools._ORIGIN_BR:
  3787. x_start = header.width - 1;
  3788. x_step = -1;
  3789. x_end = -1;
  3790. y_start = header.height - 1;
  3791. y_step = -1;
  3792. y_end = -1;
  3793. break;
  3794. }
  3795. // Load the specify method
  3796. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3797. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3798. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3799. };
  3800. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3801. var image = pixel_data, colormap = palettes;
  3802. var width = header.width, height = header.height;
  3803. var color, i = 0, x, y;
  3804. var imageData = new Uint8Array(width * height * 4);
  3805. for (y = y_start; y !== y_end; y += y_step) {
  3806. for (x = x_start; x !== x_end; x += x_step, i++) {
  3807. color = image[i];
  3808. imageData[(x + width * y) * 4 + 3] = 255;
  3809. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3810. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3811. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3812. }
  3813. }
  3814. return imageData;
  3815. };
  3816. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3817. var image = pixel_data;
  3818. var width = header.width, height = header.height;
  3819. var color, i = 0, x, y;
  3820. var imageData = new Uint8Array(width * height * 4);
  3821. for (y = y_start; y !== y_end; y += y_step) {
  3822. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3823. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3824. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3825. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3826. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3827. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3828. }
  3829. }
  3830. return imageData;
  3831. };
  3832. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3833. var image = pixel_data;
  3834. var width = header.width, height = header.height;
  3835. var i = 0, x, y;
  3836. var imageData = new Uint8Array(width * height * 4);
  3837. for (y = y_start; y !== y_end; y += y_step) {
  3838. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3839. imageData[(x + width * y) * 4 + 3] = 255;
  3840. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3841. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3842. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3843. }
  3844. }
  3845. return imageData;
  3846. };
  3847. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3848. var image = pixel_data;
  3849. var width = header.width, height = header.height;
  3850. var i = 0, x, y;
  3851. var imageData = new Uint8Array(width * height * 4);
  3852. for (y = y_start; y !== y_end; y += y_step) {
  3853. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3854. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3855. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3856. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3857. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3858. }
  3859. }
  3860. return imageData;
  3861. };
  3862. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3863. var image = pixel_data;
  3864. var width = header.width, height = header.height;
  3865. var color, i = 0, x, y;
  3866. var imageData = new Uint8Array(width * height * 4);
  3867. for (y = y_start; y !== y_end; y += y_step) {
  3868. for (x = x_start; x !== x_end; x += x_step, i++) {
  3869. color = image[i];
  3870. imageData[(x + width * y) * 4 + 0] = color;
  3871. imageData[(x + width * y) * 4 + 1] = color;
  3872. imageData[(x + width * y) * 4 + 2] = color;
  3873. imageData[(x + width * y) * 4 + 3] = 255;
  3874. }
  3875. }
  3876. return imageData;
  3877. };
  3878. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3879. var image = pixel_data;
  3880. var width = header.width, height = header.height;
  3881. var i = 0, x, y;
  3882. var imageData = new Uint8Array(width * height * 4);
  3883. for (y = y_start; y !== y_end; y += y_step) {
  3884. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3885. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3886. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3887. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3888. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3889. }
  3890. }
  3891. return imageData;
  3892. };
  3893. TGATools._TYPE_NO_DATA = 0;
  3894. TGATools._TYPE_INDEXED = 1;
  3895. TGATools._TYPE_RGB = 2;
  3896. TGATools._TYPE_GREY = 3;
  3897. TGATools._TYPE_RLE_INDEXED = 9;
  3898. TGATools._TYPE_RLE_RGB = 10;
  3899. TGATools._TYPE_RLE_GREY = 11;
  3900. TGATools._ORIGIN_MASK = 0x30;
  3901. TGATools._ORIGIN_SHIFT = 0x04;
  3902. TGATools._ORIGIN_BL = 0x00;
  3903. TGATools._ORIGIN_BR = 0x01;
  3904. TGATools._ORIGIN_UL = 0x02;
  3905. TGATools._ORIGIN_UR = 0x03;
  3906. return TGATools;
  3907. })();
  3908. Internals.TGATools = TGATools;
  3909. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3910. })(BABYLON || (BABYLON = {}));
  3911. var BABYLON;
  3912. (function (BABYLON) {
  3913. var Internals;
  3914. (function (Internals) {
  3915. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3916. // All values and structures referenced from:
  3917. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3918. var DDS_MAGIC = 0x20534444;
  3919. 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;
  3920. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3921. 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;
  3922. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3923. function FourCCToInt32(value) {
  3924. return value.charCodeAt(0) +
  3925. (value.charCodeAt(1) << 8) +
  3926. (value.charCodeAt(2) << 16) +
  3927. (value.charCodeAt(3) << 24);
  3928. }
  3929. function Int32ToFourCC(value) {
  3930. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3931. }
  3932. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3933. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3934. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3935. var headerLengthInt = 31; // The header length in 32 bit ints
  3936. // Offsets into the header array
  3937. var off_magic = 0;
  3938. var off_size = 1;
  3939. var off_flags = 2;
  3940. var off_height = 3;
  3941. var off_width = 4;
  3942. var off_mipmapCount = 7;
  3943. var off_pfFlags = 20;
  3944. var off_pfFourCC = 21;
  3945. var off_RGBbpp = 22;
  3946. var off_RMask = 23;
  3947. var off_GMask = 24;
  3948. var off_BMask = 25;
  3949. var off_AMask = 26;
  3950. var off_caps1 = 27;
  3951. var off_caps2 = 28;
  3952. ;
  3953. var DDSTools = (function () {
  3954. function DDSTools() {
  3955. }
  3956. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3957. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3958. var mipmapCount = 1;
  3959. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3960. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3961. }
  3962. return {
  3963. width: header[off_width],
  3964. height: header[off_height],
  3965. mipmapCount: mipmapCount,
  3966. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3967. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3968. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3969. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3970. };
  3971. };
  3972. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3973. var byteArray = new Uint8Array(dataLength);
  3974. var srcData = new Uint8Array(arrayBuffer);
  3975. var index = 0;
  3976. for (var y = height - 1; y >= 0; y--) {
  3977. for (var x = 0; x < width; x++) {
  3978. var srcPos = dataOffset + (x + y * width) * 4;
  3979. byteArray[index + 2] = srcData[srcPos];
  3980. byteArray[index + 1] = srcData[srcPos + 1];
  3981. byteArray[index] = srcData[srcPos + 2];
  3982. byteArray[index + 3] = srcData[srcPos + 3];
  3983. index += 4;
  3984. }
  3985. }
  3986. return byteArray;
  3987. };
  3988. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3989. var byteArray = new Uint8Array(dataLength);
  3990. var srcData = new Uint8Array(arrayBuffer);
  3991. var index = 0;
  3992. for (var y = height - 1; y >= 0; y--) {
  3993. for (var x = 0; x < width; x++) {
  3994. var srcPos = dataOffset + (x + y * width) * 3;
  3995. byteArray[index + 2] = srcData[srcPos];
  3996. byteArray[index + 1] = srcData[srcPos + 1];
  3997. byteArray[index] = srcData[srcPos + 2];
  3998. index += 3;
  3999. }
  4000. }
  4001. return byteArray;
  4002. };
  4003. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  4004. var byteArray = new Uint8Array(dataLength);
  4005. var srcData = new Uint8Array(arrayBuffer);
  4006. var index = 0;
  4007. for (var y = height - 1; y >= 0; y--) {
  4008. for (var x = 0; x < width; x++) {
  4009. var srcPos = dataOffset + (x + y * width);
  4010. byteArray[index] = srcData[srcPos];
  4011. index++;
  4012. }
  4013. }
  4014. return byteArray;
  4015. };
  4016. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  4017. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  4018. if (header[off_magic] != DDS_MAGIC) {
  4019. BABYLON.Tools.Error("Invalid magic number in DDS header");
  4020. return;
  4021. }
  4022. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  4023. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  4024. return;
  4025. }
  4026. if (info.isFourCC) {
  4027. fourCC = header[off_pfFourCC];
  4028. switch (fourCC) {
  4029. case FOURCC_DXT1:
  4030. blockBytes = 8;
  4031. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  4032. break;
  4033. case FOURCC_DXT3:
  4034. blockBytes = 16;
  4035. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  4036. break;
  4037. case FOURCC_DXT5:
  4038. blockBytes = 16;
  4039. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4040. break;
  4041. default:
  4042. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4043. return;
  4044. }
  4045. }
  4046. mipmapCount = 1;
  4047. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4048. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4049. }
  4050. var bpp = header[off_RGBbpp];
  4051. for (var face = 0; face < faces; face++) {
  4052. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4053. width = header[off_width];
  4054. height = header[off_height];
  4055. dataOffset = header[off_size] + 4;
  4056. for (i = 0; i < mipmapCount; ++i) {
  4057. if (info.isRGB) {
  4058. if (bpp === 24) {
  4059. dataLength = width * height * 3;
  4060. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4061. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4062. }
  4063. else {
  4064. dataLength = width * height * 4;
  4065. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4066. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4067. }
  4068. }
  4069. else if (info.isLuminance) {
  4070. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4071. var unpaddedRowSize = width;
  4072. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4073. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4074. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4075. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4076. }
  4077. else {
  4078. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4079. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4080. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4081. }
  4082. dataOffset += dataLength;
  4083. width *= 0.5;
  4084. height *= 0.5;
  4085. width = Math.max(1.0, width);
  4086. height = Math.max(1.0, height);
  4087. }
  4088. }
  4089. };
  4090. return DDSTools;
  4091. })();
  4092. Internals.DDSTools = DDSTools;
  4093. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4094. })(BABYLON || (BABYLON = {}));
  4095. var BABYLON;
  4096. (function (BABYLON) {
  4097. var SmartArray = (function () {
  4098. function SmartArray(capacity) {
  4099. this.length = 0;
  4100. this._duplicateId = 0;
  4101. this.data = new Array(capacity);
  4102. this._id = SmartArray._GlobalId++;
  4103. }
  4104. SmartArray.prototype.push = function (value) {
  4105. this.data[this.length++] = value;
  4106. if (this.length > this.data.length) {
  4107. this.data.length *= 2;
  4108. }
  4109. if (!value.__smartArrayFlags) {
  4110. value.__smartArrayFlags = {};
  4111. }
  4112. value.__smartArrayFlags[this._id] = this._duplicateId;
  4113. };
  4114. SmartArray.prototype.pushNoDuplicate = function (value) {
  4115. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4116. return;
  4117. }
  4118. this.push(value);
  4119. };
  4120. SmartArray.prototype.sort = function (compareFn) {
  4121. this.data.sort(compareFn);
  4122. };
  4123. SmartArray.prototype.reset = function () {
  4124. this.length = 0;
  4125. this._duplicateId++;
  4126. };
  4127. SmartArray.prototype.concat = function (array) {
  4128. if (array.length === 0) {
  4129. return;
  4130. }
  4131. if (this.length + array.length > this.data.length) {
  4132. this.data.length = (this.length + array.length) * 2;
  4133. }
  4134. for (var index = 0; index < array.length; index++) {
  4135. this.data[this.length++] = (array.data || array)[index];
  4136. }
  4137. };
  4138. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4139. if (array.length === 0) {
  4140. return;
  4141. }
  4142. if (this.length + array.length > this.data.length) {
  4143. this.data.length = (this.length + array.length) * 2;
  4144. }
  4145. for (var index = 0; index < array.length; index++) {
  4146. var item = (array.data || array)[index];
  4147. this.pushNoDuplicate(item);
  4148. }
  4149. };
  4150. SmartArray.prototype.indexOf = function (value) {
  4151. var position = this.data.indexOf(value);
  4152. if (position >= this.length) {
  4153. return -1;
  4154. }
  4155. return position;
  4156. };
  4157. // Statics
  4158. SmartArray._GlobalId = 0;
  4159. return SmartArray;
  4160. })();
  4161. BABYLON.SmartArray = SmartArray;
  4162. })(BABYLON || (BABYLON = {}));
  4163. var BABYLON;
  4164. (function (BABYLON) {
  4165. var SmartCollection = (function () {
  4166. function SmartCollection(capacity) {
  4167. if (capacity === void 0) { capacity = 10; }
  4168. this.count = 0;
  4169. this._initialCapacity = capacity;
  4170. this.items = {};
  4171. this._keys = new Array(this._initialCapacity);
  4172. }
  4173. SmartCollection.prototype.add = function (key, item) {
  4174. if (this.items[key] != undefined) {
  4175. return -1;
  4176. }
  4177. this.items[key] = item;
  4178. //literal keys are always strings, but we keep source type of key in _keys array
  4179. this._keys[this.count++] = key;
  4180. if (this.count > this._keys.length) {
  4181. this._keys.length *= 2;
  4182. }
  4183. return this.count;
  4184. };
  4185. SmartCollection.prototype.remove = function (key) {
  4186. if (this.items[key] == undefined) {
  4187. return -1;
  4188. }
  4189. return this.removeItemOfIndex(this.indexOf(key));
  4190. };
  4191. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4192. if (index < this.count && index > -1) {
  4193. delete this.items[this._keys[index]];
  4194. //here, shifting by hand is better optimised than .splice
  4195. while (index < this.count) {
  4196. this._keys[index] = this._keys[index + 1];
  4197. index++;
  4198. }
  4199. }
  4200. else {
  4201. return -1;
  4202. }
  4203. return --this.count;
  4204. };
  4205. SmartCollection.prototype.indexOf = function (key) {
  4206. for (var i = 0; i !== this.count; i++) {
  4207. if (this._keys[i] === key) {
  4208. return i;
  4209. }
  4210. }
  4211. return -1;
  4212. };
  4213. SmartCollection.prototype.item = function (key) {
  4214. return this.items[key];
  4215. };
  4216. SmartCollection.prototype.getAllKeys = function () {
  4217. if (this.count > 0) {
  4218. var keys = new Array(this.count);
  4219. for (var i = 0; i < this.count; i++) {
  4220. keys[i] = this._keys[i];
  4221. }
  4222. return keys;
  4223. }
  4224. else {
  4225. return undefined;
  4226. }
  4227. };
  4228. SmartCollection.prototype.getKeyByIndex = function (index) {
  4229. if (index < this.count && index > -1) {
  4230. return this._keys[index];
  4231. }
  4232. else {
  4233. return undefined;
  4234. }
  4235. };
  4236. SmartCollection.prototype.getItemByIndex = function (index) {
  4237. if (index < this.count && index > -1) {
  4238. return this.items[this._keys[index]];
  4239. }
  4240. else {
  4241. return undefined;
  4242. }
  4243. };
  4244. SmartCollection.prototype.empty = function () {
  4245. if (this.count > 0) {
  4246. this.count = 0;
  4247. this.items = {};
  4248. this._keys = new Array(this._initialCapacity);
  4249. }
  4250. };
  4251. SmartCollection.prototype.forEach = function (block) {
  4252. var key;
  4253. for (key in this.items) {
  4254. if (this.items.hasOwnProperty(key)) {
  4255. block(this.items[key]);
  4256. }
  4257. }
  4258. };
  4259. return SmartCollection;
  4260. })();
  4261. BABYLON.SmartCollection = SmartCollection;
  4262. })(BABYLON || (BABYLON = {}));
  4263. var BABYLON;
  4264. (function (BABYLON) {
  4265. // Screenshots
  4266. var screenshotCanvas;
  4267. var cloneValue = function (source, destinationObject) {
  4268. if (!source)
  4269. return null;
  4270. if (source instanceof BABYLON.Mesh) {
  4271. return null;
  4272. }
  4273. if (source instanceof BABYLON.SubMesh) {
  4274. return source.clone(destinationObject);
  4275. }
  4276. else if (source.clone) {
  4277. return source.clone();
  4278. }
  4279. return null;
  4280. };
  4281. var Tools = (function () {
  4282. function Tools() {
  4283. }
  4284. Tools.ToHex = function (i) {
  4285. var str = i.toString(16);
  4286. if (i <= 15) {
  4287. return ("0" + str).toUpperCase();
  4288. }
  4289. return str.toUpperCase();
  4290. };
  4291. Tools.SetImmediate = function (action) {
  4292. if (window.setImmediate) {
  4293. window.setImmediate(action);
  4294. }
  4295. else {
  4296. setTimeout(action, 1);
  4297. }
  4298. };
  4299. Tools.IsExponantOfTwo = function (value) {
  4300. var count = 1;
  4301. do {
  4302. count *= 2;
  4303. } while (count < value);
  4304. return count === value;
  4305. };
  4306. Tools.GetExponantOfTwo = function (value, max) {
  4307. var count = 1;
  4308. do {
  4309. count *= 2;
  4310. } while (count < value);
  4311. if (count > max)
  4312. count = max;
  4313. return count;
  4314. };
  4315. Tools.GetFilename = function (path) {
  4316. var index = path.lastIndexOf("/");
  4317. if (index < 0)
  4318. return path;
  4319. return path.substring(index + 1);
  4320. };
  4321. Tools.GetDOMTextContent = function (element) {
  4322. var result = "";
  4323. var child = element.firstChild;
  4324. while (child) {
  4325. if (child.nodeType === 3) {
  4326. result += child.textContent;
  4327. }
  4328. child = child.nextSibling;
  4329. }
  4330. return result;
  4331. };
  4332. Tools.ToDegrees = function (angle) {
  4333. return angle * 180 / Math.PI;
  4334. };
  4335. Tools.ToRadians = function (angle) {
  4336. return angle * Math.PI / 180;
  4337. };
  4338. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4339. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4340. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4341. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4342. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4343. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4344. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4345. }
  4346. return {
  4347. minimum: minimum,
  4348. maximum: maximum
  4349. };
  4350. };
  4351. Tools.ExtractMinAndMax = function (positions, start, count) {
  4352. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4353. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4354. for (var index = start; index < start + count; index++) {
  4355. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4356. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4357. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4358. }
  4359. return {
  4360. minimum: minimum,
  4361. maximum: maximum
  4362. };
  4363. };
  4364. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4365. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4366. return undefined;
  4367. return Array.isArray(obj) ? obj : [obj];
  4368. };
  4369. // Misc.
  4370. Tools.GetPointerPrefix = function () {
  4371. var eventPrefix = "pointer";
  4372. // Check if hand.js is referenced or if the browser natively supports pointer events
  4373. if (!navigator.pointerEnabled) {
  4374. eventPrefix = "mouse";
  4375. }
  4376. return eventPrefix;
  4377. };
  4378. Tools.QueueNewFrame = function (func) {
  4379. if (window.requestAnimationFrame)
  4380. window.requestAnimationFrame(func);
  4381. else if (window.msRequestAnimationFrame)
  4382. window.msRequestAnimationFrame(func);
  4383. else if (window.webkitRequestAnimationFrame)
  4384. window.webkitRequestAnimationFrame(func);
  4385. else if (window.mozRequestAnimationFrame)
  4386. window.mozRequestAnimationFrame(func);
  4387. else if (window.oRequestAnimationFrame)
  4388. window.oRequestAnimationFrame(func);
  4389. else {
  4390. window.setTimeout(func, 16);
  4391. }
  4392. };
  4393. Tools.RequestFullscreen = function (element) {
  4394. if (element.requestFullscreen)
  4395. element.requestFullscreen();
  4396. else if (element.msRequestFullscreen)
  4397. element.msRequestFullscreen();
  4398. else if (element.webkitRequestFullscreen)
  4399. element.webkitRequestFullscreen();
  4400. else if (element.mozRequestFullScreen)
  4401. element.mozRequestFullScreen();
  4402. };
  4403. Tools.ExitFullscreen = function () {
  4404. if (document.exitFullscreen) {
  4405. document.exitFullscreen();
  4406. }
  4407. else if (document.mozCancelFullScreen) {
  4408. document.mozCancelFullScreen();
  4409. }
  4410. else if (document.webkitCancelFullScreen) {
  4411. document.webkitCancelFullScreen();
  4412. }
  4413. else if (document.msCancelFullScreen) {
  4414. document.msCancelFullScreen();
  4415. }
  4416. };
  4417. // External files
  4418. Tools.CleanUrl = function (url) {
  4419. url = url.replace(/#/mg, "%23");
  4420. return url;
  4421. };
  4422. Tools.LoadImage = function (url, onload, onerror, database) {
  4423. url = Tools.CleanUrl(url);
  4424. var img = new Image();
  4425. if (url.substr(0, 5) !== "data:")
  4426. img.crossOrigin = 'anonymous';
  4427. img.onload = function () {
  4428. onload(img);
  4429. };
  4430. img.onerror = function (err) {
  4431. Tools.Error("Error while trying to load texture: " + url);
  4432. 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";
  4433. onload(img);
  4434. };
  4435. var noIndexedDB = function () {
  4436. img.src = url;
  4437. };
  4438. var loadFromIndexedDB = function () {
  4439. database.loadImageFromDB(url, img);
  4440. };
  4441. //ANY database to do!
  4442. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4443. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4444. }
  4445. else {
  4446. if (url.indexOf("file:") === -1) {
  4447. noIndexedDB();
  4448. }
  4449. else {
  4450. try {
  4451. var textureName = url.substring(5);
  4452. var blobURL;
  4453. try {
  4454. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4455. }
  4456. catch (ex) {
  4457. // Chrome doesn't support oneTimeOnly parameter
  4458. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4459. }
  4460. img.src = blobURL;
  4461. }
  4462. catch (e) {
  4463. img.src = null;
  4464. }
  4465. }
  4466. }
  4467. return img;
  4468. };
  4469. //ANY
  4470. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4471. url = Tools.CleanUrl(url);
  4472. var noIndexedDB = function () {
  4473. var request = new XMLHttpRequest();
  4474. var loadUrl = Tools.BaseUrl + url;
  4475. request.open('GET', loadUrl, true);
  4476. if (useArrayBuffer) {
  4477. request.responseType = "arraybuffer";
  4478. }
  4479. request.onprogress = progressCallBack;
  4480. request.onreadystatechange = function () {
  4481. if (request.readyState === 4) {
  4482. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4483. callback(!useArrayBuffer ? request.responseText : request.response);
  4484. }
  4485. else {
  4486. if (onError) {
  4487. onError();
  4488. }
  4489. else {
  4490. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4491. }
  4492. }
  4493. }
  4494. };
  4495. request.send(null);
  4496. };
  4497. var loadFromIndexedDB = function () {
  4498. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4499. };
  4500. if (url.indexOf("file:") !== -1) {
  4501. var fileName = url.substring(5);
  4502. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4503. }
  4504. else {
  4505. // Caching all files
  4506. if (database && database.enableSceneOffline) {
  4507. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4508. }
  4509. else {
  4510. noIndexedDB();
  4511. }
  4512. }
  4513. };
  4514. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4515. var reader = new FileReader();
  4516. reader.onload = function (e) {
  4517. //target doesn't have result from ts 1.3
  4518. callback(e.target['result']);
  4519. };
  4520. reader.onprogress = progressCallback;
  4521. reader.readAsDataURL(fileToLoad);
  4522. };
  4523. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4524. var reader = new FileReader();
  4525. reader.onerror = function (e) {
  4526. Tools.Log("Error while reading file: " + fileToLoad.name);
  4527. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4528. };
  4529. reader.onload = function (e) {
  4530. //target doesn't have result from ts 1.3
  4531. callback(e.target['result']);
  4532. };
  4533. reader.onprogress = progressCallBack;
  4534. if (!useArrayBuffer) {
  4535. // Asynchronous read
  4536. reader.readAsText(fileToLoad);
  4537. }
  4538. else {
  4539. reader.readAsArrayBuffer(fileToLoad);
  4540. }
  4541. };
  4542. //returns a downloadable url to a file content.
  4543. Tools.FileAsURL = function (content) {
  4544. var fileBlob = new Blob([content]);
  4545. var url = window.URL || window.webkitURL;
  4546. var link = url.createObjectURL(fileBlob);
  4547. return link;
  4548. };
  4549. // Misc.
  4550. Tools.Clamp = function (value, min, max) {
  4551. if (min === void 0) { min = 0; }
  4552. if (max === void 0) { max = 1; }
  4553. return Math.min(max, Math.max(min, value));
  4554. };
  4555. // Returns -1 when value is a negative number and
  4556. // +1 when value is a positive number.
  4557. Tools.Sign = function (value) {
  4558. value = +value; // convert to a number
  4559. if (value === 0 || isNaN(value))
  4560. return value;
  4561. return value > 0 ? 1 : -1;
  4562. };
  4563. Tools.Format = function (value, decimals) {
  4564. if (decimals === void 0) { decimals = 2; }
  4565. return value.toFixed(decimals);
  4566. };
  4567. Tools.CheckExtends = function (v, min, max) {
  4568. if (v.x < min.x)
  4569. min.x = v.x;
  4570. if (v.y < min.y)
  4571. min.y = v.y;
  4572. if (v.z < min.z)
  4573. min.z = v.z;
  4574. if (v.x > max.x)
  4575. max.x = v.x;
  4576. if (v.y > max.y)
  4577. max.y = v.y;
  4578. if (v.z > max.z)
  4579. max.z = v.z;
  4580. };
  4581. Tools.WithinEpsilon = function (a, b, epsilon) {
  4582. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4583. var num = a - b;
  4584. return -epsilon <= num && num <= epsilon;
  4585. };
  4586. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4587. for (var prop in source) {
  4588. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4589. continue;
  4590. }
  4591. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4592. continue;
  4593. }
  4594. var sourceValue = source[prop];
  4595. var typeOfSourceValue = typeof sourceValue;
  4596. if (typeOfSourceValue === "function") {
  4597. continue;
  4598. }
  4599. if (typeOfSourceValue === "object") {
  4600. if (sourceValue instanceof Array) {
  4601. destination[prop] = [];
  4602. if (sourceValue.length > 0) {
  4603. if (typeof sourceValue[0] == "object") {
  4604. for (var index = 0; index < sourceValue.length; index++) {
  4605. var clonedValue = cloneValue(sourceValue[index], destination);
  4606. if (destination[prop].indexOf(clonedValue) === -1) {
  4607. destination[prop].push(clonedValue);
  4608. }
  4609. }
  4610. }
  4611. else {
  4612. destination[prop] = sourceValue.slice(0);
  4613. }
  4614. }
  4615. }
  4616. else {
  4617. destination[prop] = cloneValue(sourceValue, destination);
  4618. }
  4619. }
  4620. else {
  4621. destination[prop] = sourceValue;
  4622. }
  4623. }
  4624. };
  4625. Tools.IsEmpty = function (obj) {
  4626. for (var i in obj) {
  4627. return false;
  4628. }
  4629. return true;
  4630. };
  4631. Tools.RegisterTopRootEvents = function (events) {
  4632. for (var index = 0; index < events.length; index++) {
  4633. var event = events[index];
  4634. window.addEventListener(event.name, event.handler, false);
  4635. try {
  4636. if (window.parent) {
  4637. window.parent.addEventListener(event.name, event.handler, false);
  4638. }
  4639. }
  4640. catch (e) {
  4641. }
  4642. }
  4643. };
  4644. Tools.UnregisterTopRootEvents = function (events) {
  4645. for (var index = 0; index < events.length; index++) {
  4646. var event = events[index];
  4647. window.removeEventListener(event.name, event.handler);
  4648. try {
  4649. if (window.parent) {
  4650. window.parent.removeEventListener(event.name, event.handler);
  4651. }
  4652. }
  4653. catch (e) {
  4654. }
  4655. }
  4656. };
  4657. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4658. // Read the contents of the framebuffer
  4659. var numberOfChannelsByLine = width * 4;
  4660. var halfHeight = height / 2;
  4661. //Reading datas from WebGL
  4662. var data = engine.readPixels(0, 0, width, height);
  4663. //To flip image on Y axis.
  4664. for (var i = 0; i < halfHeight; i++) {
  4665. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4666. var currentCell = j + i * numberOfChannelsByLine;
  4667. var targetLine = height - i - 1;
  4668. var targetCell = j + targetLine * numberOfChannelsByLine;
  4669. var temp = data[currentCell];
  4670. data[currentCell] = data[targetCell];
  4671. data[targetCell] = temp;
  4672. }
  4673. }
  4674. // Create a 2D canvas to store the result
  4675. if (!screenshotCanvas) {
  4676. screenshotCanvas = document.createElement('canvas');
  4677. }
  4678. screenshotCanvas.width = width;
  4679. screenshotCanvas.height = height;
  4680. var context = screenshotCanvas.getContext('2d');
  4681. // Copy the pixels to a 2D canvas
  4682. var imageData = context.createImageData(width, height);
  4683. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4684. var castData = imageData.data;
  4685. castData.set(data);
  4686. context.putImageData(imageData, 0, 0);
  4687. var base64Image = screenshotCanvas.toDataURL();
  4688. if (successCallback) {
  4689. successCallback(base64Image);
  4690. }
  4691. else {
  4692. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4693. if (("download" in document.createElement("a"))) {
  4694. var a = window.document.createElement("a");
  4695. a.href = base64Image;
  4696. var date = new Date();
  4697. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4698. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4699. window.document.body.appendChild(a);
  4700. a.addEventListener("click", function () {
  4701. a.parentElement.removeChild(a);
  4702. });
  4703. a.click();
  4704. }
  4705. else {
  4706. var newWindow = window.open("");
  4707. var img = newWindow.document.createElement("img");
  4708. img.src = base64Image;
  4709. newWindow.document.body.appendChild(img);
  4710. }
  4711. }
  4712. };
  4713. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4714. var width;
  4715. var height;
  4716. //If a precision value is specified
  4717. if (size.precision) {
  4718. width = Math.round(engine.getRenderWidth() * size.precision);
  4719. height = Math.round(width / engine.getAspectRatio(camera));
  4720. size = { width: width, height: height };
  4721. }
  4722. else if (size.width && size.height) {
  4723. width = size.width;
  4724. height = size.height;
  4725. }
  4726. else if (size.width && !size.height) {
  4727. width = size.width;
  4728. height = Math.round(width / engine.getAspectRatio(camera));
  4729. size = { width: width, height: height };
  4730. }
  4731. else if (size.height && !size.width) {
  4732. height = size.height;
  4733. width = Math.round(height * engine.getAspectRatio(camera));
  4734. size = { width: width, height: height };
  4735. }
  4736. else if (!isNaN(size)) {
  4737. height = size;
  4738. width = size;
  4739. }
  4740. else {
  4741. Tools.Error("Invalid 'size' parameter !");
  4742. return;
  4743. }
  4744. var scene = camera.getScene();
  4745. var previousCamera = null;
  4746. if (scene.activeCamera !== camera) {
  4747. previousCamera = scene.activeCamera;
  4748. scene.activeCamera = camera;
  4749. }
  4750. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4751. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4752. texture.renderList = scene.meshes;
  4753. texture.onAfterRender = function () {
  4754. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4755. };
  4756. scene.incrementRenderId();
  4757. texture.render(true);
  4758. texture.dispose();
  4759. if (previousCamera) {
  4760. scene.activeCamera = previousCamera;
  4761. }
  4762. };
  4763. // XHR response validator for local file scenario
  4764. Tools.ValidateXHRData = function (xhr, dataType) {
  4765. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4766. if (dataType === void 0) { dataType = 7; }
  4767. try {
  4768. if (dataType & 1) {
  4769. if (xhr.responseText && xhr.responseText.length > 0) {
  4770. return true;
  4771. }
  4772. else if (dataType === 1) {
  4773. return false;
  4774. }
  4775. }
  4776. if (dataType & 2) {
  4777. // Check header width and height since there is no "TGA" magic number
  4778. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4779. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4780. return true;
  4781. }
  4782. else if (dataType === 2) {
  4783. return false;
  4784. }
  4785. }
  4786. if (dataType & 4) {
  4787. // Check for the "DDS" magic number
  4788. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4789. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4790. return true;
  4791. }
  4792. else {
  4793. return false;
  4794. }
  4795. }
  4796. }
  4797. catch (e) {
  4798. }
  4799. return false;
  4800. };
  4801. Object.defineProperty(Tools, "NoneLogLevel", {
  4802. get: function () {
  4803. return Tools._NoneLogLevel;
  4804. },
  4805. enumerable: true,
  4806. configurable: true
  4807. });
  4808. Object.defineProperty(Tools, "MessageLogLevel", {
  4809. get: function () {
  4810. return Tools._MessageLogLevel;
  4811. },
  4812. enumerable: true,
  4813. configurable: true
  4814. });
  4815. Object.defineProperty(Tools, "WarningLogLevel", {
  4816. get: function () {
  4817. return Tools._WarningLogLevel;
  4818. },
  4819. enumerable: true,
  4820. configurable: true
  4821. });
  4822. Object.defineProperty(Tools, "ErrorLogLevel", {
  4823. get: function () {
  4824. return Tools._ErrorLogLevel;
  4825. },
  4826. enumerable: true,
  4827. configurable: true
  4828. });
  4829. Object.defineProperty(Tools, "AllLogLevel", {
  4830. get: function () {
  4831. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4832. },
  4833. enumerable: true,
  4834. configurable: true
  4835. });
  4836. Tools._AddLogEntry = function (entry) {
  4837. Tools._LogCache = entry + Tools._LogCache;
  4838. if (Tools.OnNewCacheEntry) {
  4839. Tools.OnNewCacheEntry(entry);
  4840. }
  4841. };
  4842. Tools._FormatMessage = function (message) {
  4843. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4844. var date = new Date();
  4845. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4846. };
  4847. Tools._LogDisabled = function (message) {
  4848. // nothing to do
  4849. };
  4850. Tools._LogEnabled = function (message) {
  4851. var formattedMessage = Tools._FormatMessage(message);
  4852. console.log("BJS - " + formattedMessage);
  4853. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4854. Tools._AddLogEntry(entry);
  4855. };
  4856. Tools._WarnDisabled = function (message) {
  4857. // nothing to do
  4858. };
  4859. Tools._WarnEnabled = function (message) {
  4860. var formattedMessage = Tools._FormatMessage(message);
  4861. console.warn("BJS - " + formattedMessage);
  4862. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4863. Tools._AddLogEntry(entry);
  4864. };
  4865. Tools._ErrorDisabled = function (message) {
  4866. // nothing to do
  4867. };
  4868. Tools._ErrorEnabled = function (message) {
  4869. Tools.errorsCount++;
  4870. var formattedMessage = Tools._FormatMessage(message);
  4871. console.error("BJS - " + formattedMessage);
  4872. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4873. Tools._AddLogEntry(entry);
  4874. };
  4875. Object.defineProperty(Tools, "LogCache", {
  4876. get: function () {
  4877. return Tools._LogCache;
  4878. },
  4879. enumerable: true,
  4880. configurable: true
  4881. });
  4882. Tools.ClearLogCache = function () {
  4883. Tools._LogCache = "";
  4884. Tools.errorsCount = 0;
  4885. };
  4886. Object.defineProperty(Tools, "LogLevels", {
  4887. set: function (level) {
  4888. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4889. Tools.Log = Tools._LogEnabled;
  4890. }
  4891. else {
  4892. Tools.Log = Tools._LogDisabled;
  4893. }
  4894. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4895. Tools.Warn = Tools._WarnEnabled;
  4896. }
  4897. else {
  4898. Tools.Warn = Tools._WarnDisabled;
  4899. }
  4900. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4901. Tools.Error = Tools._ErrorEnabled;
  4902. }
  4903. else {
  4904. Tools.Error = Tools._ErrorDisabled;
  4905. }
  4906. },
  4907. enumerable: true,
  4908. configurable: true
  4909. });
  4910. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4911. get: function () {
  4912. return Tools._PerformanceNoneLogLevel;
  4913. },
  4914. enumerable: true,
  4915. configurable: true
  4916. });
  4917. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4918. get: function () {
  4919. return Tools._PerformanceUserMarkLogLevel;
  4920. },
  4921. enumerable: true,
  4922. configurable: true
  4923. });
  4924. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4925. get: function () {
  4926. return Tools._PerformanceConsoleLogLevel;
  4927. },
  4928. enumerable: true,
  4929. configurable: true
  4930. });
  4931. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4932. set: function (level) {
  4933. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4934. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4935. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4936. return;
  4937. }
  4938. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4939. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4940. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4941. return;
  4942. }
  4943. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4944. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4950. };
  4951. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4952. };
  4953. Tools._StartUserMark = function (counterName, condition) {
  4954. if (condition === void 0) { condition = true; }
  4955. if (!condition || !Tools._performance.mark) {
  4956. return;
  4957. }
  4958. Tools._performance.mark(counterName + "-Begin");
  4959. };
  4960. Tools._EndUserMark = function (counterName, condition) {
  4961. if (condition === void 0) { condition = true; }
  4962. if (!condition || !Tools._performance.mark) {
  4963. return;
  4964. }
  4965. Tools._performance.mark(counterName + "-End");
  4966. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4967. };
  4968. Tools._StartPerformanceConsole = function (counterName, condition) {
  4969. if (condition === void 0) { condition = true; }
  4970. if (!condition) {
  4971. return;
  4972. }
  4973. Tools._StartUserMark(counterName, condition);
  4974. if (console.time) {
  4975. console.time(counterName);
  4976. }
  4977. };
  4978. Tools._EndPerformanceConsole = function (counterName, condition) {
  4979. if (condition === void 0) { condition = true; }
  4980. if (!condition) {
  4981. return;
  4982. }
  4983. Tools._EndUserMark(counterName, condition);
  4984. if (console.time) {
  4985. console.timeEnd(counterName);
  4986. }
  4987. };
  4988. Object.defineProperty(Tools, "Now", {
  4989. get: function () {
  4990. if (window.performance && window.performance.now) {
  4991. return window.performance.now();
  4992. }
  4993. return new Date().getTime();
  4994. },
  4995. enumerable: true,
  4996. configurable: true
  4997. });
  4998. // Deprecated
  4999. Tools.GetFps = function () {
  5000. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  5001. return 0;
  5002. };
  5003. Tools.BaseUrl = "";
  5004. // Logs
  5005. Tools._NoneLogLevel = 0;
  5006. Tools._MessageLogLevel = 1;
  5007. Tools._WarningLogLevel = 2;
  5008. Tools._ErrorLogLevel = 4;
  5009. Tools._LogCache = "";
  5010. Tools.errorsCount = 0;
  5011. Tools.Log = Tools._LogEnabled;
  5012. Tools.Warn = Tools._WarnEnabled;
  5013. Tools.Error = Tools._ErrorEnabled;
  5014. // Performances
  5015. Tools._PerformanceNoneLogLevel = 0;
  5016. Tools._PerformanceUserMarkLogLevel = 1;
  5017. Tools._PerformanceConsoleLogLevel = 2;
  5018. Tools._performance = window.performance;
  5019. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5020. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5021. return Tools;
  5022. })();
  5023. BABYLON.Tools = Tools;
  5024. /**
  5025. * An implementation of a loop for asynchronous functions.
  5026. */
  5027. var AsyncLoop = (function () {
  5028. /**
  5029. * Constroctor.
  5030. * @param iterations the number of iterations.
  5031. * @param _fn the function to run each iteration
  5032. * @param _successCallback the callback that will be called upon succesful execution
  5033. * @param offset starting offset.
  5034. */
  5035. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5036. if (offset === void 0) { offset = 0; }
  5037. this.iterations = iterations;
  5038. this._fn = _fn;
  5039. this._successCallback = _successCallback;
  5040. this.index = offset - 1;
  5041. this._done = false;
  5042. }
  5043. /**
  5044. * Execute the next iteration. Must be called after the last iteration was finished.
  5045. */
  5046. AsyncLoop.prototype.executeNext = function () {
  5047. if (!this._done) {
  5048. if (this.index + 1 < this.iterations) {
  5049. ++this.index;
  5050. this._fn(this);
  5051. }
  5052. else {
  5053. this.breakLoop();
  5054. }
  5055. }
  5056. };
  5057. /**
  5058. * Break the loop and run the success callback.
  5059. */
  5060. AsyncLoop.prototype.breakLoop = function () {
  5061. this._done = true;
  5062. this._successCallback();
  5063. };
  5064. /**
  5065. * Helper function
  5066. */
  5067. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5068. if (offset === void 0) { offset = 0; }
  5069. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5070. loop.executeNext();
  5071. return loop;
  5072. };
  5073. /**
  5074. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5075. * @param iterations total number of iterations
  5076. * @param syncedIterations number of synchronous iterations in each async iteration.
  5077. * @param fn the function to call each iteration.
  5078. * @param callback a success call back that will be called when iterating stops.
  5079. * @param breakFunction a break condition (optional)
  5080. * @param timeout timeout settings for the setTimeout function. default - 0.
  5081. * @constructor
  5082. */
  5083. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5084. if (timeout === void 0) { timeout = 0; }
  5085. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5086. if (breakFunction && breakFunction())
  5087. loop.breakLoop();
  5088. else {
  5089. setTimeout(function () {
  5090. for (var i = 0; i < syncedIterations; ++i) {
  5091. var iteration = (loop.index * syncedIterations) + i;
  5092. if (iteration >= iterations)
  5093. break;
  5094. fn(iteration);
  5095. if (breakFunction && breakFunction()) {
  5096. loop.breakLoop();
  5097. break;
  5098. }
  5099. }
  5100. loop.executeNext();
  5101. }, timeout);
  5102. }
  5103. }, callback);
  5104. };
  5105. return AsyncLoop;
  5106. })();
  5107. BABYLON.AsyncLoop = AsyncLoop;
  5108. })(BABYLON || (BABYLON = {}));
  5109. var BABYLON;
  5110. (function (BABYLON) {
  5111. var _DepthCullingState = (function () {
  5112. function _DepthCullingState() {
  5113. this._isDepthTestDirty = false;
  5114. this._isDepthMaskDirty = false;
  5115. this._isDepthFuncDirty = false;
  5116. this._isCullFaceDirty = false;
  5117. this._isCullDirty = false;
  5118. this._isZOffsetDirty = false;
  5119. }
  5120. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5121. get: function () {
  5122. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5123. },
  5124. enumerable: true,
  5125. configurable: true
  5126. });
  5127. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5128. get: function () {
  5129. return this._zOffset;
  5130. },
  5131. set: function (value) {
  5132. if (this._zOffset === value) {
  5133. return;
  5134. }
  5135. this._zOffset = value;
  5136. this._isZOffsetDirty = true;
  5137. },
  5138. enumerable: true,
  5139. configurable: true
  5140. });
  5141. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5142. get: function () {
  5143. return this._cullFace;
  5144. },
  5145. set: function (value) {
  5146. if (this._cullFace === value) {
  5147. return;
  5148. }
  5149. this._cullFace = value;
  5150. this._isCullFaceDirty = true;
  5151. },
  5152. enumerable: true,
  5153. configurable: true
  5154. });
  5155. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5156. get: function () {
  5157. return this._cull;
  5158. },
  5159. set: function (value) {
  5160. if (this._cull === value) {
  5161. return;
  5162. }
  5163. this._cull = value;
  5164. this._isCullDirty = true;
  5165. },
  5166. enumerable: true,
  5167. configurable: true
  5168. });
  5169. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5170. get: function () {
  5171. return this._depthFunc;
  5172. },
  5173. set: function (value) {
  5174. if (this._depthFunc === value) {
  5175. return;
  5176. }
  5177. this._depthFunc = value;
  5178. this._isDepthFuncDirty = true;
  5179. },
  5180. enumerable: true,
  5181. configurable: true
  5182. });
  5183. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5184. get: function () {
  5185. return this._depthMask;
  5186. },
  5187. set: function (value) {
  5188. if (this._depthMask === value) {
  5189. return;
  5190. }
  5191. this._depthMask = value;
  5192. this._isDepthMaskDirty = true;
  5193. },
  5194. enumerable: true,
  5195. configurable: true
  5196. });
  5197. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5198. get: function () {
  5199. return this._depthTest;
  5200. },
  5201. set: function (value) {
  5202. if (this._depthTest === value) {
  5203. return;
  5204. }
  5205. this._depthTest = value;
  5206. this._isDepthTestDirty = true;
  5207. },
  5208. enumerable: true,
  5209. configurable: true
  5210. });
  5211. _DepthCullingState.prototype.reset = function () {
  5212. this._depthMask = true;
  5213. this._depthTest = true;
  5214. this._depthFunc = null;
  5215. this._cull = null;
  5216. this._cullFace = null;
  5217. this._zOffset = 0;
  5218. this._isDepthTestDirty = true;
  5219. this._isDepthMaskDirty = true;
  5220. this._isDepthFuncDirty = false;
  5221. this._isCullFaceDirty = false;
  5222. this._isCullDirty = false;
  5223. this._isZOffsetDirty = false;
  5224. };
  5225. _DepthCullingState.prototype.apply = function (gl) {
  5226. if (!this.isDirty) {
  5227. return;
  5228. }
  5229. // Cull
  5230. if (this._isCullDirty) {
  5231. if (this.cull) {
  5232. gl.enable(gl.CULL_FACE);
  5233. }
  5234. else {
  5235. gl.disable(gl.CULL_FACE);
  5236. }
  5237. this._isCullDirty = false;
  5238. }
  5239. // Cull face
  5240. if (this._isCullFaceDirty) {
  5241. gl.cullFace(this.cullFace);
  5242. this._isCullFaceDirty = false;
  5243. }
  5244. // Depth mask
  5245. if (this._isDepthMaskDirty) {
  5246. gl.depthMask(this.depthMask);
  5247. this._isDepthMaskDirty = false;
  5248. }
  5249. // Depth test
  5250. if (this._isDepthTestDirty) {
  5251. if (this.depthTest) {
  5252. gl.enable(gl.DEPTH_TEST);
  5253. }
  5254. else {
  5255. gl.disable(gl.DEPTH_TEST);
  5256. }
  5257. this._isDepthTestDirty = false;
  5258. }
  5259. // Depth func
  5260. if (this._isDepthFuncDirty) {
  5261. gl.depthFunc(this.depthFunc);
  5262. this._isDepthFuncDirty = false;
  5263. }
  5264. // zOffset
  5265. if (this._isZOffsetDirty) {
  5266. if (this.zOffset) {
  5267. gl.enable(gl.POLYGON_OFFSET_FILL);
  5268. gl.polygonOffset(this.zOffset, 0);
  5269. }
  5270. else {
  5271. gl.disable(gl.POLYGON_OFFSET_FILL);
  5272. }
  5273. this._isZOffsetDirty = false;
  5274. }
  5275. };
  5276. return _DepthCullingState;
  5277. })();
  5278. BABYLON._DepthCullingState = _DepthCullingState;
  5279. var _AlphaState = (function () {
  5280. function _AlphaState() {
  5281. this._isAlphaBlendDirty = false;
  5282. this._isBlendFunctionParametersDirty = false;
  5283. this._alphaBlend = false;
  5284. this._blendFunctionParameters = new Array(4);
  5285. }
  5286. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5287. get: function () {
  5288. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5289. },
  5290. enumerable: true,
  5291. configurable: true
  5292. });
  5293. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5294. get: function () {
  5295. return this._alphaBlend;
  5296. },
  5297. set: function (value) {
  5298. if (this._alphaBlend === value) {
  5299. return;
  5300. }
  5301. this._alphaBlend = value;
  5302. this._isAlphaBlendDirty = true;
  5303. },
  5304. enumerable: true,
  5305. configurable: true
  5306. });
  5307. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5308. if (this._blendFunctionParameters[0] === value0 &&
  5309. this._blendFunctionParameters[1] === value1 &&
  5310. this._blendFunctionParameters[2] === value2 &&
  5311. this._blendFunctionParameters[3] === value3) {
  5312. return;
  5313. }
  5314. this._blendFunctionParameters[0] = value0;
  5315. this._blendFunctionParameters[1] = value1;
  5316. this._blendFunctionParameters[2] = value2;
  5317. this._blendFunctionParameters[3] = value3;
  5318. this._isBlendFunctionParametersDirty = true;
  5319. };
  5320. _AlphaState.prototype.reset = function () {
  5321. this._alphaBlend = false;
  5322. this._blendFunctionParameters[0] = null;
  5323. this._blendFunctionParameters[1] = null;
  5324. this._blendFunctionParameters[2] = null;
  5325. this._blendFunctionParameters[3] = null;
  5326. this._isAlphaBlendDirty = true;
  5327. this._isBlendFunctionParametersDirty = false;
  5328. };
  5329. _AlphaState.prototype.apply = function (gl) {
  5330. if (!this.isDirty) {
  5331. return;
  5332. }
  5333. // Alpha blend
  5334. if (this._isAlphaBlendDirty) {
  5335. if (this._alphaBlend) {
  5336. gl.enable(gl.BLEND);
  5337. }
  5338. else {
  5339. gl.disable(gl.BLEND);
  5340. }
  5341. this._isAlphaBlendDirty = false;
  5342. }
  5343. // Alpha function
  5344. if (this._isBlendFunctionParametersDirty) {
  5345. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5346. this._isBlendFunctionParametersDirty = false;
  5347. }
  5348. };
  5349. return _AlphaState;
  5350. })();
  5351. BABYLON._AlphaState = _AlphaState;
  5352. var compileShader = function (gl, source, type, defines) {
  5353. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5354. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5355. gl.compileShader(shader);
  5356. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5357. throw new Error(gl.getShaderInfoLog(shader));
  5358. }
  5359. return shader;
  5360. };
  5361. var getWebGLTextureType = function (gl, type) {
  5362. var textureType = gl.UNSIGNED_BYTE;
  5363. if (type === Engine.TEXTURETYPE_FLOAT)
  5364. textureType = gl.FLOAT;
  5365. return textureType;
  5366. };
  5367. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5368. var magFilter = gl.NEAREST;
  5369. var minFilter = gl.NEAREST;
  5370. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5371. magFilter = gl.LINEAR;
  5372. if (generateMipMaps) {
  5373. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5374. }
  5375. else {
  5376. minFilter = gl.LINEAR;
  5377. }
  5378. }
  5379. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5380. magFilter = gl.LINEAR;
  5381. if (generateMipMaps) {
  5382. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5383. }
  5384. else {
  5385. minFilter = gl.LINEAR;
  5386. }
  5387. }
  5388. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5389. magFilter = gl.NEAREST;
  5390. if (generateMipMaps) {
  5391. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5392. }
  5393. else {
  5394. minFilter = gl.NEAREST;
  5395. }
  5396. }
  5397. return {
  5398. min: minFilter,
  5399. mag: magFilter
  5400. };
  5401. };
  5402. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5403. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5404. var engine = scene.getEngine();
  5405. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5406. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5407. gl.bindTexture(gl.TEXTURE_2D, texture);
  5408. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5409. texture._baseWidth = width;
  5410. texture._baseHeight = height;
  5411. texture._width = potWidth;
  5412. texture._height = potHeight;
  5413. texture.isReady = true;
  5414. processFunction(potWidth, potHeight);
  5415. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5418. if (!noMipmap && !isCompressed) {
  5419. gl.generateMipmap(gl.TEXTURE_2D);
  5420. }
  5421. gl.bindTexture(gl.TEXTURE_2D, null);
  5422. engine._activeTexturesCache = [];
  5423. scene._removePendingData(texture);
  5424. };
  5425. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5426. var onload = function () {
  5427. loadedImages[index] = img;
  5428. loadedImages._internalCount++;
  5429. scene._removePendingData(img);
  5430. if (loadedImages._internalCount === 6) {
  5431. onfinish(loadedImages);
  5432. }
  5433. };
  5434. var onerror = function () {
  5435. scene._removePendingData(img);
  5436. };
  5437. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5438. scene._addPendingData(img);
  5439. };
  5440. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5441. var loadedImages = [];
  5442. loadedImages._internalCount = 0;
  5443. for (var index = 0; index < 6; index++) {
  5444. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5445. }
  5446. };
  5447. var EngineCapabilities = (function () {
  5448. function EngineCapabilities() {
  5449. }
  5450. return EngineCapabilities;
  5451. })();
  5452. BABYLON.EngineCapabilities = EngineCapabilities;
  5453. /**
  5454. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5455. */
  5456. var Engine = (function () {
  5457. /**
  5458. * @constructor
  5459. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5460. * @param {boolean} [antialias] - enable antialias
  5461. * @param options - further options to be sent to the getContext function
  5462. */
  5463. function Engine(canvas, antialias, options) {
  5464. var _this = this;
  5465. // Public members
  5466. this.isFullscreen = false;
  5467. this.isPointerLock = false;
  5468. this.cullBackFaces = true;
  5469. this.renderEvenInBackground = true;
  5470. // To enable/disable IDB support and avoid XHR on .manifest
  5471. this.enableOfflineSupport = true;
  5472. this.scenes = new Array();
  5473. this._windowIsBackground = false;
  5474. this._drawCalls = 0;
  5475. this._renderingQueueLaunched = false;
  5476. this._activeRenderLoops = [];
  5477. // FPS
  5478. this.fpsRange = 60;
  5479. this.previousFramesDuration = [];
  5480. this.fps = 60;
  5481. this.deltaTime = 0;
  5482. // States
  5483. this._depthCullingState = new _DepthCullingState();
  5484. this._alphaState = new _AlphaState();
  5485. this._alphaMode = Engine.ALPHA_DISABLE;
  5486. // Cache
  5487. this._loadedTexturesCache = new Array();
  5488. this._activeTexturesCache = new Array();
  5489. this._compiledEffects = {};
  5490. this._uintIndicesCurrentlySet = false;
  5491. this._renderingCanvas = canvas;
  5492. options = options || {};
  5493. options.antialias = antialias;
  5494. if (options.preserveDrawingBuffer === undefined) {
  5495. options.preserveDrawingBuffer = false;
  5496. }
  5497. // GL
  5498. try {
  5499. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5500. }
  5501. catch (e) {
  5502. throw new Error("WebGL not supported");
  5503. }
  5504. if (!this._gl) {
  5505. throw new Error("WebGL not supported");
  5506. }
  5507. this._onBlur = function () {
  5508. _this._windowIsBackground = true;
  5509. };
  5510. this._onFocus = function () {
  5511. _this._windowIsBackground = false;
  5512. };
  5513. window.addEventListener("blur", this._onBlur);
  5514. window.addEventListener("focus", this._onFocus);
  5515. // Viewport
  5516. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5517. this.resize();
  5518. // Caps
  5519. this._caps = new EngineCapabilities();
  5520. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5521. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5522. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5523. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5524. // Infos
  5525. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5526. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5527. if (rendererInfo != null) {
  5528. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5529. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5530. }
  5531. if (!this._glVendor) {
  5532. this._glVendor = "Unknown vendor";
  5533. }
  5534. if (!this._glRenderer) {
  5535. this._glRenderer = "Unknown renderer";
  5536. }
  5537. // Extensions
  5538. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5539. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5540. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5541. 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');
  5542. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5543. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5544. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5545. this._caps.highPrecisionShaderSupported = true;
  5546. if (this._gl.getShaderPrecisionFormat) {
  5547. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5548. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5549. }
  5550. // Depth buffer
  5551. this.setDepthBuffer(true);
  5552. this.setDepthFunctionToLessOrEqual();
  5553. this.setDepthWrite(true);
  5554. // Fullscreen
  5555. this._onFullscreenChange = function () {
  5556. if (document.fullscreen !== undefined) {
  5557. _this.isFullscreen = document.fullscreen;
  5558. }
  5559. else if (document.mozFullScreen !== undefined) {
  5560. _this.isFullscreen = document.mozFullScreen;
  5561. }
  5562. else if (document.webkitIsFullScreen !== undefined) {
  5563. _this.isFullscreen = document.webkitIsFullScreen;
  5564. }
  5565. else if (document.msIsFullScreen !== undefined) {
  5566. _this.isFullscreen = document.msIsFullScreen;
  5567. }
  5568. // Pointer lock
  5569. if (_this.isFullscreen && _this._pointerLockRequested) {
  5570. canvas.requestPointerLock = canvas.requestPointerLock ||
  5571. canvas.msRequestPointerLock ||
  5572. canvas.mozRequestPointerLock ||
  5573. canvas.webkitRequestPointerLock;
  5574. if (canvas.requestPointerLock) {
  5575. canvas.requestPointerLock();
  5576. }
  5577. }
  5578. };
  5579. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5580. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5581. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5582. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5583. // Pointer lock
  5584. this._onPointerLockChange = function () {
  5585. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5586. document.webkitPointerLockElement === canvas ||
  5587. document.msPointerLockElement === canvas ||
  5588. document.pointerLockElement === canvas);
  5589. };
  5590. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5591. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5592. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5593. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5594. if (!Engine.audioEngine) {
  5595. Engine.audioEngine = new BABYLON.AudioEngine();
  5596. }
  5597. //default loading screen
  5598. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5599. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5600. }
  5601. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5602. get: function () {
  5603. return Engine._ALPHA_DISABLE;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5609. get: function () {
  5610. return Engine._ALPHA_ONEONE;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(Engine, "ALPHA_ADD", {
  5616. get: function () {
  5617. return Engine._ALPHA_ADD;
  5618. },
  5619. enumerable: true,
  5620. configurable: true
  5621. });
  5622. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5623. get: function () {
  5624. return Engine._ALPHA_COMBINE;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5630. get: function () {
  5631. return Engine._ALPHA_SUBTRACT;
  5632. },
  5633. enumerable: true,
  5634. configurable: true
  5635. });
  5636. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5637. get: function () {
  5638. return Engine._ALPHA_MULTIPLY;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5644. get: function () {
  5645. return Engine._ALPHA_MAXIMIZED;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5651. get: function () {
  5652. return Engine._DELAYLOADSTATE_NONE;
  5653. },
  5654. enumerable: true,
  5655. configurable: true
  5656. });
  5657. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5658. get: function () {
  5659. return Engine._DELAYLOADSTATE_LOADED;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5665. get: function () {
  5666. return Engine._DELAYLOADSTATE_LOADING;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5672. get: function () {
  5673. return Engine._DELAYLOADSTATE_NOTLOADED;
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5679. get: function () {
  5680. return Engine._TEXTUREFORMAT_ALPHA;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5686. get: function () {
  5687. return Engine._TEXTUREFORMAT_LUMINANCE;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5693. get: function () {
  5694. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5695. },
  5696. enumerable: true,
  5697. configurable: true
  5698. });
  5699. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5700. get: function () {
  5701. return Engine._TEXTUREFORMAT_RGB;
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5707. get: function () {
  5708. return Engine._TEXTUREFORMAT_RGBA;
  5709. },
  5710. enumerable: true,
  5711. configurable: true
  5712. });
  5713. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5714. get: function () {
  5715. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5716. },
  5717. enumerable: true,
  5718. configurable: true
  5719. });
  5720. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5721. get: function () {
  5722. return Engine._TEXTURETYPE_FLOAT;
  5723. },
  5724. enumerable: true,
  5725. configurable: true
  5726. });
  5727. Object.defineProperty(Engine, "Version", {
  5728. get: function () {
  5729. return "2.3.0-alpha";
  5730. },
  5731. enumerable: true,
  5732. configurable: true
  5733. });
  5734. Engine.prototype._prepareWorkingCanvas = function () {
  5735. if (this._workingCanvas) {
  5736. return;
  5737. }
  5738. this._workingCanvas = document.createElement("canvas");
  5739. this._workingContext = this._workingCanvas.getContext("2d");
  5740. };
  5741. Engine.prototype.getGlInfo = function () {
  5742. return {
  5743. vendor: this._glVendor,
  5744. renderer: this._glRenderer,
  5745. version: this._glVersion
  5746. };
  5747. };
  5748. Engine.prototype.getAspectRatio = function (camera) {
  5749. var viewport = camera.viewport;
  5750. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5751. };
  5752. Engine.prototype.getRenderWidth = function () {
  5753. if (this._currentRenderTarget) {
  5754. return this._currentRenderTarget._width;
  5755. }
  5756. return this._renderingCanvas.width;
  5757. };
  5758. Engine.prototype.getRenderHeight = function () {
  5759. if (this._currentRenderTarget) {
  5760. return this._currentRenderTarget._height;
  5761. }
  5762. return this._renderingCanvas.height;
  5763. };
  5764. Engine.prototype.getRenderingCanvas = function () {
  5765. return this._renderingCanvas;
  5766. };
  5767. Engine.prototype.getRenderingCanvasClientRect = function () {
  5768. return this._renderingCanvas.getBoundingClientRect();
  5769. };
  5770. Engine.prototype.setHardwareScalingLevel = function (level) {
  5771. this._hardwareScalingLevel = level;
  5772. this.resize();
  5773. };
  5774. Engine.prototype.getHardwareScalingLevel = function () {
  5775. return this._hardwareScalingLevel;
  5776. };
  5777. Engine.prototype.getLoadedTexturesCache = function () {
  5778. return this._loadedTexturesCache;
  5779. };
  5780. Engine.prototype.getCaps = function () {
  5781. return this._caps;
  5782. };
  5783. Object.defineProperty(Engine.prototype, "drawCalls", {
  5784. get: function () {
  5785. return this._drawCalls;
  5786. },
  5787. enumerable: true,
  5788. configurable: true
  5789. });
  5790. // Methods
  5791. Engine.prototype.resetDrawCalls = function () {
  5792. this._drawCalls = 0;
  5793. };
  5794. Engine.prototype.setDepthFunctionToGreater = function () {
  5795. this._depthCullingState.depthFunc = this._gl.GREATER;
  5796. };
  5797. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5798. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5799. };
  5800. Engine.prototype.setDepthFunctionToLess = function () {
  5801. this._depthCullingState.depthFunc = this._gl.LESS;
  5802. };
  5803. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5804. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5805. };
  5806. /**
  5807. * stop executing a render loop function and remove it from the execution array
  5808. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5809. */
  5810. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5811. if (!renderFunction) {
  5812. this._activeRenderLoops = [];
  5813. return;
  5814. }
  5815. var index = this._activeRenderLoops.indexOf(renderFunction);
  5816. if (index >= 0) {
  5817. this._activeRenderLoops.splice(index, 1);
  5818. }
  5819. };
  5820. Engine.prototype._renderLoop = function () {
  5821. var _this = this;
  5822. var shouldRender = true;
  5823. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5824. shouldRender = false;
  5825. }
  5826. if (shouldRender) {
  5827. // Start new frame
  5828. this.beginFrame();
  5829. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5830. var renderFunction = this._activeRenderLoops[index];
  5831. renderFunction();
  5832. }
  5833. // Present
  5834. this.endFrame();
  5835. }
  5836. if (this._activeRenderLoops.length > 0) {
  5837. // Register new frame
  5838. BABYLON.Tools.QueueNewFrame(function () {
  5839. _this._renderLoop();
  5840. });
  5841. }
  5842. else {
  5843. this._renderingQueueLaunched = false;
  5844. }
  5845. };
  5846. /**
  5847. * Register and execute a render loop. The engine can have more than one render function.
  5848. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5849. * @example
  5850. * engine.runRenderLoop(function () {
  5851. * scene.render()
  5852. * })
  5853. */
  5854. Engine.prototype.runRenderLoop = function (renderFunction) {
  5855. var _this = this;
  5856. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5857. return;
  5858. }
  5859. this._activeRenderLoops.push(renderFunction);
  5860. if (!this._renderingQueueLaunched) {
  5861. this._renderingQueueLaunched = true;
  5862. BABYLON.Tools.QueueNewFrame(function () {
  5863. _this._renderLoop();
  5864. });
  5865. }
  5866. };
  5867. /**
  5868. * Toggle full screen mode.
  5869. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5870. */
  5871. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5872. if (this.isFullscreen) {
  5873. BABYLON.Tools.ExitFullscreen();
  5874. }
  5875. else {
  5876. this._pointerLockRequested = requestPointerLock;
  5877. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5878. }
  5879. };
  5880. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5881. this.applyStates();
  5882. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5883. if (this._depthCullingState.depthMask) {
  5884. this._gl.clearDepth(1.0);
  5885. }
  5886. var mode = 0;
  5887. if (backBuffer)
  5888. mode |= this._gl.COLOR_BUFFER_BIT;
  5889. if (depthStencil && this._depthCullingState.depthMask)
  5890. mode |= this._gl.DEPTH_BUFFER_BIT;
  5891. this._gl.clear(mode);
  5892. };
  5893. /**
  5894. * Set the WebGL's viewport
  5895. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5896. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5897. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5898. */
  5899. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5900. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5901. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5902. var x = viewport.x || 0;
  5903. var y = viewport.y || 0;
  5904. this._cachedViewport = viewport;
  5905. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5906. };
  5907. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5908. this._cachedViewport = null;
  5909. this._gl.viewport(x, y, width, height);
  5910. };
  5911. Engine.prototype.beginFrame = function () {
  5912. this._measureFps();
  5913. };
  5914. Engine.prototype.endFrame = function () {
  5915. //this.flushFramebuffer();
  5916. };
  5917. /**
  5918. * resize the view according to the canvas' size.
  5919. * @example
  5920. * window.addEventListener("resize", function () {
  5921. * engine.resize();
  5922. * });
  5923. */
  5924. Engine.prototype.resize = function () {
  5925. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5926. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5927. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5928. };
  5929. /**
  5930. * force a specific size of the canvas
  5931. * @param {number} width - the new canvas' width
  5932. * @param {number} height - the new canvas' height
  5933. */
  5934. Engine.prototype.setSize = function (width, height) {
  5935. this._renderingCanvas.width = width;
  5936. this._renderingCanvas.height = height;
  5937. for (var index = 0; index < this.scenes.length; index++) {
  5938. var scene = this.scenes[index];
  5939. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5940. var cam = scene.cameras[camIndex];
  5941. cam._currentRenderId = 0;
  5942. }
  5943. }
  5944. };
  5945. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5946. this._currentRenderTarget = texture;
  5947. var gl = this._gl;
  5948. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5949. if (texture.isCube) {
  5950. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5951. }
  5952. else {
  5953. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5954. }
  5955. this._gl.viewport(0, 0, texture._width, texture._height);
  5956. this.wipeCaches();
  5957. };
  5958. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5959. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5960. this._currentRenderTarget = null;
  5961. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5962. var gl = this._gl;
  5963. gl.bindTexture(gl.TEXTURE_2D, texture);
  5964. gl.generateMipmap(gl.TEXTURE_2D);
  5965. gl.bindTexture(gl.TEXTURE_2D, null);
  5966. }
  5967. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5968. };
  5969. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5970. if (texture.generateMipMaps) {
  5971. var gl = this._gl;
  5972. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5973. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5974. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5975. }
  5976. };
  5977. Engine.prototype.flushFramebuffer = function () {
  5978. this._gl.flush();
  5979. };
  5980. Engine.prototype.restoreDefaultFramebuffer = function () {
  5981. this._currentRenderTarget = null;
  5982. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5983. this.setViewport(this._cachedViewport);
  5984. this.wipeCaches();
  5985. };
  5986. // VBOs
  5987. Engine.prototype._resetVertexBufferBinding = function () {
  5988. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5989. this._cachedVertexBuffers = null;
  5990. };
  5991. Engine.prototype.createVertexBuffer = function (vertices) {
  5992. var vbo = this._gl.createBuffer();
  5993. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5994. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5995. this._resetVertexBufferBinding();
  5996. vbo.references = 1;
  5997. return vbo;
  5998. };
  5999. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6000. var vbo = this._gl.createBuffer();
  6001. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6002. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6003. this._resetVertexBufferBinding();
  6004. vbo.references = 1;
  6005. return vbo;
  6006. };
  6007. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6008. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6009. if (offset === undefined) {
  6010. offset = 0;
  6011. }
  6012. if (vertices instanceof Float32Array) {
  6013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6014. }
  6015. else {
  6016. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6017. }
  6018. this._resetVertexBufferBinding();
  6019. };
  6020. Engine.prototype._resetIndexBufferBinding = function () {
  6021. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6022. this._cachedIndexBuffer = null;
  6023. };
  6024. Engine.prototype.createIndexBuffer = function (indices) {
  6025. var vbo = this._gl.createBuffer();
  6026. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6027. // Check for 32 bits indices
  6028. var arrayBuffer;
  6029. var need32Bits = false;
  6030. if (this._caps.uintIndices) {
  6031. for (var index = 0; index < indices.length; index++) {
  6032. if (indices[index] > 65535) {
  6033. need32Bits = true;
  6034. break;
  6035. }
  6036. }
  6037. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6038. }
  6039. else {
  6040. arrayBuffer = new Uint16Array(indices);
  6041. }
  6042. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6043. this._resetIndexBufferBinding();
  6044. vbo.references = 1;
  6045. vbo.is32Bits = need32Bits;
  6046. return vbo;
  6047. };
  6048. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6049. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6050. this._cachedVertexBuffers = vertexBuffer;
  6051. this._cachedEffectForVertexBuffers = effect;
  6052. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6053. var offset = 0;
  6054. for (var index = 0; index < vertexDeclaration.length; index++) {
  6055. var order = effect.getAttributeLocation(index);
  6056. if (order >= 0) {
  6057. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6058. }
  6059. offset += vertexDeclaration[index] * 4;
  6060. }
  6061. }
  6062. if (this._cachedIndexBuffer !== indexBuffer) {
  6063. this._cachedIndexBuffer = indexBuffer;
  6064. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6065. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6066. }
  6067. };
  6068. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6069. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6070. this._cachedVertexBuffers = vertexBuffers;
  6071. this._cachedEffectForVertexBuffers = effect;
  6072. var attributes = effect.getAttributesNames();
  6073. for (var index = 0; index < attributes.length; index++) {
  6074. var order = effect.getAttributeLocation(index);
  6075. if (order >= 0) {
  6076. var vertexBuffer = vertexBuffers[attributes[index]];
  6077. if (!vertexBuffer) {
  6078. continue;
  6079. }
  6080. var stride = vertexBuffer.getStrideSize();
  6081. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6082. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6083. }
  6084. }
  6085. }
  6086. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6087. this._cachedIndexBuffer = indexBuffer;
  6088. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6089. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6090. }
  6091. };
  6092. Engine.prototype._releaseBuffer = function (buffer) {
  6093. buffer.references--;
  6094. if (buffer.references === 0) {
  6095. this._gl.deleteBuffer(buffer);
  6096. return true;
  6097. }
  6098. return false;
  6099. };
  6100. Engine.prototype.createInstancesBuffer = function (capacity) {
  6101. var buffer = this._gl.createBuffer();
  6102. buffer.capacity = capacity;
  6103. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6104. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6105. return buffer;
  6106. };
  6107. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6108. this._gl.deleteBuffer(buffer);
  6109. };
  6110. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6111. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6112. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6113. for (var index = 0; index < 4; index++) {
  6114. var offsetLocation = offsetLocations[index];
  6115. this._gl.enableVertexAttribArray(offsetLocation);
  6116. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6117. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6118. }
  6119. };
  6120. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6121. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6122. for (var index = 0; index < 4; index++) {
  6123. var offsetLocation = offsetLocations[index];
  6124. this._gl.disableVertexAttribArray(offsetLocation);
  6125. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6126. }
  6127. };
  6128. Engine.prototype.applyStates = function () {
  6129. this._depthCullingState.apply(this._gl);
  6130. this._alphaState.apply(this._gl);
  6131. };
  6132. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6133. // Apply states
  6134. this.applyStates();
  6135. this._drawCalls++;
  6136. // Render
  6137. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6138. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6139. if (instancesCount) {
  6140. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6141. return;
  6142. }
  6143. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6144. };
  6145. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6146. // Apply states
  6147. this.applyStates();
  6148. this._drawCalls++;
  6149. if (instancesCount) {
  6150. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6151. return;
  6152. }
  6153. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6154. };
  6155. // Shaders
  6156. Engine.prototype._releaseEffect = function (effect) {
  6157. if (this._compiledEffects[effect._key]) {
  6158. delete this._compiledEffects[effect._key];
  6159. if (effect.getProgram()) {
  6160. this._gl.deleteProgram(effect.getProgram());
  6161. }
  6162. }
  6163. };
  6164. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6165. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6166. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6167. var name = vertex + "+" + fragment + "@" + defines;
  6168. if (this._compiledEffects[name]) {
  6169. return this._compiledEffects[name];
  6170. }
  6171. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6172. effect._key = name;
  6173. this._compiledEffects[name] = effect;
  6174. return effect;
  6175. };
  6176. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6177. if (uniformsNames === void 0) { uniformsNames = []; }
  6178. if (samplers === void 0) { samplers = []; }
  6179. if (defines === void 0) { defines = ""; }
  6180. return this.createEffect({
  6181. vertex: "particles",
  6182. fragmentElement: fragmentName
  6183. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6184. };
  6185. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6186. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6187. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6188. var shaderProgram = this._gl.createProgram();
  6189. this._gl.attachShader(shaderProgram, vertexShader);
  6190. this._gl.attachShader(shaderProgram, fragmentShader);
  6191. this._gl.linkProgram(shaderProgram);
  6192. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6193. if (!linked) {
  6194. var error = this._gl.getProgramInfoLog(shaderProgram);
  6195. if (error) {
  6196. throw new Error(error);
  6197. }
  6198. }
  6199. this._gl.deleteShader(vertexShader);
  6200. this._gl.deleteShader(fragmentShader);
  6201. return shaderProgram;
  6202. };
  6203. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6204. var results = [];
  6205. for (var index = 0; index < uniformsNames.length; index++) {
  6206. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6207. }
  6208. return results;
  6209. };
  6210. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6211. var results = [];
  6212. for (var index = 0; index < attributesNames.length; index++) {
  6213. try {
  6214. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6215. }
  6216. catch (e) {
  6217. results.push(-1);
  6218. }
  6219. }
  6220. return results;
  6221. };
  6222. Engine.prototype.enableEffect = function (effect) {
  6223. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6224. if (effect && effect.onBind) {
  6225. effect.onBind(effect);
  6226. }
  6227. return;
  6228. }
  6229. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6230. // Use program
  6231. this._gl.useProgram(effect.getProgram());
  6232. for (var i in this._vertexAttribArrays) {
  6233. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6234. continue;
  6235. }
  6236. this._vertexAttribArrays[i] = false;
  6237. this._gl.disableVertexAttribArray(i);
  6238. }
  6239. var attributesCount = effect.getAttributesCount();
  6240. for (var index = 0; index < attributesCount; index++) {
  6241. // Attributes
  6242. var order = effect.getAttributeLocation(index);
  6243. if (order >= 0) {
  6244. this._vertexAttribArrays[order] = true;
  6245. this._gl.enableVertexAttribArray(order);
  6246. }
  6247. }
  6248. this._currentEffect = effect;
  6249. if (effect.onBind) {
  6250. effect.onBind(effect);
  6251. }
  6252. };
  6253. Engine.prototype.setArray = function (uniform, array) {
  6254. if (!uniform)
  6255. return;
  6256. this._gl.uniform1fv(uniform, array);
  6257. };
  6258. Engine.prototype.setArray2 = function (uniform, array) {
  6259. if (!uniform || array.length % 2 !== 0)
  6260. return;
  6261. this._gl.uniform2fv(uniform, array);
  6262. };
  6263. Engine.prototype.setArray3 = function (uniform, array) {
  6264. if (!uniform || array.length % 3 !== 0)
  6265. return;
  6266. this._gl.uniform3fv(uniform, array);
  6267. };
  6268. Engine.prototype.setArray4 = function (uniform, array) {
  6269. if (!uniform || array.length % 4 !== 0)
  6270. return;
  6271. this._gl.uniform4fv(uniform, array);
  6272. };
  6273. Engine.prototype.setMatrices = function (uniform, matrices) {
  6274. if (!uniform)
  6275. return;
  6276. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6277. };
  6278. Engine.prototype.setMatrix = function (uniform, matrix) {
  6279. if (!uniform)
  6280. return;
  6281. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6282. };
  6283. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6284. if (!uniform)
  6285. return;
  6286. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6287. };
  6288. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6289. if (!uniform)
  6290. return;
  6291. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6292. };
  6293. Engine.prototype.setFloat = function (uniform, value) {
  6294. if (!uniform)
  6295. return;
  6296. this._gl.uniform1f(uniform, value);
  6297. };
  6298. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6299. if (!uniform)
  6300. return;
  6301. this._gl.uniform2f(uniform, x, y);
  6302. };
  6303. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6304. if (!uniform)
  6305. return;
  6306. this._gl.uniform3f(uniform, x, y, z);
  6307. };
  6308. Engine.prototype.setBool = function (uniform, bool) {
  6309. if (!uniform)
  6310. return;
  6311. this._gl.uniform1i(uniform, bool);
  6312. };
  6313. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6314. if (!uniform)
  6315. return;
  6316. this._gl.uniform4f(uniform, x, y, z, w);
  6317. };
  6318. Engine.prototype.setColor3 = function (uniform, color3) {
  6319. if (!uniform)
  6320. return;
  6321. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6322. };
  6323. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6324. if (!uniform)
  6325. return;
  6326. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6327. };
  6328. // States
  6329. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6330. if (zOffset === void 0) { zOffset = 0; }
  6331. if (reverseSide === void 0) { reverseSide = false; }
  6332. // Culling
  6333. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6334. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6335. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6336. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6337. if (culling) {
  6338. this._depthCullingState.cullFace = cullFace;
  6339. this._depthCullingState.cull = true;
  6340. }
  6341. else {
  6342. this._depthCullingState.cull = false;
  6343. }
  6344. }
  6345. // Z offset
  6346. this._depthCullingState.zOffset = zOffset;
  6347. };
  6348. Engine.prototype.setDepthBuffer = function (enable) {
  6349. this._depthCullingState.depthTest = enable;
  6350. };
  6351. Engine.prototype.getDepthWrite = function () {
  6352. return this._depthCullingState.depthMask;
  6353. };
  6354. Engine.prototype.setDepthWrite = function (enable) {
  6355. this._depthCullingState.depthMask = enable;
  6356. };
  6357. Engine.prototype.setColorWrite = function (enable) {
  6358. this._gl.colorMask(enable, enable, enable, enable);
  6359. };
  6360. Engine.prototype.setAlphaMode = function (mode) {
  6361. if (this._alphaMode === mode) {
  6362. return;
  6363. }
  6364. switch (mode) {
  6365. case Engine.ALPHA_DISABLE:
  6366. this.setDepthWrite(true);
  6367. this._alphaState.alphaBlend = false;
  6368. break;
  6369. case Engine.ALPHA_COMBINE:
  6370. this.setDepthWrite(false);
  6371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6372. this._alphaState.alphaBlend = true;
  6373. break;
  6374. case Engine.ALPHA_ONEONE:
  6375. this.setDepthWrite(false);
  6376. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6377. this._alphaState.alphaBlend = true;
  6378. break;
  6379. case Engine.ALPHA_ADD:
  6380. this.setDepthWrite(false);
  6381. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6382. this._alphaState.alphaBlend = true;
  6383. break;
  6384. case Engine.ALPHA_SUBTRACT:
  6385. this.setDepthWrite(false);
  6386. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6387. this._alphaState.alphaBlend = true;
  6388. break;
  6389. case Engine.ALPHA_MULTIPLY:
  6390. this.setDepthWrite(false);
  6391. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6392. this._alphaState.alphaBlend = true;
  6393. break;
  6394. case Engine.ALPHA_MAXIMIZED:
  6395. this.setDepthWrite(false);
  6396. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6397. this._alphaState.alphaBlend = true;
  6398. break;
  6399. }
  6400. this._alphaMode = mode;
  6401. };
  6402. Engine.prototype.getAlphaMode = function () {
  6403. return this._alphaMode;
  6404. };
  6405. Engine.prototype.setAlphaTesting = function (enable) {
  6406. this._alphaTest = enable;
  6407. };
  6408. Engine.prototype.getAlphaTesting = function () {
  6409. return this._alphaTest;
  6410. };
  6411. // Textures
  6412. Engine.prototype.wipeCaches = function () {
  6413. this._activeTexturesCache = [];
  6414. this._currentEffect = null;
  6415. this._depthCullingState.reset();
  6416. this._alphaState.reset();
  6417. this._cachedVertexBuffers = null;
  6418. this._cachedIndexBuffer = null;
  6419. this._cachedEffectForVertexBuffers = null;
  6420. };
  6421. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6422. var gl = this._gl;
  6423. gl.bindTexture(gl.TEXTURE_2D, texture);
  6424. var magFilter = gl.NEAREST;
  6425. var minFilter = gl.NEAREST;
  6426. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6427. magFilter = gl.LINEAR;
  6428. minFilter = gl.LINEAR;
  6429. }
  6430. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6431. magFilter = gl.LINEAR;
  6432. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6433. }
  6434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6436. gl.bindTexture(gl.TEXTURE_2D, null);
  6437. texture.samplingMode = samplingMode;
  6438. };
  6439. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6440. var _this = this;
  6441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6442. if (onLoad === void 0) { onLoad = null; }
  6443. if (onError === void 0) { onError = null; }
  6444. if (buffer === void 0) { buffer = null; }
  6445. var texture = this._gl.createTexture();
  6446. var extension;
  6447. var fromData = false;
  6448. if (url.substr(0, 5) === "data:") {
  6449. fromData = true;
  6450. }
  6451. if (!fromData)
  6452. extension = url.substr(url.length - 4, 4).toLowerCase();
  6453. else {
  6454. var oldUrl = url;
  6455. fromData = oldUrl.split(':');
  6456. url = oldUrl;
  6457. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6458. }
  6459. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6460. var isTGA = (extension === ".tga");
  6461. scene._addPendingData(texture);
  6462. texture.url = url;
  6463. texture.noMipmap = noMipmap;
  6464. texture.references = 1;
  6465. texture.samplingMode = samplingMode;
  6466. this._loadedTexturesCache.push(texture);
  6467. var onerror = function () {
  6468. scene._removePendingData(texture);
  6469. if (onError) {
  6470. onError();
  6471. }
  6472. };
  6473. var callback;
  6474. if (isTGA) {
  6475. callback = function (arrayBuffer) {
  6476. var data = new Uint8Array(arrayBuffer);
  6477. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6478. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6479. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6480. if (onLoad) {
  6481. onLoad();
  6482. }
  6483. }, samplingMode);
  6484. };
  6485. if (!(fromData instanceof Array))
  6486. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6487. callback(arrayBuffer);
  6488. }, onerror, scene.database, true);
  6489. else
  6490. callback(buffer);
  6491. }
  6492. else if (isDDS) {
  6493. callback = function (data) {
  6494. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6495. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6496. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6497. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6498. if (onLoad) {
  6499. onLoad();
  6500. }
  6501. }, samplingMode);
  6502. };
  6503. if (!(fromData instanceof Array))
  6504. BABYLON.Tools.LoadFile(url, function (data) {
  6505. callback(data);
  6506. }, onerror, scene.database, true);
  6507. else
  6508. callback(buffer);
  6509. }
  6510. else {
  6511. var onload = function (img) {
  6512. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6513. var isPot = (img.width === potWidth && img.height === potHeight);
  6514. if (!isPot) {
  6515. _this._prepareWorkingCanvas();
  6516. _this._workingCanvas.width = potWidth;
  6517. _this._workingCanvas.height = potHeight;
  6518. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6519. _this._workingContext.imageSmoothingEnabled = false;
  6520. _this._workingContext.mozImageSmoothingEnabled = false;
  6521. _this._workingContext.oImageSmoothingEnabled = false;
  6522. _this._workingContext.webkitImageSmoothingEnabled = false;
  6523. _this._workingContext.msImageSmoothingEnabled = false;
  6524. }
  6525. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6526. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6527. _this._workingContext.imageSmoothingEnabled = true;
  6528. _this._workingContext.mozImageSmoothingEnabled = true;
  6529. _this._workingContext.oImageSmoothingEnabled = true;
  6530. _this._workingContext.webkitImageSmoothingEnabled = true;
  6531. _this._workingContext.msImageSmoothingEnabled = true;
  6532. }
  6533. }
  6534. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6535. if (onLoad) {
  6536. onLoad();
  6537. }
  6538. }, samplingMode);
  6539. };
  6540. if (!(fromData instanceof Array))
  6541. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6542. else
  6543. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6544. }
  6545. return texture;
  6546. };
  6547. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6548. if (compression === void 0) { compression = null; }
  6549. var internalFormat = this._gl.RGBA;
  6550. switch (format) {
  6551. case Engine.TEXTUREFORMAT_ALPHA:
  6552. internalFormat = this._gl.ALPHA;
  6553. break;
  6554. case Engine.TEXTUREFORMAT_LUMINANCE:
  6555. internalFormat = this._gl.LUMINANCE;
  6556. break;
  6557. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6558. internalFormat = this._gl.LUMINANCE_ALPHA;
  6559. break;
  6560. case Engine.TEXTUREFORMAT_RGB:
  6561. internalFormat = this._gl.RGB;
  6562. break;
  6563. case Engine.TEXTUREFORMAT_RGBA:
  6564. internalFormat = this._gl.RGBA;
  6565. break;
  6566. }
  6567. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6568. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6569. if (compression) {
  6570. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6571. }
  6572. else {
  6573. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6574. }
  6575. if (texture.generateMipMaps) {
  6576. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6577. }
  6578. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6579. this._activeTexturesCache = [];
  6580. texture.isReady = true;
  6581. };
  6582. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6583. if (compression === void 0) { compression = null; }
  6584. var texture = this._gl.createTexture();
  6585. texture._baseWidth = width;
  6586. texture._baseHeight = height;
  6587. texture._width = width;
  6588. texture._height = height;
  6589. texture.references = 1;
  6590. this.updateRawTexture(texture, data, format, invertY, compression);
  6591. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6592. // Filters
  6593. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6594. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6595. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6596. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6597. texture.samplingMode = samplingMode;
  6598. this._loadedTexturesCache.push(texture);
  6599. return texture;
  6600. };
  6601. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6602. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6603. var texture = this._gl.createTexture();
  6604. texture._baseWidth = width;
  6605. texture._baseHeight = height;
  6606. if (forceExponantOfTwo) {
  6607. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6608. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6609. }
  6610. this._activeTexturesCache = [];
  6611. texture._width = width;
  6612. texture._height = height;
  6613. texture.isReady = false;
  6614. texture.generateMipMaps = generateMipMaps;
  6615. texture.references = 1;
  6616. texture.samplingMode = samplingMode;
  6617. this.updateTextureSamplingMode(samplingMode, texture);
  6618. this._loadedTexturesCache.push(texture);
  6619. return texture;
  6620. };
  6621. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6622. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6623. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6626. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6627. };
  6628. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6629. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6630. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6631. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6632. if (texture.generateMipMaps) {
  6633. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6634. }
  6635. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6636. this._activeTexturesCache = [];
  6637. texture.isReady = true;
  6638. };
  6639. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6640. if (texture._isDisabled) {
  6641. return;
  6642. }
  6643. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6644. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6645. try {
  6646. // Testing video texture support
  6647. if (this._videoTextureSupported === undefined) {
  6648. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6649. if (this._gl.getError() !== 0) {
  6650. this._videoTextureSupported = false;
  6651. }
  6652. else {
  6653. this._videoTextureSupported = true;
  6654. }
  6655. }
  6656. // Copy video through the current working canvas if video texture is not supported
  6657. if (!this._videoTextureSupported) {
  6658. if (!texture._workingCanvas) {
  6659. texture._workingCanvas = document.createElement("canvas");
  6660. texture._workingContext = texture._workingCanvas.getContext("2d");
  6661. texture._workingCanvas.width = texture._width;
  6662. texture._workingCanvas.height = texture._height;
  6663. }
  6664. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6665. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6666. }
  6667. else {
  6668. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6669. }
  6670. if (texture.generateMipMaps) {
  6671. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6672. }
  6673. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6674. this._activeTexturesCache = [];
  6675. texture.isReady = true;
  6676. }
  6677. catch (ex) {
  6678. // Something unexpected
  6679. // Let's disable the texture
  6680. texture._isDisabled = true;
  6681. }
  6682. };
  6683. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6684. // old version had a "generateMipMaps" arg instead of options.
  6685. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6686. // in the same way, generateDepthBuffer is defaulted to true
  6687. var generateMipMaps = false;
  6688. var generateDepthBuffer = true;
  6689. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6690. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6691. if (options !== undefined) {
  6692. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6693. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6694. type = options.type === undefined ? type : options.type;
  6695. if (options.samplingMode !== undefined) {
  6696. samplingMode = options.samplingMode;
  6697. }
  6698. if (type === Engine.TEXTURETYPE_FLOAT) {
  6699. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6700. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6701. }
  6702. }
  6703. var gl = this._gl;
  6704. var texture = gl.createTexture();
  6705. gl.bindTexture(gl.TEXTURE_2D, texture);
  6706. var width = size.width || size;
  6707. var height = size.height || size;
  6708. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6709. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6710. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6711. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6712. }
  6713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6716. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6717. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6718. var depthBuffer;
  6719. // Create the depth buffer
  6720. if (generateDepthBuffer) {
  6721. depthBuffer = gl.createRenderbuffer();
  6722. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6723. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6724. }
  6725. // Create the framebuffer
  6726. var framebuffer = gl.createFramebuffer();
  6727. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6728. if (generateDepthBuffer) {
  6729. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6730. }
  6731. if (generateMipMaps) {
  6732. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6733. }
  6734. // Unbind
  6735. gl.bindTexture(gl.TEXTURE_2D, null);
  6736. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6737. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6738. texture._framebuffer = framebuffer;
  6739. if (generateDepthBuffer) {
  6740. texture._depthBuffer = depthBuffer;
  6741. }
  6742. texture._width = width;
  6743. texture._height = height;
  6744. texture.isReady = true;
  6745. texture.generateMipMaps = generateMipMaps;
  6746. texture.references = 1;
  6747. texture.samplingMode = samplingMode;
  6748. this._activeTexturesCache = [];
  6749. this._loadedTexturesCache.push(texture);
  6750. return texture;
  6751. };
  6752. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6753. var gl = this._gl;
  6754. var texture = gl.createTexture();
  6755. var generateMipMaps = true;
  6756. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6757. if (options !== undefined) {
  6758. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6759. if (options.samplingMode !== undefined) {
  6760. samplingMode = options.samplingMode;
  6761. }
  6762. }
  6763. texture.isCube = true;
  6764. texture.references = 1;
  6765. texture.generateMipMaps = generateMipMaps;
  6766. texture.references = 1;
  6767. texture.samplingMode = samplingMode;
  6768. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6769. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6770. for (var face = 0; face < 6; face++) {
  6771. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6772. }
  6773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6777. // Create the depth buffer
  6778. var depthBuffer = gl.createRenderbuffer();
  6779. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6780. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6781. // Create the framebuffer
  6782. var framebuffer = gl.createFramebuffer();
  6783. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6784. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6785. // Unbind
  6786. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6787. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6788. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6789. texture._framebuffer = framebuffer;
  6790. texture._depthBuffer = depthBuffer;
  6791. this._activeTexturesCache = [];
  6792. texture._width = size;
  6793. texture._height = size;
  6794. texture.isReady = true;
  6795. return texture;
  6796. };
  6797. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6798. var _this = this;
  6799. var gl = this._gl;
  6800. var texture = gl.createTexture();
  6801. texture.isCube = true;
  6802. texture.url = rootUrl;
  6803. texture.references = 1;
  6804. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6805. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6806. if (isDDS) {
  6807. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6808. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6809. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6810. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6811. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6812. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6813. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6814. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6815. }
  6816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6820. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6821. _this._activeTexturesCache = [];
  6822. texture._width = info.width;
  6823. texture._height = info.height;
  6824. texture.isReady = true;
  6825. }, null, null, true);
  6826. }
  6827. else {
  6828. cascadeLoad(rootUrl, scene, function (imgs) {
  6829. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6830. var height = width;
  6831. _this._prepareWorkingCanvas();
  6832. _this._workingCanvas.width = width;
  6833. _this._workingCanvas.height = height;
  6834. var faces = [
  6835. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6836. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6837. ];
  6838. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6839. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6840. for (var index = 0; index < faces.length; index++) {
  6841. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6842. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6843. }
  6844. if (!noMipmap) {
  6845. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6846. }
  6847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6851. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6852. _this._activeTexturesCache = [];
  6853. texture._width = width;
  6854. texture._height = height;
  6855. texture.isReady = true;
  6856. }, extensions);
  6857. }
  6858. return texture;
  6859. };
  6860. Engine.prototype._releaseTexture = function (texture) {
  6861. var gl = this._gl;
  6862. if (texture._framebuffer) {
  6863. gl.deleteFramebuffer(texture._framebuffer);
  6864. }
  6865. if (texture._depthBuffer) {
  6866. gl.deleteRenderbuffer(texture._depthBuffer);
  6867. }
  6868. gl.deleteTexture(texture);
  6869. // Unbind channels
  6870. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6871. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6872. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6873. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6874. this._activeTexturesCache[channel] = null;
  6875. }
  6876. var index = this._loadedTexturesCache.indexOf(texture);
  6877. if (index !== -1) {
  6878. this._loadedTexturesCache.splice(index, 1);
  6879. }
  6880. };
  6881. Engine.prototype.bindSamplers = function (effect) {
  6882. this._gl.useProgram(effect.getProgram());
  6883. var samplers = effect.getSamplers();
  6884. for (var index = 0; index < samplers.length; index++) {
  6885. var uniform = effect.getUniform(samplers[index]);
  6886. this._gl.uniform1i(uniform, index);
  6887. }
  6888. this._currentEffect = null;
  6889. };
  6890. Engine.prototype._bindTexture = function (channel, texture) {
  6891. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6892. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6893. this._activeTexturesCache[channel] = null;
  6894. };
  6895. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6896. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6897. };
  6898. Engine.prototype.setTexture = function (channel, texture) {
  6899. if (channel < 0) {
  6900. return;
  6901. }
  6902. // Not ready?
  6903. if (!texture || !texture.isReady()) {
  6904. if (this._activeTexturesCache[channel] != null) {
  6905. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6906. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6907. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6908. this._activeTexturesCache[channel] = null;
  6909. }
  6910. return;
  6911. }
  6912. // Video
  6913. if (texture instanceof BABYLON.VideoTexture) {
  6914. if (texture.update()) {
  6915. this._activeTexturesCache[channel] = null;
  6916. }
  6917. }
  6918. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6919. texture.delayLoad();
  6920. return;
  6921. }
  6922. if (this._activeTexturesCache[channel] === texture) {
  6923. return;
  6924. }
  6925. this._activeTexturesCache[channel] = texture;
  6926. var internalTexture = texture.getInternalTexture();
  6927. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6928. if (internalTexture.isCube) {
  6929. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6930. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6931. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6932. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6933. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6934. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6935. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6936. }
  6937. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6938. }
  6939. else {
  6940. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6941. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6942. internalTexture._cachedWrapU = texture.wrapU;
  6943. switch (texture.wrapU) {
  6944. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6945. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6946. break;
  6947. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6948. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6949. break;
  6950. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6951. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6952. break;
  6953. }
  6954. }
  6955. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6956. internalTexture._cachedWrapV = texture.wrapV;
  6957. switch (texture.wrapV) {
  6958. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6959. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6960. break;
  6961. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6962. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6963. break;
  6964. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6965. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6966. break;
  6967. }
  6968. }
  6969. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6970. }
  6971. };
  6972. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6973. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6974. var value = texture.anisotropicFilteringLevel;
  6975. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6976. value = 1;
  6977. }
  6978. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6979. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6980. texture._cachedAnisotropicFilteringLevel = value;
  6981. }
  6982. };
  6983. Engine.prototype.readPixels = function (x, y, width, height) {
  6984. var data = new Uint8Array(height * width * 4);
  6985. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6986. return data;
  6987. };
  6988. Engine.prototype.releaseInternalTexture = function (texture) {
  6989. if (!texture) {
  6990. return;
  6991. }
  6992. texture.references--;
  6993. // Final reference ?
  6994. if (texture.references === 0) {
  6995. var texturesCache = this.getLoadedTexturesCache();
  6996. var index = texturesCache.indexOf(texture);
  6997. if (index > -1) {
  6998. texturesCache.splice(index, 1);
  6999. }
  7000. this._releaseTexture(texture);
  7001. }
  7002. };
  7003. // Dispose
  7004. Engine.prototype.dispose = function () {
  7005. this.hideLoadingUI();
  7006. this.stopRenderLoop();
  7007. // Release scenes
  7008. while (this.scenes.length) {
  7009. this.scenes[0].dispose();
  7010. }
  7011. // Release audio engine
  7012. Engine.audioEngine.dispose();
  7013. // Release effects
  7014. for (var name in this._compiledEffects) {
  7015. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7016. }
  7017. // Unbind
  7018. for (var i in this._vertexAttribArrays) {
  7019. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  7020. continue;
  7021. }
  7022. this._gl.disableVertexAttribArray(i);
  7023. }
  7024. this._gl = null;
  7025. // Events
  7026. window.removeEventListener("blur", this._onBlur);
  7027. window.removeEventListener("focus", this._onFocus);
  7028. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7029. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7030. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7031. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7032. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7033. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7034. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7035. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7036. };
  7037. // Loading screen
  7038. Engine.prototype.displayLoadingUI = function () {
  7039. this._loadingScreen.displayLoadingUI();
  7040. };
  7041. Engine.prototype.hideLoadingUI = function () {
  7042. this._loadingScreen.hideLoadingUI();
  7043. };
  7044. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7045. get: function () {
  7046. return this._loadingScreen;
  7047. },
  7048. set: function (loadingScreen) {
  7049. this._loadingScreen = loadingScreen;
  7050. },
  7051. enumerable: true,
  7052. configurable: true
  7053. });
  7054. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7055. set: function (text) {
  7056. this._loadingScreen.loadingUIText = text;
  7057. },
  7058. enumerable: true,
  7059. configurable: true
  7060. });
  7061. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7062. set: function (color) {
  7063. this._loadingScreen.loadingUIBackgroundColor = color;
  7064. },
  7065. enumerable: true,
  7066. configurable: true
  7067. });
  7068. // FPS
  7069. Engine.prototype.getFps = function () {
  7070. return this.fps;
  7071. };
  7072. Engine.prototype.getDeltaTime = function () {
  7073. return this.deltaTime;
  7074. };
  7075. Engine.prototype._measureFps = function () {
  7076. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7077. var length = this.previousFramesDuration.length;
  7078. if (length >= 2) {
  7079. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7080. }
  7081. if (length >= this.fpsRange) {
  7082. if (length > this.fpsRange) {
  7083. this.previousFramesDuration.splice(0, 1);
  7084. length = this.previousFramesDuration.length;
  7085. }
  7086. var sum = 0;
  7087. for (var id = 0; id < length - 1; id++) {
  7088. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7089. }
  7090. this.fps = 1000.0 / (sum / (length - 1));
  7091. }
  7092. };
  7093. // Statics
  7094. Engine.isSupported = function () {
  7095. try {
  7096. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7097. if (navigator.isCocoonJS) {
  7098. return true;
  7099. }
  7100. var tempcanvas = document.createElement("canvas");
  7101. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7102. return gl != null && !!window.WebGLRenderingContext;
  7103. }
  7104. catch (e) {
  7105. return false;
  7106. }
  7107. };
  7108. // Const statics
  7109. Engine._ALPHA_DISABLE = 0;
  7110. Engine._ALPHA_ADD = 1;
  7111. Engine._ALPHA_COMBINE = 2;
  7112. Engine._ALPHA_SUBTRACT = 3;
  7113. Engine._ALPHA_MULTIPLY = 4;
  7114. Engine._ALPHA_MAXIMIZED = 5;
  7115. Engine._ALPHA_ONEONE = 6;
  7116. Engine._DELAYLOADSTATE_NONE = 0;
  7117. Engine._DELAYLOADSTATE_LOADED = 1;
  7118. Engine._DELAYLOADSTATE_LOADING = 2;
  7119. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7120. Engine._TEXTUREFORMAT_ALPHA = 0;
  7121. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7122. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7123. Engine._TEXTUREFORMAT_RGB = 4;
  7124. Engine._TEXTUREFORMAT_RGBA = 5;
  7125. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7126. Engine._TEXTURETYPE_FLOAT = 1;
  7127. // Updatable statics so stick with vars here
  7128. Engine.Epsilon = 0.001;
  7129. Engine.CollisionsEpsilon = 0.001;
  7130. Engine.CodeRepository = "src/";
  7131. Engine.ShadersRepository = "src/Shaders/";
  7132. return Engine;
  7133. })();
  7134. BABYLON.Engine = Engine;
  7135. })(BABYLON || (BABYLON = {}));
  7136. var BABYLON;
  7137. (function (BABYLON) {
  7138. /**
  7139. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7140. */
  7141. var Node = (function () {
  7142. /**
  7143. * @constructor
  7144. * @param {string} name - the name and id to be given to this node
  7145. * @param {BABYLON.Scene} the scene this node will be added to
  7146. */
  7147. function Node(name, scene) {
  7148. this.state = "";
  7149. this.animations = new Array();
  7150. this._childrenFlag = -1;
  7151. this._isEnabled = true;
  7152. this._isReady = true;
  7153. this._currentRenderId = -1;
  7154. this._parentRenderId = -1;
  7155. this.name = name;
  7156. this.id = name;
  7157. this._scene = scene;
  7158. this._initCache();
  7159. }
  7160. Node.prototype.getScene = function () {
  7161. return this._scene;
  7162. };
  7163. Node.prototype.getEngine = function () {
  7164. return this._scene.getEngine();
  7165. };
  7166. // override it in derived class
  7167. Node.prototype.getWorldMatrix = function () {
  7168. return BABYLON.Matrix.Identity();
  7169. };
  7170. // override it in derived class if you add new variables to the cache
  7171. // and call the parent class method
  7172. Node.prototype._initCache = function () {
  7173. this._cache = {};
  7174. this._cache.parent = undefined;
  7175. };
  7176. Node.prototype.updateCache = function (force) {
  7177. if (!force && this.isSynchronized())
  7178. return;
  7179. this._cache.parent = this.parent;
  7180. this._updateCache();
  7181. };
  7182. // override it in derived class if you add new variables to the cache
  7183. // and call the parent class method if !ignoreParentClass
  7184. Node.prototype._updateCache = function (ignoreParentClass) {
  7185. };
  7186. // override it in derived class if you add new variables to the cache
  7187. Node.prototype._isSynchronized = function () {
  7188. return true;
  7189. };
  7190. Node.prototype._markSyncedWithParent = function () {
  7191. this._parentRenderId = this.parent._currentRenderId;
  7192. };
  7193. Node.prototype.isSynchronizedWithParent = function () {
  7194. if (!this.parent) {
  7195. return true;
  7196. }
  7197. if (this._parentRenderId !== this.parent._currentRenderId) {
  7198. return false;
  7199. }
  7200. return this.parent.isSynchronized();
  7201. };
  7202. Node.prototype.isSynchronized = function (updateCache) {
  7203. var check = this.hasNewParent();
  7204. check = check || !this.isSynchronizedWithParent();
  7205. check = check || !this._isSynchronized();
  7206. if (updateCache)
  7207. this.updateCache(true);
  7208. return !check;
  7209. };
  7210. Node.prototype.hasNewParent = function (update) {
  7211. if (this._cache.parent === this.parent)
  7212. return false;
  7213. if (update)
  7214. this._cache.parent = this.parent;
  7215. return true;
  7216. };
  7217. /**
  7218. * Is this node ready to be used/rendered
  7219. * @return {boolean} is it ready
  7220. */
  7221. Node.prototype.isReady = function () {
  7222. return this._isReady;
  7223. };
  7224. /**
  7225. * Is this node enabled.
  7226. * If the node has a parent and is enabled, the parent will be inspected as well.
  7227. * @return {boolean} whether this node (and its parent) is enabled.
  7228. * @see setEnabled
  7229. */
  7230. Node.prototype.isEnabled = function () {
  7231. if (!this._isEnabled) {
  7232. return false;
  7233. }
  7234. if (this.parent) {
  7235. return this.parent.isEnabled();
  7236. }
  7237. return true;
  7238. };
  7239. /**
  7240. * Set the enabled state of this node.
  7241. * @param {boolean} value - the new enabled state
  7242. * @see isEnabled
  7243. */
  7244. Node.prototype.setEnabled = function (value) {
  7245. this._isEnabled = value;
  7246. };
  7247. /**
  7248. * Is this node a descendant of the given node.
  7249. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7250. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7251. * @see parent
  7252. */
  7253. Node.prototype.isDescendantOf = function (ancestor) {
  7254. if (this.parent) {
  7255. if (this.parent === ancestor) {
  7256. return true;
  7257. }
  7258. return this.parent.isDescendantOf(ancestor);
  7259. }
  7260. return false;
  7261. };
  7262. Node.prototype._getDescendants = function (list, results) {
  7263. for (var index = 0; index < list.length; index++) {
  7264. var item = list[index];
  7265. if (item.isDescendantOf(this)) {
  7266. results.push(item);
  7267. }
  7268. }
  7269. };
  7270. /**
  7271. * Will return all nodes that have this node as parent.
  7272. * @return {BABYLON.Node[]} all children nodes of all types.
  7273. */
  7274. Node.prototype.getDescendants = function () {
  7275. var results = [];
  7276. this._getDescendants(this._scene.meshes, results);
  7277. this._getDescendants(this._scene.lights, results);
  7278. this._getDescendants(this._scene.cameras, results);
  7279. return results;
  7280. };
  7281. Node.prototype._setReady = function (state) {
  7282. if (state == this._isReady) {
  7283. return;
  7284. }
  7285. if (!state) {
  7286. this._isReady = false;
  7287. return;
  7288. }
  7289. this._isReady = true;
  7290. if (this.onReady) {
  7291. this.onReady(this);
  7292. }
  7293. };
  7294. return Node;
  7295. })();
  7296. BABYLON.Node = Node;
  7297. })(BABYLON || (BABYLON = {}));
  7298. var BABYLON;
  7299. (function (BABYLON) {
  7300. var FilesInput = (function () {
  7301. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7302. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7303. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7304. this._engine = p_engine;
  7305. this._canvas = p_canvas;
  7306. this._currentScene = p_scene;
  7307. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7308. this._progressCallback = p_progressCallback;
  7309. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7310. this._textureLoadingCallback = p_textureLoadingCallback;
  7311. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7312. }
  7313. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7314. var _this = this;
  7315. if (p_elementToMonitor) {
  7316. this._elementToMonitor = p_elementToMonitor;
  7317. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7318. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7319. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7320. }
  7321. };
  7322. FilesInput.prototype.renderFunction = function () {
  7323. if (this._additionnalRenderLoopLogicCallback) {
  7324. this._additionnalRenderLoopLogicCallback();
  7325. }
  7326. if (this._currentScene) {
  7327. if (this._textureLoadingCallback) {
  7328. var remaining = this._currentScene.getWaitingItemsCount();
  7329. if (remaining > 0) {
  7330. this._textureLoadingCallback(remaining);
  7331. }
  7332. }
  7333. this._currentScene.render();
  7334. }
  7335. };
  7336. FilesInput.prototype.drag = function (e) {
  7337. e.stopPropagation();
  7338. e.preventDefault();
  7339. };
  7340. FilesInput.prototype.drop = function (eventDrop) {
  7341. eventDrop.stopPropagation();
  7342. eventDrop.preventDefault();
  7343. this.loadFiles(eventDrop);
  7344. };
  7345. FilesInput.prototype.loadFiles = function (event) {
  7346. if (this._startingProcessingFilesCallback)
  7347. this._startingProcessingFilesCallback();
  7348. // Handling data transfer via drag'n'drop
  7349. if (event && event.dataTransfer && event.dataTransfer.files) {
  7350. this._filesToLoad = event.dataTransfer.files;
  7351. }
  7352. // Handling files from input files
  7353. if (event && event.target && event.target.files) {
  7354. this._filesToLoad = event.target.files;
  7355. }
  7356. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7357. for (var i = 0; i < this._filesToLoad.length; i++) {
  7358. switch (this._filesToLoad[i].type) {
  7359. case "image/jpeg":
  7360. case "image/png":
  7361. case "image/bmp":
  7362. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7363. break;
  7364. case "image/targa":
  7365. case "image/vnd.ms-dds":
  7366. case "audio/wav":
  7367. case "audio/x-wav":
  7368. case "audio/mp3":
  7369. case "audio/mpeg":
  7370. case "audio/mpeg3":
  7371. case "audio/x-mpeg-3":
  7372. case "audio/ogg":
  7373. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7374. break;
  7375. default:
  7376. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7377. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7378. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7379. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7380. this._sceneFileToLoad = this._filesToLoad[i];
  7381. }
  7382. break;
  7383. }
  7384. }
  7385. this.reload();
  7386. }
  7387. };
  7388. FilesInput.prototype.reload = function () {
  7389. var _this = this;
  7390. var that = this;
  7391. // If a ".babylon" file has been provided
  7392. if (this._sceneFileToLoad) {
  7393. if (this._currentScene) {
  7394. if (BABYLON.Tools.errorsCount > 0) {
  7395. BABYLON.Tools.ClearLogCache();
  7396. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7397. }
  7398. this._engine.stopRenderLoop();
  7399. this._currentScene.dispose();
  7400. }
  7401. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7402. that._currentScene = newScene;
  7403. // Wait for textures and shaders to be ready
  7404. that._currentScene.executeWhenReady(function () {
  7405. // Attach camera to canvas inputs
  7406. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7407. that._currentScene.createDefaultCameraOrLight();
  7408. }
  7409. that._currentScene.activeCamera.attachControl(that._canvas);
  7410. if (that._sceneLoadedCallback) {
  7411. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7412. }
  7413. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7414. });
  7415. }, function (progress) {
  7416. if (_this._progressCallback) {
  7417. _this._progressCallback(progress);
  7418. }
  7419. });
  7420. }
  7421. else {
  7422. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7423. }
  7424. };
  7425. FilesInput.FilesTextures = new Array();
  7426. FilesInput.FilesToLoad = new Array();
  7427. return FilesInput;
  7428. })();
  7429. BABYLON.FilesInput = FilesInput;
  7430. })(BABYLON || (BABYLON = {}));
  7431. var BABYLON;
  7432. (function (BABYLON) {
  7433. var IntersectionInfo = (function () {
  7434. function IntersectionInfo(bu, bv, distance) {
  7435. this.bu = bu;
  7436. this.bv = bv;
  7437. this.distance = distance;
  7438. this.faceId = 0;
  7439. this.subMeshId = 0;
  7440. }
  7441. return IntersectionInfo;
  7442. })();
  7443. BABYLON.IntersectionInfo = IntersectionInfo;
  7444. var PickingInfo = (function () {
  7445. function PickingInfo() {
  7446. this.hit = false;
  7447. this.distance = 0;
  7448. this.pickedPoint = null;
  7449. this.pickedMesh = null;
  7450. this.bu = 0;
  7451. this.bv = 0;
  7452. this.faceId = -1;
  7453. this.subMeshId = 0;
  7454. }
  7455. // Methods
  7456. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7457. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7458. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7459. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7460. return null;
  7461. }
  7462. var indices = this.pickedMesh.getIndices();
  7463. var result;
  7464. if (useVerticesNormals) {
  7465. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7466. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7467. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7468. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7469. normal0 = normal0.scale(this.bu);
  7470. normal1 = normal1.scale(this.bv);
  7471. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7472. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7473. }
  7474. else {
  7475. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7476. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7477. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7478. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7479. var p1p2 = vertex1.subtract(vertex2);
  7480. var p3p2 = vertex3.subtract(vertex2);
  7481. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7482. }
  7483. if (useWorldCoordinates) {
  7484. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7485. }
  7486. return BABYLON.Vector3.Normalize(result);
  7487. };
  7488. PickingInfo.prototype.getTextureCoordinates = function () {
  7489. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7490. return null;
  7491. }
  7492. var indices = this.pickedMesh.getIndices();
  7493. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7494. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7495. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7496. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7497. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7498. uv1 = uv1.scale(this.bu);
  7499. uv2 = uv2.scale(this.bv);
  7500. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7501. };
  7502. return PickingInfo;
  7503. })();
  7504. BABYLON.PickingInfo = PickingInfo;
  7505. })(BABYLON || (BABYLON = {}));
  7506. var BABYLON;
  7507. (function (BABYLON) {
  7508. var BoundingSphere = (function () {
  7509. function BoundingSphere(minimum, maximum) {
  7510. this.minimum = minimum;
  7511. this.maximum = maximum;
  7512. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7513. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7514. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7515. this.radius = distance * 0.5;
  7516. this.centerWorld = BABYLON.Vector3.Zero();
  7517. this._update(BABYLON.Matrix.Identity());
  7518. }
  7519. // Methods
  7520. BoundingSphere.prototype._update = function (world) {
  7521. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7522. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7523. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7524. };
  7525. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7526. for (var i = 0; i < 6; i++) {
  7527. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7528. return false;
  7529. }
  7530. return true;
  7531. };
  7532. BoundingSphere.prototype.intersectsPoint = function (point) {
  7533. var x = this.centerWorld.x - point.x;
  7534. var y = this.centerWorld.y - point.y;
  7535. var z = this.centerWorld.z - point.z;
  7536. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7537. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7538. return false;
  7539. return true;
  7540. };
  7541. // Statics
  7542. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7543. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7544. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7545. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7546. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7547. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7548. return false;
  7549. return true;
  7550. };
  7551. return BoundingSphere;
  7552. })();
  7553. BABYLON.BoundingSphere = BoundingSphere;
  7554. })(BABYLON || (BABYLON = {}));
  7555. var BABYLON;
  7556. (function (BABYLON) {
  7557. var BoundingBox = (function () {
  7558. function BoundingBox(minimum, maximum) {
  7559. this.minimum = minimum;
  7560. this.maximum = maximum;
  7561. this.vectors = new Array();
  7562. this.vectorsWorld = new Array();
  7563. // Bounding vectors
  7564. this.vectors.push(this.minimum.clone());
  7565. this.vectors.push(this.maximum.clone());
  7566. this.vectors.push(this.minimum.clone());
  7567. this.vectors[2].x = this.maximum.x;
  7568. this.vectors.push(this.minimum.clone());
  7569. this.vectors[3].y = this.maximum.y;
  7570. this.vectors.push(this.minimum.clone());
  7571. this.vectors[4].z = this.maximum.z;
  7572. this.vectors.push(this.maximum.clone());
  7573. this.vectors[5].z = this.minimum.z;
  7574. this.vectors.push(this.maximum.clone());
  7575. this.vectors[6].x = this.minimum.x;
  7576. this.vectors.push(this.maximum.clone());
  7577. this.vectors[7].y = this.minimum.y;
  7578. // OBB
  7579. this.center = this.maximum.add(this.minimum).scale(0.5);
  7580. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7581. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7582. // World
  7583. for (var index = 0; index < this.vectors.length; index++) {
  7584. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7585. }
  7586. this.minimumWorld = BABYLON.Vector3.Zero();
  7587. this.maximumWorld = BABYLON.Vector3.Zero();
  7588. this._update(BABYLON.Matrix.Identity());
  7589. }
  7590. // Methods
  7591. BoundingBox.prototype.getWorldMatrix = function () {
  7592. return this._worldMatrix;
  7593. };
  7594. BoundingBox.prototype._update = function (world) {
  7595. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7596. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7597. for (var index = 0; index < this.vectors.length; index++) {
  7598. var v = this.vectorsWorld[index];
  7599. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7600. if (v.x < this.minimumWorld.x)
  7601. this.minimumWorld.x = v.x;
  7602. if (v.y < this.minimumWorld.y)
  7603. this.minimumWorld.y = v.y;
  7604. if (v.z < this.minimumWorld.z)
  7605. this.minimumWorld.z = v.z;
  7606. if (v.x > this.maximumWorld.x)
  7607. this.maximumWorld.x = v.x;
  7608. if (v.y > this.maximumWorld.y)
  7609. this.maximumWorld.y = v.y;
  7610. if (v.z > this.maximumWorld.z)
  7611. this.maximumWorld.z = v.z;
  7612. }
  7613. // OBB
  7614. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7615. this.center.scaleInPlace(0.5);
  7616. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7617. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7618. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7619. this._worldMatrix = world;
  7620. };
  7621. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7622. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7623. };
  7624. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7625. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7626. };
  7627. BoundingBox.prototype.intersectsPoint = function (point) {
  7628. var delta = -BABYLON.Engine.Epsilon;
  7629. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7630. return false;
  7631. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7632. return false;
  7633. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7634. return false;
  7635. return true;
  7636. };
  7637. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7638. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7639. };
  7640. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7641. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7642. return false;
  7643. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7644. return false;
  7645. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7646. return false;
  7647. return true;
  7648. };
  7649. // Statics
  7650. BoundingBox.Intersects = function (box0, box1) {
  7651. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7652. return false;
  7653. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7654. return false;
  7655. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7656. return false;
  7657. return true;
  7658. };
  7659. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7660. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7661. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7662. return (num <= (sphereRadius * sphereRadius));
  7663. };
  7664. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7665. for (var p = 0; p < 6; p++) {
  7666. for (var i = 0; i < 8; i++) {
  7667. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7668. return false;
  7669. }
  7670. }
  7671. }
  7672. return true;
  7673. };
  7674. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7675. for (var p = 0; p < 6; p++) {
  7676. var inCount = 8;
  7677. for (var i = 0; i < 8; i++) {
  7678. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7679. --inCount;
  7680. }
  7681. else {
  7682. break;
  7683. }
  7684. }
  7685. if (inCount === 0)
  7686. return false;
  7687. }
  7688. return true;
  7689. };
  7690. return BoundingBox;
  7691. })();
  7692. BABYLON.BoundingBox = BoundingBox;
  7693. })(BABYLON || (BABYLON = {}));
  7694. var BABYLON;
  7695. (function (BABYLON) {
  7696. var computeBoxExtents = function (axis, box) {
  7697. var p = BABYLON.Vector3.Dot(box.center, axis);
  7698. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7699. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7700. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7701. var r = r0 + r1 + r2;
  7702. return {
  7703. min: p - r,
  7704. max: p + r
  7705. };
  7706. };
  7707. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7708. var axisOverlap = function (axis, box0, box1) {
  7709. var result0 = computeBoxExtents(axis, box0);
  7710. var result1 = computeBoxExtents(axis, box1);
  7711. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7712. };
  7713. var BoundingInfo = (function () {
  7714. function BoundingInfo(minimum, maximum) {
  7715. this.minimum = minimum;
  7716. this.maximum = maximum;
  7717. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7718. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7719. }
  7720. // Methods
  7721. BoundingInfo.prototype._update = function (world) {
  7722. this.boundingBox._update(world);
  7723. this.boundingSphere._update(world);
  7724. };
  7725. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7726. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7727. return false;
  7728. return this.boundingBox.isInFrustum(frustumPlanes);
  7729. };
  7730. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7731. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7732. };
  7733. BoundingInfo.prototype._checkCollision = function (collider) {
  7734. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7735. };
  7736. BoundingInfo.prototype.intersectsPoint = function (point) {
  7737. if (!this.boundingSphere.centerWorld) {
  7738. return false;
  7739. }
  7740. if (!this.boundingSphere.intersectsPoint(point)) {
  7741. return false;
  7742. }
  7743. if (!this.boundingBox.intersectsPoint(point)) {
  7744. return false;
  7745. }
  7746. return true;
  7747. };
  7748. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7749. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7750. return false;
  7751. }
  7752. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7753. return false;
  7754. }
  7755. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7756. return false;
  7757. }
  7758. if (!precise) {
  7759. return true;
  7760. }
  7761. var box0 = this.boundingBox;
  7762. var box1 = boundingInfo.boundingBox;
  7763. if (!axisOverlap(box0.directions[0], box0, box1))
  7764. return false;
  7765. if (!axisOverlap(box0.directions[1], box0, box1))
  7766. return false;
  7767. if (!axisOverlap(box0.directions[2], box0, box1))
  7768. return false;
  7769. if (!axisOverlap(box1.directions[0], box0, box1))
  7770. return false;
  7771. if (!axisOverlap(box1.directions[1], box0, box1))
  7772. return false;
  7773. if (!axisOverlap(box1.directions[2], box0, box1))
  7774. return false;
  7775. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7776. return false;
  7777. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7778. return false;
  7779. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7780. return false;
  7781. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7782. return false;
  7783. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7784. return false;
  7785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7786. return false;
  7787. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7788. return false;
  7789. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7790. return false;
  7791. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7792. return false;
  7793. return true;
  7794. };
  7795. return BoundingInfo;
  7796. })();
  7797. BABYLON.BoundingInfo = BoundingInfo;
  7798. })(BABYLON || (BABYLON = {}));
  7799. var BABYLON;
  7800. (function (BABYLON) {
  7801. var AbstractMesh = (function (_super) {
  7802. __extends(AbstractMesh, _super);
  7803. function AbstractMesh(name, scene) {
  7804. var _this = this;
  7805. _super.call(this, name, scene);
  7806. // Properties
  7807. this.definedFacingForward = true; // orientation for POV movement & rotation
  7808. this.position = new BABYLON.Vector3(0, 0, 0);
  7809. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7810. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7811. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7812. this.visibility = 1.0;
  7813. this.alphaIndex = Number.MAX_VALUE;
  7814. this.infiniteDistance = false;
  7815. this.isVisible = true;
  7816. this.isPickable = true;
  7817. this.showBoundingBox = false;
  7818. this.showSubMeshesBoundingBox = false;
  7819. this.onDispose = null;
  7820. this.isBlocker = false;
  7821. this.renderingGroupId = 0;
  7822. this.receiveShadows = false;
  7823. this.renderOutline = false;
  7824. this.outlineColor = BABYLON.Color3.Red();
  7825. this.outlineWidth = 0.02;
  7826. this.renderOverlay = false;
  7827. this.overlayColor = BABYLON.Color3.Red();
  7828. this.overlayAlpha = 0.5;
  7829. this.hasVertexAlpha = false;
  7830. this.useVertexColors = true;
  7831. this.applyFog = true;
  7832. this.computeBonesUsingShaders = true;
  7833. this.scalingDeterminant = 1;
  7834. this.useOctreeForRenderingSelection = true;
  7835. this.useOctreeForPicking = true;
  7836. this.useOctreeForCollisions = true;
  7837. this.layerMask = 0x0FFFFFFF;
  7838. this.alwaysSelectAsActiveMesh = false;
  7839. // Physics
  7840. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7841. // Collisions
  7842. this._checkCollisions = false;
  7843. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7844. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7845. this._collider = new BABYLON.Collider();
  7846. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7847. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7848. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7849. // Edges
  7850. this.edgesWidth = 1;
  7851. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7852. // Cache
  7853. this._localScaling = BABYLON.Matrix.Zero();
  7854. this._localRotation = BABYLON.Matrix.Zero();
  7855. this._localTranslation = BABYLON.Matrix.Zero();
  7856. this._localBillboard = BABYLON.Matrix.Zero();
  7857. this._localPivotScaling = BABYLON.Matrix.Zero();
  7858. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7859. this._localWorld = BABYLON.Matrix.Zero();
  7860. this._worldMatrix = BABYLON.Matrix.Zero();
  7861. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7862. this._absolutePosition = BABYLON.Vector3.Zero();
  7863. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7864. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7865. this._isDirty = false;
  7866. this._pivotMatrix = BABYLON.Matrix.Identity();
  7867. this._isDisposed = false;
  7868. this._renderId = 0;
  7869. this._intersectionsInProgress = new Array();
  7870. this._onAfterWorldMatrixUpdate = new Array();
  7871. this._isWorldMatrixFrozen = false;
  7872. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7873. if (collidedMesh === void 0) { collidedMesh = null; }
  7874. //TODO move this to the collision coordinator!
  7875. if (_this.getScene().workerCollisions)
  7876. newPosition.multiplyInPlace(_this._collider.radius);
  7877. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7878. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7879. _this.position.addInPlace(_this._diffPositionForCollisions);
  7880. }
  7881. if (_this.onCollide && collidedMesh) {
  7882. _this.onCollide(collidedMesh);
  7883. }
  7884. };
  7885. scene.addMesh(this);
  7886. }
  7887. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7888. get: function () {
  7889. return AbstractMesh._BILLBOARDMODE_NONE;
  7890. },
  7891. enumerable: true,
  7892. configurable: true
  7893. });
  7894. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7895. get: function () {
  7896. return AbstractMesh._BILLBOARDMODE_X;
  7897. },
  7898. enumerable: true,
  7899. configurable: true
  7900. });
  7901. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7902. get: function () {
  7903. return AbstractMesh._BILLBOARDMODE_Y;
  7904. },
  7905. enumerable: true,
  7906. configurable: true
  7907. });
  7908. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7909. get: function () {
  7910. return AbstractMesh._BILLBOARDMODE_Z;
  7911. },
  7912. enumerable: true,
  7913. configurable: true
  7914. });
  7915. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7916. get: function () {
  7917. return AbstractMesh._BILLBOARDMODE_ALL;
  7918. },
  7919. enumerable: true,
  7920. configurable: true
  7921. });
  7922. // Methods
  7923. AbstractMesh.prototype.disableEdgesRendering = function () {
  7924. if (this._edgesRenderer !== undefined) {
  7925. this._edgesRenderer.dispose();
  7926. this._edgesRenderer = undefined;
  7927. }
  7928. };
  7929. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7930. if (epsilon === void 0) { epsilon = 0.95; }
  7931. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7932. this.disableEdgesRendering();
  7933. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7934. };
  7935. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7936. get: function () {
  7937. return false;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. AbstractMesh.prototype.getLOD = function (camera) {
  7943. return this;
  7944. };
  7945. AbstractMesh.prototype.getTotalVertices = function () {
  7946. return 0;
  7947. };
  7948. AbstractMesh.prototype.getIndices = function () {
  7949. return null;
  7950. };
  7951. AbstractMesh.prototype.getVerticesData = function (kind) {
  7952. return null;
  7953. };
  7954. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7955. return false;
  7956. };
  7957. AbstractMesh.prototype.getBoundingInfo = function () {
  7958. if (this._masterMesh) {
  7959. return this._masterMesh.getBoundingInfo();
  7960. }
  7961. if (!this._boundingInfo) {
  7962. this._updateBoundingInfo();
  7963. }
  7964. return this._boundingInfo;
  7965. };
  7966. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7967. get: function () {
  7968. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7969. },
  7970. enumerable: true,
  7971. configurable: true
  7972. });
  7973. AbstractMesh.prototype._preActivate = function () {
  7974. };
  7975. AbstractMesh.prototype._activate = function (renderId) {
  7976. this._renderId = renderId;
  7977. };
  7978. AbstractMesh.prototype.getWorldMatrix = function () {
  7979. if (this._masterMesh) {
  7980. return this._masterMesh.getWorldMatrix();
  7981. }
  7982. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7983. this.computeWorldMatrix();
  7984. }
  7985. return this._worldMatrix;
  7986. };
  7987. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7988. get: function () {
  7989. return this._worldMatrix;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7995. get: function () {
  7996. return this._absolutePosition;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8002. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8003. this.computeWorldMatrix(true);
  8004. this._isWorldMatrixFrozen = true;
  8005. };
  8006. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8007. this._isWorldMatrixFrozen = false;
  8008. this.computeWorldMatrix(true);
  8009. };
  8010. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8011. get: function () {
  8012. return this._isWorldMatrixFrozen;
  8013. },
  8014. enumerable: true,
  8015. configurable: true
  8016. });
  8017. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8018. axis.normalize();
  8019. if (!this.rotationQuaternion) {
  8020. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8021. this.rotation = BABYLON.Vector3.Zero();
  8022. }
  8023. var rotationQuaternion;
  8024. if (!space || space === BABYLON.Space.LOCAL) {
  8025. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8026. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8027. }
  8028. else {
  8029. if (this.parent) {
  8030. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8031. invertParentWorldMatrix.invert();
  8032. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8033. }
  8034. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8035. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8036. }
  8037. };
  8038. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8039. var displacementVector = axis.scale(distance);
  8040. if (!space || space === BABYLON.Space.LOCAL) {
  8041. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8042. this.setPositionWithLocalVector(tempV3);
  8043. }
  8044. else {
  8045. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8046. }
  8047. };
  8048. AbstractMesh.prototype.getAbsolutePosition = function () {
  8049. this.computeWorldMatrix();
  8050. return this._absolutePosition;
  8051. };
  8052. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8053. if (!absolutePosition) {
  8054. return;
  8055. }
  8056. var absolutePositionX;
  8057. var absolutePositionY;
  8058. var absolutePositionZ;
  8059. if (absolutePosition.x === undefined) {
  8060. if (arguments.length < 3) {
  8061. return;
  8062. }
  8063. absolutePositionX = arguments[0];
  8064. absolutePositionY = arguments[1];
  8065. absolutePositionZ = arguments[2];
  8066. }
  8067. else {
  8068. absolutePositionX = absolutePosition.x;
  8069. absolutePositionY = absolutePosition.y;
  8070. absolutePositionZ = absolutePosition.z;
  8071. }
  8072. if (this.parent) {
  8073. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8074. invertParentWorldMatrix.invert();
  8075. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8076. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8077. }
  8078. else {
  8079. this.position.x = absolutePositionX;
  8080. this.position.y = absolutePositionY;
  8081. this.position.z = absolutePositionZ;
  8082. }
  8083. };
  8084. // ================================== Point of View Movement =================================
  8085. /**
  8086. * Perform relative position change from the point of view of behind the front of the mesh.
  8087. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8088. * Supports definition of mesh facing forward or backward.
  8089. * @param {number} amountRight
  8090. * @param {number} amountUp
  8091. * @param {number} amountForward
  8092. */
  8093. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8094. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8095. };
  8096. /**
  8097. * Calculate relative position change from the point of view of behind the front of the mesh.
  8098. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8099. * Supports definition of mesh facing forward or backward.
  8100. * @param {number} amountRight
  8101. * @param {number} amountUp
  8102. * @param {number} amountForward
  8103. */
  8104. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8105. var rotMatrix = new BABYLON.Matrix();
  8106. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8107. rotQuaternion.toRotationMatrix(rotMatrix);
  8108. var translationDelta = BABYLON.Vector3.Zero();
  8109. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8111. return translationDelta;
  8112. };
  8113. // ================================== Point of View Rotation =================================
  8114. /**
  8115. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8116. * Supports definition of mesh facing forward or backward.
  8117. * @param {number} flipBack
  8118. * @param {number} twirlClockwise
  8119. * @param {number} tiltRight
  8120. */
  8121. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8122. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8123. };
  8124. /**
  8125. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8126. * Supports definition of mesh facing forward or backward.
  8127. * @param {number} flipBack
  8128. * @param {number} twirlClockwise
  8129. * @param {number} tiltRight
  8130. */
  8131. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8132. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8133. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8134. };
  8135. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8136. this._pivotMatrix = matrix;
  8137. this._cache.pivotMatrixUpdated = true;
  8138. };
  8139. AbstractMesh.prototype.getPivotMatrix = function () {
  8140. return this._pivotMatrix;
  8141. };
  8142. AbstractMesh.prototype._isSynchronized = function () {
  8143. if (this._isDirty) {
  8144. return false;
  8145. }
  8146. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8147. return false;
  8148. if (this._cache.pivotMatrixUpdated) {
  8149. return false;
  8150. }
  8151. if (this.infiniteDistance) {
  8152. return false;
  8153. }
  8154. if (!this._cache.position.equals(this.position))
  8155. return false;
  8156. if (this.rotationQuaternion) {
  8157. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8158. return false;
  8159. }
  8160. else {
  8161. if (!this._cache.rotation.equals(this.rotation))
  8162. return false;
  8163. }
  8164. if (!this._cache.scaling.equals(this.scaling))
  8165. return false;
  8166. return true;
  8167. };
  8168. AbstractMesh.prototype._initCache = function () {
  8169. _super.prototype._initCache.call(this);
  8170. this._cache.localMatrixUpdated = false;
  8171. this._cache.position = BABYLON.Vector3.Zero();
  8172. this._cache.scaling = BABYLON.Vector3.Zero();
  8173. this._cache.rotation = BABYLON.Vector3.Zero();
  8174. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8175. };
  8176. AbstractMesh.prototype.markAsDirty = function (property) {
  8177. if (property === "rotation") {
  8178. this.rotationQuaternion = null;
  8179. }
  8180. this._currentRenderId = Number.MAX_VALUE;
  8181. this._isDirty = true;
  8182. };
  8183. AbstractMesh.prototype._updateBoundingInfo = function () {
  8184. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8185. this._boundingInfo._update(this.worldMatrixFromCache);
  8186. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8187. };
  8188. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8189. if (!this.subMeshes) {
  8190. return;
  8191. }
  8192. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8193. var subMesh = this.subMeshes[subIndex];
  8194. subMesh.updateBoundingInfo(matrix);
  8195. }
  8196. };
  8197. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8198. if (this._isWorldMatrixFrozen) {
  8199. return this._worldMatrix;
  8200. }
  8201. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8202. return this._worldMatrix;
  8203. }
  8204. this._cache.position.copyFrom(this.position);
  8205. this._cache.scaling.copyFrom(this.scaling);
  8206. this._cache.pivotMatrixUpdated = false;
  8207. this._currentRenderId = this.getScene().getRenderId();
  8208. this._isDirty = false;
  8209. // Scaling
  8210. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  8211. // Rotation
  8212. if (this.rotationQuaternion) {
  8213. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8214. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8215. }
  8216. else {
  8217. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8218. this._cache.rotation.copyFrom(this.rotation);
  8219. }
  8220. // Translation
  8221. if (this.infiniteDistance && !this.parent) {
  8222. var camera = this.getScene().activeCamera;
  8223. if (camera) {
  8224. var cameraWorldMatrix = camera.getWorldMatrix();
  8225. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8226. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8227. }
  8228. }
  8229. else {
  8230. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8231. }
  8232. // Composing transformations
  8233. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8234. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8235. // Billboarding
  8236. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8237. var localPosition = this.position.clone();
  8238. var zero = this.getScene().activeCamera.globalPosition.clone();
  8239. if (this.parent && this.parent.position) {
  8240. localPosition.addInPlace(this.parent.position);
  8241. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8242. }
  8243. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8244. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8245. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8246. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8247. zero.y = localPosition.y + 0.001;
  8248. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8249. zero.z = localPosition.z + 0.001;
  8250. }
  8251. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8252. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8253. this._localBillboard.invert();
  8254. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8255. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8256. }
  8257. // Local world
  8258. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8259. // Parent
  8260. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8261. this._markSyncedWithParent();
  8262. if (this._meshToBoneReferal) {
  8263. if (!this._localMeshReferalTransform) {
  8264. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8265. }
  8266. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8267. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8268. }
  8269. else {
  8270. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8271. }
  8272. }
  8273. else {
  8274. this._worldMatrix.copyFrom(this._localWorld);
  8275. }
  8276. // Bounding info
  8277. this._updateBoundingInfo();
  8278. // Absolute position
  8279. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8280. // Callbacks
  8281. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8282. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8283. }
  8284. return this._worldMatrix;
  8285. };
  8286. /**
  8287. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8288. * @param func: callback function to add
  8289. */
  8290. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8291. this._onAfterWorldMatrixUpdate.push(func);
  8292. };
  8293. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8294. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8295. if (index > -1) {
  8296. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8297. }
  8298. };
  8299. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8300. this.computeWorldMatrix();
  8301. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8302. };
  8303. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8304. this.computeWorldMatrix();
  8305. var invLocalWorldMatrix = this._localWorld.clone();
  8306. invLocalWorldMatrix.invert();
  8307. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8308. };
  8309. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8310. this.computeWorldMatrix(true);
  8311. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8312. };
  8313. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8314. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8315. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8316. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8317. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8318. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8319. /// <returns>Mesh oriented towards targetMesh</returns>
  8320. yawCor = yawCor || 0; // default to zero if undefined
  8321. pitchCor = pitchCor || 0;
  8322. rollCor = rollCor || 0;
  8323. var dv = targetPoint.subtract(this.position);
  8324. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8325. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8326. var pitch = Math.atan2(dv.y, len);
  8327. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8328. };
  8329. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8330. this._meshToBoneReferal = affectedMesh;
  8331. this.parent = bone;
  8332. if (bone.getWorldMatrix().determinant() < 0) {
  8333. this.scalingDeterminant *= -1;
  8334. }
  8335. };
  8336. AbstractMesh.prototype.detachFromBone = function () {
  8337. if (this.parent.getWorldMatrix().determinant() < 0) {
  8338. this.scalingDeterminant *= -1;
  8339. }
  8340. this._meshToBoneReferal = null;
  8341. this.parent = null;
  8342. };
  8343. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8344. return this._boundingInfo.isInFrustum(frustumPlanes);
  8345. };
  8346. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8347. if (!camera) {
  8348. camera = this.getScene().activeCamera;
  8349. }
  8350. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8351. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8352. return false;
  8353. }
  8354. return true;
  8355. };
  8356. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8357. if (!this._boundingInfo || !mesh._boundingInfo) {
  8358. return false;
  8359. }
  8360. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8361. };
  8362. AbstractMesh.prototype.intersectsPoint = function (point) {
  8363. if (!this._boundingInfo) {
  8364. return false;
  8365. }
  8366. return this._boundingInfo.intersectsPoint(point);
  8367. };
  8368. // Physics
  8369. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8370. var physicsEngine = this.getScene().getPhysicsEngine();
  8371. if (!physicsEngine) {
  8372. return null;
  8373. }
  8374. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8375. if (impostor.impostor) {
  8376. // Old API
  8377. options = impostor;
  8378. impostor = impostor.impostor;
  8379. }
  8380. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8381. physicsEngine._unregisterMesh(this);
  8382. return null;
  8383. }
  8384. if (!options) {
  8385. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8386. }
  8387. else {
  8388. if (!options.mass && options.mass !== 0)
  8389. options.mass = 0;
  8390. if (!options.friction && options.friction !== 0)
  8391. options.friction = 0.2;
  8392. if (!options.restitution && options.restitution !== 0)
  8393. options.restitution = 0.2;
  8394. }
  8395. this._physicImpostor = impostor;
  8396. this._physicsMass = options.mass;
  8397. this._physicsFriction = options.friction;
  8398. this._physicRestitution = options.restitution;
  8399. return physicsEngine._registerMesh(this, impostor, options);
  8400. };
  8401. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8402. if (!this._physicImpostor) {
  8403. return BABYLON.PhysicsEngine.NoImpostor;
  8404. }
  8405. return this._physicImpostor;
  8406. };
  8407. AbstractMesh.prototype.getPhysicsMass = function () {
  8408. if (!this._physicsMass) {
  8409. return 0;
  8410. }
  8411. return this._physicsMass;
  8412. };
  8413. AbstractMesh.prototype.getPhysicsFriction = function () {
  8414. if (!this._physicsFriction) {
  8415. return 0;
  8416. }
  8417. return this._physicsFriction;
  8418. };
  8419. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8420. if (!this._physicRestitution) {
  8421. return 0;
  8422. }
  8423. return this._physicRestitution;
  8424. };
  8425. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8426. if (!camera) {
  8427. camera = this.getScene().activeCamera;
  8428. }
  8429. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8430. };
  8431. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8432. if (!camera) {
  8433. camera = this.getScene().activeCamera;
  8434. }
  8435. return this.absolutePosition.subtract(camera.position).length();
  8436. };
  8437. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8438. if (!this._physicImpostor) {
  8439. return;
  8440. }
  8441. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8442. };
  8443. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8444. if (!this._physicImpostor) {
  8445. return;
  8446. }
  8447. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8448. };
  8449. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8450. if (!this._physicImpostor) {
  8451. return;
  8452. }
  8453. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8454. };
  8455. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8456. // Collisions
  8457. get: function () {
  8458. return this._checkCollisions;
  8459. },
  8460. set: function (collisionEnabled) {
  8461. this._checkCollisions = collisionEnabled;
  8462. if (this.getScene().workerCollisions) {
  8463. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8464. }
  8465. },
  8466. enumerable: true,
  8467. configurable: true
  8468. });
  8469. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8470. var globalPosition = this.getAbsolutePosition();
  8471. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8472. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8473. this._collider.radius = this.ellipsoid;
  8474. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8475. };
  8476. // Submeshes octree
  8477. /**
  8478. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8479. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8480. */
  8481. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8482. if (maxCapacity === void 0) { maxCapacity = 64; }
  8483. if (maxDepth === void 0) { maxDepth = 2; }
  8484. if (!this._submeshesOctree) {
  8485. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8486. }
  8487. this.computeWorldMatrix(true);
  8488. // Update octree
  8489. var bbox = this.getBoundingInfo().boundingBox;
  8490. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8491. return this._submeshesOctree;
  8492. };
  8493. // Collisions
  8494. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8495. this._generatePointsArray();
  8496. // Transformation
  8497. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8498. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8499. subMesh._lastColliderWorldVertices = [];
  8500. subMesh._trianglePlanes = [];
  8501. var start = subMesh.verticesStart;
  8502. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8503. for (var i = start; i < end; i++) {
  8504. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8505. }
  8506. }
  8507. // Collide
  8508. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8509. if (collider.collisionFound) {
  8510. collider.collidedMesh = this;
  8511. }
  8512. };
  8513. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8514. var subMeshes;
  8515. var len;
  8516. // Octrees
  8517. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8518. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8519. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8520. len = intersections.length;
  8521. subMeshes = intersections.data;
  8522. }
  8523. else {
  8524. subMeshes = this.subMeshes;
  8525. len = subMeshes.length;
  8526. }
  8527. for (var index = 0; index < len; index++) {
  8528. var subMesh = subMeshes[index];
  8529. // Bounding test
  8530. if (len > 1 && !subMesh._checkCollision(collider))
  8531. continue;
  8532. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8533. }
  8534. };
  8535. AbstractMesh.prototype._checkCollision = function (collider) {
  8536. // Bounding box test
  8537. if (!this._boundingInfo._checkCollision(collider))
  8538. return;
  8539. // Transformation matrix
  8540. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8541. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8542. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8543. };
  8544. // Picking
  8545. AbstractMesh.prototype._generatePointsArray = function () {
  8546. return false;
  8547. };
  8548. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8549. var pickingInfo = new BABYLON.PickingInfo();
  8550. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8551. return pickingInfo;
  8552. }
  8553. if (!this._generatePointsArray()) {
  8554. return pickingInfo;
  8555. }
  8556. var intersectInfo = null;
  8557. // Octrees
  8558. var subMeshes;
  8559. var len;
  8560. if (this._submeshesOctree && this.useOctreeForPicking) {
  8561. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8562. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8563. len = intersections.length;
  8564. subMeshes = intersections.data;
  8565. }
  8566. else {
  8567. subMeshes = this.subMeshes;
  8568. len = subMeshes.length;
  8569. }
  8570. for (var index = 0; index < len; index++) {
  8571. var subMesh = subMeshes[index];
  8572. // Bounding test
  8573. if (len > 1 && !subMesh.canIntersects(ray))
  8574. continue;
  8575. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8576. if (currentIntersectInfo) {
  8577. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8578. intersectInfo = currentIntersectInfo;
  8579. intersectInfo.subMeshId = index;
  8580. if (fastCheck) {
  8581. break;
  8582. }
  8583. }
  8584. }
  8585. }
  8586. if (intersectInfo) {
  8587. // Get picked point
  8588. var world = this.getWorldMatrix();
  8589. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8590. var direction = ray.direction.clone();
  8591. direction = direction.scale(intersectInfo.distance);
  8592. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8593. var pickedPoint = worldOrigin.add(worldDirection);
  8594. // Return result
  8595. pickingInfo.hit = true;
  8596. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8597. pickingInfo.pickedPoint = pickedPoint;
  8598. pickingInfo.pickedMesh = this;
  8599. pickingInfo.bu = intersectInfo.bu;
  8600. pickingInfo.bv = intersectInfo.bv;
  8601. pickingInfo.faceId = intersectInfo.faceId;
  8602. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8603. return pickingInfo;
  8604. }
  8605. return pickingInfo;
  8606. };
  8607. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8608. return null;
  8609. };
  8610. AbstractMesh.prototype.releaseSubMeshes = function () {
  8611. if (this.subMeshes) {
  8612. while (this.subMeshes.length) {
  8613. this.subMeshes[0].dispose();
  8614. }
  8615. }
  8616. else {
  8617. this.subMeshes = new Array();
  8618. }
  8619. };
  8620. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8621. var index;
  8622. // Physics
  8623. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8624. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8625. }
  8626. // Intersections in progress
  8627. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8628. var other = this._intersectionsInProgress[index];
  8629. var pos = other._intersectionsInProgress.indexOf(this);
  8630. other._intersectionsInProgress.splice(pos, 1);
  8631. }
  8632. this._intersectionsInProgress = [];
  8633. // Edges
  8634. if (this._edgesRenderer) {
  8635. this._edgesRenderer.dispose();
  8636. this._edgesRenderer = null;
  8637. }
  8638. // SubMeshes
  8639. this.releaseSubMeshes();
  8640. // Remove from scene
  8641. this.getScene().removeMesh(this);
  8642. if (!doNotRecurse) {
  8643. // Particles
  8644. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8645. if (this.getScene().particleSystems[index].emitter === this) {
  8646. this.getScene().particleSystems[index].dispose();
  8647. index--;
  8648. }
  8649. }
  8650. // Children
  8651. var objects = this.getScene().meshes.slice(0);
  8652. for (index = 0; index < objects.length; index++) {
  8653. if (objects[index].parent === this) {
  8654. objects[index].dispose();
  8655. }
  8656. }
  8657. }
  8658. else {
  8659. for (index = 0; index < this.getScene().meshes.length; index++) {
  8660. var obj = this.getScene().meshes[index];
  8661. if (obj.parent === this) {
  8662. obj.parent = null;
  8663. obj.computeWorldMatrix(true);
  8664. }
  8665. }
  8666. }
  8667. this._onAfterWorldMatrixUpdate = [];
  8668. this._isDisposed = true;
  8669. // Callback
  8670. if (this.onDispose) {
  8671. this.onDispose();
  8672. }
  8673. };
  8674. // Statics
  8675. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8676. AbstractMesh._BILLBOARDMODE_X = 1;
  8677. AbstractMesh._BILLBOARDMODE_Y = 2;
  8678. AbstractMesh._BILLBOARDMODE_Z = 4;
  8679. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8680. return AbstractMesh;
  8681. })(BABYLON.Node);
  8682. BABYLON.AbstractMesh = AbstractMesh;
  8683. })(BABYLON || (BABYLON = {}));
  8684. var BABYLON;
  8685. (function (BABYLON) {
  8686. var Light = (function (_super) {
  8687. __extends(Light, _super);
  8688. function Light(name, scene) {
  8689. _super.call(this, name, scene);
  8690. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8691. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8692. this.intensity = 1.0;
  8693. this.range = Number.MAX_VALUE;
  8694. this.includeOnlyWithLayerMask = 0;
  8695. this.includedOnlyMeshes = new Array();
  8696. this.excludedMeshes = new Array();
  8697. this.excludeWithLayerMask = 0;
  8698. this._excludedMeshesIds = new Array();
  8699. this._includedOnlyMeshesIds = new Array();
  8700. scene.addLight(this);
  8701. }
  8702. Light.prototype.getShadowGenerator = function () {
  8703. return this._shadowGenerator;
  8704. };
  8705. Light.prototype.getAbsolutePosition = function () {
  8706. return BABYLON.Vector3.Zero();
  8707. };
  8708. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8709. };
  8710. Light.prototype._getWorldMatrix = function () {
  8711. return BABYLON.Matrix.Identity();
  8712. };
  8713. Light.prototype.canAffectMesh = function (mesh) {
  8714. if (!mesh) {
  8715. return true;
  8716. }
  8717. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8718. return false;
  8719. }
  8720. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8721. return false;
  8722. }
  8723. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8724. return false;
  8725. }
  8726. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8727. return false;
  8728. }
  8729. return true;
  8730. };
  8731. Light.prototype.getWorldMatrix = function () {
  8732. this._currentRenderId = this.getScene().getRenderId();
  8733. var worldMatrix = this._getWorldMatrix();
  8734. if (this.parent && this.parent.getWorldMatrix) {
  8735. if (!this._parentedWorldMatrix) {
  8736. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8737. }
  8738. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8739. this._markSyncedWithParent();
  8740. return this._parentedWorldMatrix;
  8741. }
  8742. return worldMatrix;
  8743. };
  8744. Light.prototype.dispose = function () {
  8745. if (this._shadowGenerator) {
  8746. this._shadowGenerator.dispose();
  8747. this._shadowGenerator = null;
  8748. }
  8749. // Remove from scene
  8750. this.getScene().removeLight(this);
  8751. };
  8752. return Light;
  8753. })(BABYLON.Node);
  8754. BABYLON.Light = Light;
  8755. })(BABYLON || (BABYLON = {}));
  8756. var BABYLON;
  8757. (function (BABYLON) {
  8758. var PointLight = (function (_super) {
  8759. __extends(PointLight, _super);
  8760. function PointLight(name, position, scene) {
  8761. _super.call(this, name, scene);
  8762. this.position = position;
  8763. }
  8764. PointLight.prototype.getAbsolutePosition = function () {
  8765. return this._transformedPosition ? this._transformedPosition : this.position;
  8766. };
  8767. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8768. if (this.parent && this.parent.getWorldMatrix) {
  8769. if (!this._transformedPosition) {
  8770. this._transformedPosition = BABYLON.Vector3.Zero();
  8771. }
  8772. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8773. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8774. return;
  8775. }
  8776. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8777. };
  8778. PointLight.prototype.getShadowGenerator = function () {
  8779. return null;
  8780. };
  8781. PointLight.prototype._getWorldMatrix = function () {
  8782. if (!this._worldMatrix) {
  8783. this._worldMatrix = BABYLON.Matrix.Identity();
  8784. }
  8785. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8786. return this._worldMatrix;
  8787. };
  8788. return PointLight;
  8789. })(BABYLON.Light);
  8790. BABYLON.PointLight = PointLight;
  8791. })(BABYLON || (BABYLON = {}));
  8792. var BABYLON;
  8793. (function (BABYLON) {
  8794. var SpotLight = (function (_super) {
  8795. __extends(SpotLight, _super);
  8796. function SpotLight(name, position, direction, angle, exponent, scene) {
  8797. _super.call(this, name, scene);
  8798. this.position = position;
  8799. this.direction = direction;
  8800. this.angle = angle;
  8801. this.exponent = exponent;
  8802. }
  8803. SpotLight.prototype.getAbsolutePosition = function () {
  8804. return this.transformedPosition ? this.transformedPosition : this.position;
  8805. };
  8806. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8807. var activeCamera = this.getScene().activeCamera;
  8808. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8809. };
  8810. SpotLight.prototype.supportsVSM = function () {
  8811. return true;
  8812. };
  8813. SpotLight.prototype.needRefreshPerFrame = function () {
  8814. return false;
  8815. };
  8816. SpotLight.prototype.setDirectionToTarget = function (target) {
  8817. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8818. return this.direction;
  8819. };
  8820. SpotLight.prototype.computeTransformedPosition = function () {
  8821. if (this.parent && this.parent.getWorldMatrix) {
  8822. if (!this.transformedPosition) {
  8823. this.transformedPosition = BABYLON.Vector3.Zero();
  8824. }
  8825. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8826. return true;
  8827. }
  8828. return false;
  8829. };
  8830. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8831. var normalizeDirection;
  8832. if (this.parent && this.parent.getWorldMatrix) {
  8833. if (!this._transformedDirection) {
  8834. this._transformedDirection = BABYLON.Vector3.Zero();
  8835. }
  8836. this.computeTransformedPosition();
  8837. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8838. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8839. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8840. }
  8841. else {
  8842. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8843. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8844. }
  8845. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8846. };
  8847. SpotLight.prototype._getWorldMatrix = function () {
  8848. if (!this._worldMatrix) {
  8849. this._worldMatrix = BABYLON.Matrix.Identity();
  8850. }
  8851. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8852. return this._worldMatrix;
  8853. };
  8854. return SpotLight;
  8855. })(BABYLON.Light);
  8856. BABYLON.SpotLight = SpotLight;
  8857. })(BABYLON || (BABYLON = {}));
  8858. var BABYLON;
  8859. (function (BABYLON) {
  8860. var HemisphericLight = (function (_super) {
  8861. __extends(HemisphericLight, _super);
  8862. function HemisphericLight(name, direction, scene) {
  8863. _super.call(this, name, scene);
  8864. this.direction = direction;
  8865. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8866. }
  8867. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8868. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8869. return this.direction;
  8870. };
  8871. HemisphericLight.prototype.getShadowGenerator = function () {
  8872. return null;
  8873. };
  8874. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8875. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8876. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8877. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8878. };
  8879. HemisphericLight.prototype._getWorldMatrix = function () {
  8880. if (!this._worldMatrix) {
  8881. this._worldMatrix = BABYLON.Matrix.Identity();
  8882. }
  8883. return this._worldMatrix;
  8884. };
  8885. return HemisphericLight;
  8886. })(BABYLON.Light);
  8887. BABYLON.HemisphericLight = HemisphericLight;
  8888. })(BABYLON || (BABYLON = {}));
  8889. var BABYLON;
  8890. (function (BABYLON) {
  8891. var DirectionalLight = (function (_super) {
  8892. __extends(DirectionalLight, _super);
  8893. function DirectionalLight(name, direction, scene) {
  8894. _super.call(this, name, scene);
  8895. this.direction = direction;
  8896. this.shadowOrthoScale = 0.5;
  8897. this.position = direction.scale(-1);
  8898. }
  8899. DirectionalLight.prototype.getAbsolutePosition = function () {
  8900. return this.transformedPosition ? this.transformedPosition : this.position;
  8901. };
  8902. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8903. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8904. return this.direction;
  8905. };
  8906. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8907. var orthoLeft = Number.MAX_VALUE;
  8908. var orthoRight = Number.MIN_VALUE;
  8909. var orthoTop = Number.MIN_VALUE;
  8910. var orthoBottom = Number.MAX_VALUE;
  8911. var tempVector3 = BABYLON.Vector3.Zero();
  8912. var activeCamera = this.getScene().activeCamera;
  8913. // Check extends
  8914. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8915. var mesh = renderList[meshIndex];
  8916. if (!mesh) {
  8917. continue;
  8918. }
  8919. var boundingInfo = mesh.getBoundingInfo();
  8920. if (!boundingInfo) {
  8921. continue;
  8922. }
  8923. var boundingBox = boundingInfo.boundingBox;
  8924. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8925. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8926. if (tempVector3.x < orthoLeft)
  8927. orthoLeft = tempVector3.x;
  8928. if (tempVector3.y < orthoBottom)
  8929. orthoBottom = tempVector3.y;
  8930. if (tempVector3.x > orthoRight)
  8931. orthoRight = tempVector3.x;
  8932. if (tempVector3.y > orthoTop)
  8933. orthoTop = tempVector3.y;
  8934. }
  8935. }
  8936. var xOffset = orthoRight - orthoLeft;
  8937. var yOffset = orthoTop - orthoBottom;
  8938. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8939. };
  8940. DirectionalLight.prototype.supportsVSM = function () {
  8941. return true;
  8942. };
  8943. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8944. return true;
  8945. };
  8946. DirectionalLight.prototype.computeTransformedPosition = function () {
  8947. if (this.parent && this.parent.getWorldMatrix) {
  8948. if (!this.transformedPosition) {
  8949. this.transformedPosition = BABYLON.Vector3.Zero();
  8950. }
  8951. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8952. return true;
  8953. }
  8954. return false;
  8955. };
  8956. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8957. if (this.parent && this.parent.getWorldMatrix) {
  8958. if (!this._transformedDirection) {
  8959. this._transformedDirection = BABYLON.Vector3.Zero();
  8960. }
  8961. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8962. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8963. return;
  8964. }
  8965. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8966. };
  8967. DirectionalLight.prototype._getWorldMatrix = function () {
  8968. if (!this._worldMatrix) {
  8969. this._worldMatrix = BABYLON.Matrix.Identity();
  8970. }
  8971. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8972. return this._worldMatrix;
  8973. };
  8974. return DirectionalLight;
  8975. })(BABYLON.Light);
  8976. BABYLON.DirectionalLight = DirectionalLight;
  8977. })(BABYLON || (BABYLON = {}));
  8978. var BABYLON;
  8979. (function (BABYLON) {
  8980. var ShadowGenerator = (function () {
  8981. function ShadowGenerator(mapSize, light) {
  8982. var _this = this;
  8983. // Members
  8984. this._filter = ShadowGenerator.FILTER_NONE;
  8985. this.blurScale = 2;
  8986. this._blurBoxOffset = 0;
  8987. this._bias = 0.00005;
  8988. this._lightDirection = BABYLON.Vector3.Zero();
  8989. this._darkness = 0;
  8990. this._transparencyShadow = false;
  8991. this._viewMatrix = BABYLON.Matrix.Zero();
  8992. this._projectionMatrix = BABYLON.Matrix.Zero();
  8993. this._transformMatrix = BABYLON.Matrix.Zero();
  8994. this._worldViewProjection = BABYLON.Matrix.Zero();
  8995. this._light = light;
  8996. this._scene = light.getScene();
  8997. this._mapSize = mapSize;
  8998. light._shadowGenerator = this;
  8999. // Render target
  9000. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  9001. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9002. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9003. this._shadowMap.anisotropicFilteringLevel = 1;
  9004. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9005. this._shadowMap.renderParticles = false;
  9006. this._shadowMap.onAfterUnbind = function () {
  9007. if (!_this.useBlurVarianceShadowMap) {
  9008. return;
  9009. }
  9010. if (!_this._shadowMap2) {
  9011. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9012. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9013. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9014. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9015. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9016. _this._downSamplePostprocess.onApply = function (effect) {
  9017. effect.setTexture("textureSampler", _this._shadowMap);
  9018. };
  9019. _this.blurBoxOffset = 1;
  9020. }
  9021. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9022. };
  9023. // Custom render function
  9024. var renderSubMesh = function (subMesh) {
  9025. var mesh = subMesh.getRenderingMesh();
  9026. var scene = _this._scene;
  9027. var engine = scene.getEngine();
  9028. // Culling
  9029. engine.setState(subMesh.getMaterial().backFaceCulling);
  9030. // Managing instances
  9031. var batch = mesh._getInstancesRenderList(subMesh._id);
  9032. if (batch.mustReturn) {
  9033. return;
  9034. }
  9035. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  9036. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9037. engine.enableEffect(_this._effect);
  9038. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9039. var material = subMesh.getMaterial();
  9040. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9041. // Alpha test
  9042. if (material && material.needAlphaTesting()) {
  9043. var alphaTexture = material.getAlphaTestTexture();
  9044. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9045. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9046. }
  9047. // Bones
  9048. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9049. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  9050. }
  9051. // Draw
  9052. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9053. }
  9054. else {
  9055. // Need to reset refresh rate of the shadowMap
  9056. _this._shadowMap.resetRefreshCounter();
  9057. }
  9058. };
  9059. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9060. var index;
  9061. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9062. renderSubMesh(opaqueSubMeshes.data[index]);
  9063. }
  9064. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9065. renderSubMesh(alphaTestSubMeshes.data[index]);
  9066. }
  9067. if (_this._transparencyShadow) {
  9068. for (index = 0; index < transparentSubMeshes.length; index++) {
  9069. renderSubMesh(transparentSubMeshes.data[index]);
  9070. }
  9071. }
  9072. };
  9073. this._shadowMap.onClear = function (engine) {
  9074. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9075. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9076. }
  9077. else {
  9078. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9079. }
  9080. };
  9081. }
  9082. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9083. // Static
  9084. get: function () {
  9085. return ShadowGenerator._FILTER_NONE;
  9086. },
  9087. enumerable: true,
  9088. configurable: true
  9089. });
  9090. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9091. get: function () {
  9092. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9093. },
  9094. enumerable: true,
  9095. configurable: true
  9096. });
  9097. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9098. get: function () {
  9099. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9100. },
  9101. enumerable: true,
  9102. configurable: true
  9103. });
  9104. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9105. get: function () {
  9106. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9107. },
  9108. enumerable: true,
  9109. configurable: true
  9110. });
  9111. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9112. get: function () {
  9113. return this._bias;
  9114. },
  9115. set: function (bias) {
  9116. this._bias = bias;
  9117. },
  9118. enumerable: true,
  9119. configurable: true
  9120. });
  9121. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9122. get: function () {
  9123. return this._blurBoxOffset;
  9124. },
  9125. set: function (value) {
  9126. var _this = this;
  9127. if (this._blurBoxOffset === value) {
  9128. return;
  9129. }
  9130. this._blurBoxOffset = value;
  9131. if (this._boxBlurPostprocess) {
  9132. this._boxBlurPostprocess.dispose();
  9133. }
  9134. 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);
  9135. this._boxBlurPostprocess.onApply = function (effect) {
  9136. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9137. };
  9138. },
  9139. enumerable: true,
  9140. configurable: true
  9141. });
  9142. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9143. get: function () {
  9144. return this._filter;
  9145. },
  9146. set: function (value) {
  9147. if (this._filter === value) {
  9148. return;
  9149. }
  9150. this._filter = value;
  9151. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9152. this._shadowMap.anisotropicFilteringLevel = 16;
  9153. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9154. }
  9155. else {
  9156. this._shadowMap.anisotropicFilteringLevel = 1;
  9157. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9158. }
  9159. },
  9160. enumerable: true,
  9161. configurable: true
  9162. });
  9163. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9164. get: function () {
  9165. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9166. },
  9167. set: function (value) {
  9168. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9169. },
  9170. enumerable: true,
  9171. configurable: true
  9172. });
  9173. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9174. get: function () {
  9175. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9176. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9177. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9178. },
  9179. set: function (value) {
  9180. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9181. },
  9182. enumerable: true,
  9183. configurable: true
  9184. });
  9185. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9186. get: function () {
  9187. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9188. },
  9189. set: function (value) {
  9190. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9191. },
  9192. enumerable: true,
  9193. configurable: true
  9194. });
  9195. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9196. var defines = [];
  9197. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9198. defines.push("#define VSM");
  9199. }
  9200. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9201. var mesh = subMesh.getMesh();
  9202. var material = subMesh.getMaterial();
  9203. // Alpha test
  9204. if (material && material.needAlphaTesting()) {
  9205. defines.push("#define ALPHATEST");
  9206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9207. attribs.push(BABYLON.VertexBuffer.UVKind);
  9208. defines.push("#define UV1");
  9209. }
  9210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9211. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9212. defines.push("#define UV2");
  9213. }
  9214. }
  9215. // Bones
  9216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9219. defines.push("#define BONES");
  9220. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9221. }
  9222. // Instances
  9223. if (useInstances) {
  9224. defines.push("#define INSTANCES");
  9225. attribs.push("world0");
  9226. attribs.push("world1");
  9227. attribs.push("world2");
  9228. attribs.push("world3");
  9229. }
  9230. // Get correct effect
  9231. var join = defines.join("\n");
  9232. if (this._cachedDefines !== join) {
  9233. this._cachedDefines = join;
  9234. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9235. }
  9236. return this._effect.isReady();
  9237. };
  9238. ShadowGenerator.prototype.getShadowMap = function () {
  9239. return this._shadowMap;
  9240. };
  9241. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9242. if (this._shadowMap2) {
  9243. return this._shadowMap2;
  9244. }
  9245. return this._shadowMap;
  9246. };
  9247. ShadowGenerator.prototype.getLight = function () {
  9248. return this._light;
  9249. };
  9250. // Methods
  9251. ShadowGenerator.prototype.getTransformMatrix = function () {
  9252. var scene = this._scene;
  9253. if (this._currentRenderID === scene.getRenderId()) {
  9254. return this._transformMatrix;
  9255. }
  9256. this._currentRenderID = scene.getRenderId();
  9257. var lightPosition = this._light.position;
  9258. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9259. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9260. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9261. }
  9262. if (this._light.computeTransformedPosition()) {
  9263. lightPosition = this._light.transformedPosition;
  9264. }
  9265. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9266. this._cachedPosition = lightPosition.clone();
  9267. this._cachedDirection = this._lightDirection.clone();
  9268. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9269. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9270. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9271. }
  9272. return this._transformMatrix;
  9273. };
  9274. ShadowGenerator.prototype.getDarkness = function () {
  9275. return this._darkness;
  9276. };
  9277. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9278. if (darkness >= 1.0)
  9279. this._darkness = 1.0;
  9280. else if (darkness <= 0.0)
  9281. this._darkness = 0.0;
  9282. else
  9283. this._darkness = darkness;
  9284. };
  9285. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9286. this._transparencyShadow = hasShadow;
  9287. };
  9288. ShadowGenerator.prototype._packHalf = function (depth) {
  9289. var scale = depth * 255.0;
  9290. var fract = scale - Math.floor(scale);
  9291. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9292. };
  9293. ShadowGenerator.prototype.dispose = function () {
  9294. this._shadowMap.dispose();
  9295. if (this._shadowMap2) {
  9296. this._shadowMap2.dispose();
  9297. }
  9298. if (this._downSamplePostprocess) {
  9299. this._downSamplePostprocess.dispose();
  9300. }
  9301. if (this._boxBlurPostprocess) {
  9302. this._boxBlurPostprocess.dispose();
  9303. }
  9304. };
  9305. ShadowGenerator._FILTER_NONE = 0;
  9306. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9307. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9308. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9309. return ShadowGenerator;
  9310. })();
  9311. BABYLON.ShadowGenerator = ShadowGenerator;
  9312. })(BABYLON || (BABYLON = {}));
  9313. var BABYLON;
  9314. (function (BABYLON) {
  9315. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9316. if (boxMin.x > sphereCenter.x + sphereRadius)
  9317. return false;
  9318. if (sphereCenter.x - sphereRadius > boxMax.x)
  9319. return false;
  9320. if (boxMin.y > sphereCenter.y + sphereRadius)
  9321. return false;
  9322. if (sphereCenter.y - sphereRadius > boxMax.y)
  9323. return false;
  9324. if (boxMin.z > sphereCenter.z + sphereRadius)
  9325. return false;
  9326. if (sphereCenter.z - sphereRadius > boxMax.z)
  9327. return false;
  9328. return true;
  9329. };
  9330. var getLowestRoot = function (a, b, c, maxR) {
  9331. var determinant = b * b - 4.0 * a * c;
  9332. var result = { root: 0, found: false };
  9333. if (determinant < 0)
  9334. return result;
  9335. var sqrtD = Math.sqrt(determinant);
  9336. var r1 = (-b - sqrtD) / (2.0 * a);
  9337. var r2 = (-b + sqrtD) / (2.0 * a);
  9338. if (r1 > r2) {
  9339. var temp = r2;
  9340. r2 = r1;
  9341. r1 = temp;
  9342. }
  9343. if (r1 > 0 && r1 < maxR) {
  9344. result.root = r1;
  9345. result.found = true;
  9346. return result;
  9347. }
  9348. if (r2 > 0 && r2 < maxR) {
  9349. result.root = r2;
  9350. result.found = true;
  9351. return result;
  9352. }
  9353. return result;
  9354. };
  9355. var Collider = (function () {
  9356. function Collider() {
  9357. this.radius = new BABYLON.Vector3(1, 1, 1);
  9358. this.retry = 0;
  9359. this.basePointWorld = BABYLON.Vector3.Zero();
  9360. this.velocityWorld = BABYLON.Vector3.Zero();
  9361. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9362. this._collisionPoint = BABYLON.Vector3.Zero();
  9363. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9364. this._tempVector = BABYLON.Vector3.Zero();
  9365. this._tempVector2 = BABYLON.Vector3.Zero();
  9366. this._tempVector3 = BABYLON.Vector3.Zero();
  9367. this._tempVector4 = BABYLON.Vector3.Zero();
  9368. this._edge = BABYLON.Vector3.Zero();
  9369. this._baseToVertex = BABYLON.Vector3.Zero();
  9370. this._destinationPoint = BABYLON.Vector3.Zero();
  9371. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9372. this._displacementVector = BABYLON.Vector3.Zero();
  9373. }
  9374. // Methods
  9375. Collider.prototype._initialize = function (source, dir, e) {
  9376. this.velocity = dir;
  9377. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9378. this.basePoint = source;
  9379. source.multiplyToRef(this.radius, this.basePointWorld);
  9380. dir.multiplyToRef(this.radius, this.velocityWorld);
  9381. this.velocityWorldLength = this.velocityWorld.length();
  9382. this.epsilon = e;
  9383. this.collisionFound = false;
  9384. };
  9385. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9386. pa.subtractToRef(point, this._tempVector);
  9387. pb.subtractToRef(point, this._tempVector2);
  9388. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9389. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9390. if (d < 0)
  9391. return false;
  9392. pc.subtractToRef(point, this._tempVector3);
  9393. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9394. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9395. if (d < 0)
  9396. return false;
  9397. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9398. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9399. return d >= 0;
  9400. };
  9401. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9402. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9403. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9404. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9405. return false;
  9406. }
  9407. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9408. return false;
  9409. return true;
  9410. };
  9411. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9412. var t0;
  9413. var embeddedInPlane = false;
  9414. //defensive programming, actually not needed.
  9415. if (!trianglePlaneArray) {
  9416. trianglePlaneArray = [];
  9417. }
  9418. if (!trianglePlaneArray[faceIndex]) {
  9419. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9420. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9421. }
  9422. var trianglePlane = trianglePlaneArray[faceIndex];
  9423. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9424. return;
  9425. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9426. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9427. if (normalDotVelocity == 0) {
  9428. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9429. return;
  9430. embeddedInPlane = true;
  9431. t0 = 0;
  9432. }
  9433. else {
  9434. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9435. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9436. if (t0 > t1) {
  9437. var temp = t1;
  9438. t1 = t0;
  9439. t0 = temp;
  9440. }
  9441. if (t0 > 1.0 || t1 < 0.0)
  9442. return;
  9443. if (t0 < 0)
  9444. t0 = 0;
  9445. if (t0 > 1.0)
  9446. t0 = 1.0;
  9447. }
  9448. this._collisionPoint.copyFromFloats(0, 0, 0);
  9449. var found = false;
  9450. var t = 1.0;
  9451. if (!embeddedInPlane) {
  9452. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9453. this.velocity.scaleToRef(t0, this._tempVector);
  9454. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9455. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9456. found = true;
  9457. t = t0;
  9458. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9459. }
  9460. }
  9461. if (!found) {
  9462. var velocitySquaredLength = this.velocity.lengthSquared();
  9463. var a = velocitySquaredLength;
  9464. this.basePoint.subtractToRef(p1, this._tempVector);
  9465. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9466. var c = this._tempVector.lengthSquared() - 1.0;
  9467. var lowestRoot = getLowestRoot(a, b, c, t);
  9468. if (lowestRoot.found) {
  9469. t = lowestRoot.root;
  9470. found = true;
  9471. this._collisionPoint.copyFrom(p1);
  9472. }
  9473. this.basePoint.subtractToRef(p2, this._tempVector);
  9474. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9475. c = this._tempVector.lengthSquared() - 1.0;
  9476. lowestRoot = getLowestRoot(a, b, c, t);
  9477. if (lowestRoot.found) {
  9478. t = lowestRoot.root;
  9479. found = true;
  9480. this._collisionPoint.copyFrom(p2);
  9481. }
  9482. this.basePoint.subtractToRef(p3, this._tempVector);
  9483. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9484. c = this._tempVector.lengthSquared() - 1.0;
  9485. lowestRoot = getLowestRoot(a, b, c, t);
  9486. if (lowestRoot.found) {
  9487. t = lowestRoot.root;
  9488. found = true;
  9489. this._collisionPoint.copyFrom(p3);
  9490. }
  9491. p2.subtractToRef(p1, this._edge);
  9492. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9493. var edgeSquaredLength = this._edge.lengthSquared();
  9494. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9495. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9496. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9497. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9498. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9499. lowestRoot = getLowestRoot(a, b, c, t);
  9500. if (lowestRoot.found) {
  9501. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9502. if (f >= 0.0 && f <= 1.0) {
  9503. t = lowestRoot.root;
  9504. found = true;
  9505. this._edge.scaleInPlace(f);
  9506. p1.addToRef(this._edge, this._collisionPoint);
  9507. }
  9508. }
  9509. p3.subtractToRef(p2, this._edge);
  9510. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9511. edgeSquaredLength = this._edge.lengthSquared();
  9512. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9513. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9514. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9515. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9516. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9517. lowestRoot = getLowestRoot(a, b, c, t);
  9518. if (lowestRoot.found) {
  9519. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9520. if (f >= 0.0 && f <= 1.0) {
  9521. t = lowestRoot.root;
  9522. found = true;
  9523. this._edge.scaleInPlace(f);
  9524. p2.addToRef(this._edge, this._collisionPoint);
  9525. }
  9526. }
  9527. p1.subtractToRef(p3, this._edge);
  9528. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9529. edgeSquaredLength = this._edge.lengthSquared();
  9530. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9531. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9532. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9533. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9534. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9535. lowestRoot = getLowestRoot(a, b, c, t);
  9536. if (lowestRoot.found) {
  9537. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9538. if (f >= 0.0 && f <= 1.0) {
  9539. t = lowestRoot.root;
  9540. found = true;
  9541. this._edge.scaleInPlace(f);
  9542. p3.addToRef(this._edge, this._collisionPoint);
  9543. }
  9544. }
  9545. }
  9546. if (found) {
  9547. var distToCollision = t * this.velocity.length();
  9548. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9549. if (!this.intersectionPoint) {
  9550. this.intersectionPoint = this._collisionPoint.clone();
  9551. }
  9552. else {
  9553. this.intersectionPoint.copyFrom(this._collisionPoint);
  9554. }
  9555. this.nearestDistance = distToCollision;
  9556. this.collisionFound = true;
  9557. }
  9558. }
  9559. };
  9560. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9561. for (var i = indexStart; i < indexEnd; i += 3) {
  9562. var p1 = pts[indices[i] - decal];
  9563. var p2 = pts[indices[i + 1] - decal];
  9564. var p3 = pts[indices[i + 2] - decal];
  9565. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9566. }
  9567. };
  9568. Collider.prototype._getResponse = function (pos, vel) {
  9569. pos.addToRef(vel, this._destinationPoint);
  9570. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9571. this.basePoint.addToRef(vel, pos);
  9572. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9573. this._slidePlaneNormal.normalize();
  9574. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9575. pos.addInPlace(this._displacementVector);
  9576. this.intersectionPoint.addInPlace(this._displacementVector);
  9577. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9578. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9579. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9580. };
  9581. return Collider;
  9582. })();
  9583. BABYLON.Collider = Collider;
  9584. })(BABYLON || (BABYLON = {}));
  9585. var BABYLON;
  9586. (function (BABYLON) {
  9587. //WebWorker code will be inserted to this variable.
  9588. BABYLON.CollisionWorker = "";
  9589. (function (WorkerTaskType) {
  9590. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9591. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9592. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9593. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9594. var WorkerTaskType = BABYLON.WorkerTaskType;
  9595. (function (WorkerReplyType) {
  9596. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9597. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9598. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9599. var WorkerReplyType = BABYLON.WorkerReplyType;
  9600. var CollisionCoordinatorWorker = (function () {
  9601. function CollisionCoordinatorWorker() {
  9602. var _this = this;
  9603. this._scaledPosition = BABYLON.Vector3.Zero();
  9604. this._scaledVelocity = BABYLON.Vector3.Zero();
  9605. this.onMeshUpdated = function (mesh) {
  9606. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9607. };
  9608. this.onGeometryUpdated = function (geometry) {
  9609. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9610. };
  9611. this._afterRender = function () {
  9612. if (!_this._init)
  9613. return;
  9614. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9615. return;
  9616. }
  9617. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9618. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9619. if (_this._runningUpdated > 4) {
  9620. return;
  9621. }
  9622. ++_this._runningUpdated;
  9623. var payload = {
  9624. updatedMeshes: _this._addUpdateMeshesList,
  9625. updatedGeometries: _this._addUpdateGeometriesList,
  9626. removedGeometries: _this._toRemoveGeometryArray,
  9627. removedMeshes: _this._toRemoveMeshesArray
  9628. };
  9629. var message = {
  9630. payload: payload,
  9631. taskType: WorkerTaskType.UPDATE
  9632. };
  9633. var serializable = [];
  9634. for (var id in payload.updatedGeometries) {
  9635. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9636. //prepare transferables
  9637. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9638. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9639. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9640. }
  9641. }
  9642. _this._worker.postMessage(message, serializable);
  9643. _this._addUpdateMeshesList = {};
  9644. _this._addUpdateGeometriesList = {};
  9645. _this._toRemoveGeometryArray = [];
  9646. _this._toRemoveMeshesArray = [];
  9647. };
  9648. this._onMessageFromWorker = function (e) {
  9649. var returnData = e.data;
  9650. if (returnData.error != WorkerReplyType.SUCCESS) {
  9651. //TODO what errors can be returned from the worker?
  9652. BABYLON.Tools.Warn("error returned from worker!");
  9653. return;
  9654. }
  9655. switch (returnData.taskType) {
  9656. case WorkerTaskType.INIT:
  9657. _this._init = true;
  9658. //Update the worked with ALL of the scene's current state
  9659. _this._scene.meshes.forEach(function (mesh) {
  9660. _this.onMeshAdded(mesh);
  9661. });
  9662. _this._scene.getGeometries().forEach(function (geometry) {
  9663. _this.onGeometryAdded(geometry);
  9664. });
  9665. break;
  9666. case WorkerTaskType.UPDATE:
  9667. _this._runningUpdated--;
  9668. break;
  9669. case WorkerTaskType.COLLIDE:
  9670. _this._runningCollisionTask = false;
  9671. var returnPayload = returnData.payload;
  9672. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9673. return;
  9674. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9675. //cleanup
  9676. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9677. break;
  9678. }
  9679. };
  9680. this._collisionsCallbackArray = [];
  9681. this._init = false;
  9682. this._runningUpdated = 0;
  9683. this._runningCollisionTask = false;
  9684. this._addUpdateMeshesList = {};
  9685. this._addUpdateGeometriesList = {};
  9686. this._toRemoveGeometryArray = [];
  9687. this._toRemoveMeshesArray = [];
  9688. }
  9689. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9690. if (!this._init)
  9691. return;
  9692. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9693. return;
  9694. position.divideToRef(collider.radius, this._scaledPosition);
  9695. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9696. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9697. var payload = {
  9698. collider: {
  9699. position: this._scaledPosition.asArray(),
  9700. velocity: this._scaledVelocity.asArray(),
  9701. radius: collider.radius.asArray()
  9702. },
  9703. collisionId: collisionIndex,
  9704. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9705. maximumRetry: maximumRetry
  9706. };
  9707. var message = {
  9708. payload: payload,
  9709. taskType: WorkerTaskType.COLLIDE
  9710. };
  9711. this._worker.postMessage(message);
  9712. };
  9713. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9714. this._scene = scene;
  9715. this._scene.registerAfterRender(this._afterRender);
  9716. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9717. this._worker = new Worker(workerUrl);
  9718. this._worker.onmessage = this._onMessageFromWorker;
  9719. var message = {
  9720. payload: {},
  9721. taskType: WorkerTaskType.INIT
  9722. };
  9723. this._worker.postMessage(message);
  9724. };
  9725. CollisionCoordinatorWorker.prototype.destroy = function () {
  9726. this._scene.unregisterAfterRender(this._afterRender);
  9727. this._worker.terminate();
  9728. };
  9729. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9730. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9731. this.onMeshUpdated(mesh);
  9732. };
  9733. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9734. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9735. };
  9736. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9737. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9738. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9739. this.onGeometryUpdated(geometry);
  9740. };
  9741. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9742. this._toRemoveGeometryArray.push(geometry.id);
  9743. };
  9744. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9745. var submeshes = [];
  9746. if (mesh.subMeshes) {
  9747. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9748. return {
  9749. position: idx,
  9750. verticesStart: sm.verticesStart,
  9751. verticesCount: sm.verticesCount,
  9752. indexStart: sm.indexStart,
  9753. indexCount: sm.indexCount,
  9754. hasMaterial: !!sm.getMaterial(),
  9755. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9756. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9757. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9758. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9759. };
  9760. });
  9761. }
  9762. var geometryId = null;
  9763. if (mesh instanceof BABYLON.Mesh) {
  9764. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9765. }
  9766. else if (mesh instanceof BABYLON.InstancedMesh) {
  9767. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9768. }
  9769. return {
  9770. uniqueId: mesh.uniqueId,
  9771. id: mesh.id,
  9772. name: mesh.name,
  9773. geometryId: geometryId,
  9774. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9775. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9776. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9777. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9778. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9779. subMeshes: submeshes,
  9780. checkCollisions: mesh.checkCollisions
  9781. };
  9782. };
  9783. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9784. return {
  9785. id: geometry.id,
  9786. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9787. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9788. indices: new Int32Array(geometry.getIndices() || []),
  9789. };
  9790. };
  9791. return CollisionCoordinatorWorker;
  9792. })();
  9793. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9794. var CollisionCoordinatorLegacy = (function () {
  9795. function CollisionCoordinatorLegacy() {
  9796. this._scaledPosition = BABYLON.Vector3.Zero();
  9797. this._scaledVelocity = BABYLON.Vector3.Zero();
  9798. this._finalPosition = BABYLON.Vector3.Zero();
  9799. }
  9800. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9801. position.divideToRef(collider.radius, this._scaledPosition);
  9802. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9803. collider.collidedMesh = null;
  9804. collider.retry = 0;
  9805. collider.initialVelocity = this._scaledVelocity;
  9806. collider.initialPosition = this._scaledPosition;
  9807. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9808. this._finalPosition.multiplyInPlace(collider.radius);
  9809. //run the callback
  9810. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9811. };
  9812. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9813. this._scene = scene;
  9814. };
  9815. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9816. //Legacy need no destruction method.
  9817. };
  9818. //No update in legacy mode
  9819. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9820. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9821. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9822. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9823. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9824. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9825. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9826. if (excludedMesh === void 0) { excludedMesh = null; }
  9827. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9828. if (collider.retry >= maximumRetry) {
  9829. finalPosition.copyFrom(position);
  9830. return;
  9831. }
  9832. collider._initialize(position, velocity, closeDistance);
  9833. // Check all meshes
  9834. for (var index = 0; index < this._scene.meshes.length; index++) {
  9835. var mesh = this._scene.meshes[index];
  9836. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9837. mesh._checkCollision(collider);
  9838. }
  9839. }
  9840. if (!collider.collisionFound) {
  9841. position.addToRef(velocity, finalPosition);
  9842. return;
  9843. }
  9844. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9845. collider._getResponse(position, velocity);
  9846. }
  9847. if (velocity.length() <= closeDistance) {
  9848. finalPosition.copyFrom(position);
  9849. return;
  9850. }
  9851. collider.retry++;
  9852. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9853. };
  9854. return CollisionCoordinatorLegacy;
  9855. })();
  9856. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9857. })(BABYLON || (BABYLON = {}));
  9858. var BABYLON;
  9859. (function (BABYLON) {
  9860. var VRCameraMetrics = (function () {
  9861. function VRCameraMetrics() {
  9862. this.compensateDistortion = true;
  9863. }
  9864. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9865. get: function () {
  9866. return this.hResolution / (2 * this.vResolution);
  9867. },
  9868. enumerable: true,
  9869. configurable: true
  9870. });
  9871. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9872. get: function () {
  9873. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9874. },
  9875. enumerable: true,
  9876. configurable: true
  9877. });
  9878. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9879. get: function () {
  9880. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9881. var h = (4 * meters) / this.hScreenSize;
  9882. return BABYLON.Matrix.Translation(h, 0, 0);
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9888. get: function () {
  9889. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9890. var h = (4 * meters) / this.hScreenSize;
  9891. return BABYLON.Matrix.Translation(-h, 0, 0);
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9897. get: function () {
  9898. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9904. get: function () {
  9905. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. VRCameraMetrics.GetDefault = function () {
  9911. var result = new VRCameraMetrics();
  9912. result.hResolution = 1280;
  9913. result.vResolution = 800;
  9914. result.hScreenSize = 0.149759993;
  9915. result.vScreenSize = 0.0935999975;
  9916. result.vScreenCenter = 0.0467999987,
  9917. result.eyeToScreenDistance = 0.0410000011;
  9918. result.lensSeparationDistance = 0.0635000020;
  9919. result.interpupillaryDistance = 0.0640000030;
  9920. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9921. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9922. result.postProcessScaleFactor = 1.714605507808412;
  9923. result.lensCenterOffset = 0.151976421;
  9924. return result;
  9925. };
  9926. return VRCameraMetrics;
  9927. })();
  9928. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9929. var Camera = (function (_super) {
  9930. __extends(Camera, _super);
  9931. function Camera(name, position, scene) {
  9932. _super.call(this, name, scene);
  9933. this.position = position;
  9934. // Members
  9935. this.upVector = BABYLON.Vector3.Up();
  9936. this.orthoLeft = null;
  9937. this.orthoRight = null;
  9938. this.orthoBottom = null;
  9939. this.orthoTop = null;
  9940. this.fov = 0.8;
  9941. this.minZ = 1.0;
  9942. this.maxZ = 10000.0;
  9943. this.inertia = 0.9;
  9944. this.mode = Camera.PERSPECTIVE_CAMERA;
  9945. this.isIntermediate = false;
  9946. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9947. this.layerMask = 0x0FFFFFFF;
  9948. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9949. // Camera rig members
  9950. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9951. this._rigCameras = new Array();
  9952. // Cache
  9953. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9954. this._projectionMatrix = new BABYLON.Matrix();
  9955. this._postProcesses = new Array();
  9956. this._postProcessesTakenIndices = [];
  9957. this._activeMeshes = new BABYLON.SmartArray(256);
  9958. this._globalPosition = BABYLON.Vector3.Zero();
  9959. scene.addCamera(this);
  9960. if (!scene.activeCamera) {
  9961. scene.activeCamera = this;
  9962. }
  9963. }
  9964. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9965. get: function () {
  9966. return Camera._PERSPECTIVE_CAMERA;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9972. get: function () {
  9973. return Camera._ORTHOGRAPHIC_CAMERA;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9979. get: function () {
  9980. return Camera._FOVMODE_VERTICAL_FIXED;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9986. get: function () {
  9987. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9993. get: function () {
  9994. return Camera._RIG_MODE_NONE;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10000. get: function () {
  10001. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10007. get: function () {
  10008. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10014. get: function () {
  10015. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10016. },
  10017. enumerable: true,
  10018. configurable: true
  10019. });
  10020. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10021. get: function () {
  10022. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10028. get: function () {
  10029. return Camera._RIG_MODE_VR;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(Camera.prototype, "globalPosition", {
  10035. get: function () {
  10036. return this._globalPosition;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Camera.prototype.getActiveMeshes = function () {
  10042. return this._activeMeshes;
  10043. };
  10044. Camera.prototype.isActiveMesh = function (mesh) {
  10045. return (this._activeMeshes.indexOf(mesh) !== -1);
  10046. };
  10047. //Cache
  10048. Camera.prototype._initCache = function () {
  10049. _super.prototype._initCache.call(this);
  10050. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10051. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10052. this._cache.mode = undefined;
  10053. this._cache.minZ = undefined;
  10054. this._cache.maxZ = undefined;
  10055. this._cache.fov = undefined;
  10056. this._cache.aspectRatio = undefined;
  10057. this._cache.orthoLeft = undefined;
  10058. this._cache.orthoRight = undefined;
  10059. this._cache.orthoBottom = undefined;
  10060. this._cache.orthoTop = undefined;
  10061. this._cache.renderWidth = undefined;
  10062. this._cache.renderHeight = undefined;
  10063. };
  10064. Camera.prototype._updateCache = function (ignoreParentClass) {
  10065. if (!ignoreParentClass) {
  10066. _super.prototype._updateCache.call(this);
  10067. }
  10068. var engine = this.getEngine();
  10069. this._cache.position.copyFrom(this.position);
  10070. this._cache.upVector.copyFrom(this.upVector);
  10071. this._cache.mode = this.mode;
  10072. this._cache.minZ = this.minZ;
  10073. this._cache.maxZ = this.maxZ;
  10074. this._cache.fov = this.fov;
  10075. this._cache.aspectRatio = engine.getAspectRatio(this);
  10076. this._cache.orthoLeft = this.orthoLeft;
  10077. this._cache.orthoRight = this.orthoRight;
  10078. this._cache.orthoBottom = this.orthoBottom;
  10079. this._cache.orthoTop = this.orthoTop;
  10080. this._cache.renderWidth = engine.getRenderWidth();
  10081. this._cache.renderHeight = engine.getRenderHeight();
  10082. };
  10083. Camera.prototype._updateFromScene = function () {
  10084. this.updateCache();
  10085. this._update();
  10086. };
  10087. // Synchronized
  10088. Camera.prototype._isSynchronized = function () {
  10089. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10090. };
  10091. Camera.prototype._isSynchronizedViewMatrix = function () {
  10092. if (!_super.prototype._isSynchronized.call(this))
  10093. return false;
  10094. return this._cache.position.equals(this.position)
  10095. && this._cache.upVector.equals(this.upVector)
  10096. && this.isSynchronizedWithParent();
  10097. };
  10098. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10099. var check = this._cache.mode === this.mode
  10100. && this._cache.minZ === this.minZ
  10101. && this._cache.maxZ === this.maxZ;
  10102. if (!check) {
  10103. return false;
  10104. }
  10105. var engine = this.getEngine();
  10106. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10107. check = this._cache.fov === this.fov
  10108. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10109. }
  10110. else {
  10111. check = this._cache.orthoLeft === this.orthoLeft
  10112. && this._cache.orthoRight === this.orthoRight
  10113. && this._cache.orthoBottom === this.orthoBottom
  10114. && this._cache.orthoTop === this.orthoTop
  10115. && this._cache.renderWidth === engine.getRenderWidth()
  10116. && this._cache.renderHeight === engine.getRenderHeight();
  10117. }
  10118. return check;
  10119. };
  10120. // Controls
  10121. Camera.prototype.attachControl = function (element) {
  10122. };
  10123. Camera.prototype.detachControl = function (element) {
  10124. };
  10125. Camera.prototype._update = function () {
  10126. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10127. this._updateRigCameras();
  10128. }
  10129. this._checkInputs();
  10130. };
  10131. Camera.prototype._checkInputs = function () {
  10132. };
  10133. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10134. if (insertAt === void 0) { insertAt = null; }
  10135. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10136. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10137. return 0;
  10138. }
  10139. if (insertAt == null || insertAt < 0) {
  10140. this._postProcesses.push(postProcess);
  10141. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10142. return this._postProcesses.length - 1;
  10143. }
  10144. var add = 0;
  10145. var i;
  10146. var start;
  10147. if (this._postProcesses[insertAt]) {
  10148. start = this._postProcesses.length - 1;
  10149. for (i = start; i >= insertAt + 1; --i) {
  10150. this._postProcesses[i + 1] = this._postProcesses[i];
  10151. }
  10152. add = 1;
  10153. }
  10154. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10155. if (this._postProcessesTakenIndices[i] < insertAt) {
  10156. continue;
  10157. }
  10158. start = this._postProcessesTakenIndices.length - 1;
  10159. for (var j = start; j >= i; --j) {
  10160. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10161. }
  10162. this._postProcessesTakenIndices[i] = insertAt;
  10163. break;
  10164. }
  10165. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10166. this._postProcessesTakenIndices.push(insertAt);
  10167. }
  10168. var result = insertAt + add;
  10169. this._postProcesses[result] = postProcess;
  10170. return result;
  10171. };
  10172. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10173. if (atIndices === void 0) { atIndices = null; }
  10174. var result = [];
  10175. var i;
  10176. var index;
  10177. if (!atIndices) {
  10178. var length = this._postProcesses.length;
  10179. for (i = 0; i < length; i++) {
  10180. if (this._postProcesses[i] !== postProcess) {
  10181. continue;
  10182. }
  10183. delete this._postProcesses[i];
  10184. index = this._postProcessesTakenIndices.indexOf(i);
  10185. this._postProcessesTakenIndices.splice(index, 1);
  10186. }
  10187. }
  10188. else {
  10189. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10190. for (i = 0; i < atIndices.length; i++) {
  10191. var foundPostProcess = this._postProcesses[atIndices[i]];
  10192. if (foundPostProcess !== postProcess) {
  10193. result.push(i);
  10194. continue;
  10195. }
  10196. delete this._postProcesses[atIndices[i]];
  10197. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10198. this._postProcessesTakenIndices.splice(index, 1);
  10199. }
  10200. }
  10201. return result;
  10202. };
  10203. Camera.prototype.getWorldMatrix = function () {
  10204. if (!this._worldMatrix) {
  10205. this._worldMatrix = BABYLON.Matrix.Identity();
  10206. }
  10207. var viewMatrix = this.getViewMatrix();
  10208. viewMatrix.invertToRef(this._worldMatrix);
  10209. return this._worldMatrix;
  10210. };
  10211. Camera.prototype._getViewMatrix = function () {
  10212. return BABYLON.Matrix.Identity();
  10213. };
  10214. Camera.prototype.getViewMatrix = function (force) {
  10215. this._computedViewMatrix = this._computeViewMatrix(force);
  10216. if (!force && this._isSynchronizedViewMatrix()) {
  10217. return this._computedViewMatrix;
  10218. }
  10219. if (!this.parent || !this.parent.getWorldMatrix) {
  10220. this._globalPosition.copyFrom(this.position);
  10221. }
  10222. else {
  10223. if (!this._worldMatrix) {
  10224. this._worldMatrix = BABYLON.Matrix.Identity();
  10225. }
  10226. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10227. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10228. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10229. this._computedViewMatrix.invert();
  10230. this._markSyncedWithParent();
  10231. }
  10232. this._currentRenderId = this.getScene().getRenderId();
  10233. return this._computedViewMatrix;
  10234. };
  10235. Camera.prototype._computeViewMatrix = function (force) {
  10236. if (!force && this._isSynchronizedViewMatrix()) {
  10237. return this._computedViewMatrix;
  10238. }
  10239. this._computedViewMatrix = this._getViewMatrix();
  10240. this._currentRenderId = this.getScene().getRenderId();
  10241. return this._computedViewMatrix;
  10242. };
  10243. Camera.prototype.getProjectionMatrix = function (force) {
  10244. if (!force && this._isSynchronizedProjectionMatrix()) {
  10245. return this._projectionMatrix;
  10246. }
  10247. var engine = this.getEngine();
  10248. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10249. if (this.minZ <= 0) {
  10250. this.minZ = 0.1;
  10251. }
  10252. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10253. return this._projectionMatrix;
  10254. }
  10255. var halfWidth = engine.getRenderWidth() / 2.0;
  10256. var halfHeight = engine.getRenderHeight() / 2.0;
  10257. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10258. return this._projectionMatrix;
  10259. };
  10260. Camera.prototype.dispose = function () {
  10261. // Remove from scene
  10262. this.getScene().removeCamera(this);
  10263. while (this._rigCameras.length > 0) {
  10264. this._rigCameras.pop().dispose();
  10265. }
  10266. // Postprocesses
  10267. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10268. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10269. }
  10270. };
  10271. // ---- Camera rigs section ----
  10272. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10273. while (this._rigCameras.length > 0) {
  10274. this._rigCameras.pop().dispose();
  10275. }
  10276. this.cameraRigMode = mode;
  10277. this._cameraRigParams = {};
  10278. switch (this.cameraRigMode) {
  10279. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10280. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10281. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10282. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10283. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10284. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10285. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10286. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10287. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10288. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10289. break;
  10290. }
  10291. var postProcesses = new Array();
  10292. switch (this.cameraRigMode) {
  10293. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10294. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10295. this._rigCameras[0].isIntermediate = true;
  10296. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10297. postProcesses[1].onApply = function (effect) {
  10298. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10299. };
  10300. break;
  10301. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10302. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10303. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10304. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10305. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10306. var secondCamIndex = 1 - firstCamIndex;
  10307. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10308. this._rigCameras[firstCamIndex].isIntermediate = true;
  10309. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10310. break;
  10311. case Camera.RIG_MODE_VR:
  10312. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10313. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10314. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10315. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10316. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10317. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10318. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10319. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10320. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10321. if (metrics.compensateDistorsion) {
  10322. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10323. }
  10324. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10325. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10326. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10327. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10328. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10329. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10330. if (metrics.compensateDistorsion) {
  10331. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10332. }
  10333. break;
  10334. }
  10335. this._update();
  10336. };
  10337. Camera.prototype._getVRProjectionMatrix = function () {
  10338. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10339. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10340. return this._projectionMatrix;
  10341. };
  10342. Camera.prototype.setCameraRigParameter = function (name, value) {
  10343. this._cameraRigParams[name] = value;
  10344. //provisionnally:
  10345. if (name === "interaxialDistance") {
  10346. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10347. }
  10348. };
  10349. /**
  10350. * May needs to be overridden by children so sub has required properties to be copied
  10351. */
  10352. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10353. return null;
  10354. };
  10355. /**
  10356. * May needs to be overridden by children
  10357. */
  10358. Camera.prototype._updateRigCameras = function () {
  10359. for (var i = 0; i < this._rigCameras.length; i++) {
  10360. this._rigCameras[i].minZ = this.minZ;
  10361. this._rigCameras[i].maxZ = this.maxZ;
  10362. this._rigCameras[i].fov = this.fov;
  10363. }
  10364. // only update viewport when ANAGLYPH
  10365. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10366. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10367. }
  10368. };
  10369. // Statics
  10370. Camera._PERSPECTIVE_CAMERA = 0;
  10371. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10372. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10373. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10374. Camera._RIG_MODE_NONE = 0;
  10375. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10376. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10377. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10378. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10379. Camera._RIG_MODE_VR = 20;
  10380. return Camera;
  10381. })(BABYLON.Node);
  10382. BABYLON.Camera = Camera;
  10383. })(BABYLON || (BABYLON = {}));
  10384. var BABYLON;
  10385. (function (BABYLON) {
  10386. var TargetCamera = (function (_super) {
  10387. __extends(TargetCamera, _super);
  10388. function TargetCamera(name, position, scene) {
  10389. _super.call(this, name, position, scene);
  10390. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10391. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10392. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10393. this.speed = 2.0;
  10394. this.noRotationConstraint = false;
  10395. this.lockedTarget = null;
  10396. this._currentTarget = BABYLON.Vector3.Zero();
  10397. this._viewMatrix = BABYLON.Matrix.Zero();
  10398. this._camMatrix = BABYLON.Matrix.Zero();
  10399. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10400. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10401. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10402. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10403. this._lookAtTemp = BABYLON.Matrix.Zero();
  10404. this._tempMatrix = BABYLON.Matrix.Zero();
  10405. }
  10406. TargetCamera.prototype.getFrontPosition = function (distance) {
  10407. var direction = this.getTarget().subtract(this.position);
  10408. direction.normalize();
  10409. direction.scaleInPlace(distance);
  10410. return this.globalPosition.add(direction);
  10411. };
  10412. TargetCamera.prototype._getLockedTargetPosition = function () {
  10413. if (!this.lockedTarget) {
  10414. return null;
  10415. }
  10416. return this.lockedTarget.position || this.lockedTarget;
  10417. };
  10418. // Cache
  10419. TargetCamera.prototype._initCache = function () {
  10420. _super.prototype._initCache.call(this);
  10421. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10422. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10423. };
  10424. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10425. if (!ignoreParentClass) {
  10426. _super.prototype._updateCache.call(this);
  10427. }
  10428. var lockedTargetPosition = this._getLockedTargetPosition();
  10429. if (!lockedTargetPosition) {
  10430. this._cache.lockedTarget = null;
  10431. }
  10432. else {
  10433. if (!this._cache.lockedTarget) {
  10434. this._cache.lockedTarget = lockedTargetPosition.clone();
  10435. }
  10436. else {
  10437. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10438. }
  10439. }
  10440. this._cache.rotation.copyFrom(this.rotation);
  10441. };
  10442. // Synchronized
  10443. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10444. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10445. return false;
  10446. }
  10447. var lockedTargetPosition = this._getLockedTargetPosition();
  10448. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10449. && this._cache.rotation.equals(this.rotation);
  10450. };
  10451. // Methods
  10452. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10453. var engine = this.getEngine();
  10454. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10455. };
  10456. // Target
  10457. TargetCamera.prototype.setTarget = function (target) {
  10458. this.upVector.normalize();
  10459. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10460. this._camMatrix.invert();
  10461. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10462. var vDir = target.subtract(this.position);
  10463. if (vDir.x >= 0.0) {
  10464. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10465. }
  10466. else {
  10467. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10468. }
  10469. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10470. if (isNaN(this.rotation.x)) {
  10471. this.rotation.x = 0;
  10472. }
  10473. if (isNaN(this.rotation.y)) {
  10474. this.rotation.y = 0;
  10475. }
  10476. if (isNaN(this.rotation.z)) {
  10477. this.rotation.z = 0;
  10478. }
  10479. };
  10480. TargetCamera.prototype.getTarget = function () {
  10481. return this._currentTarget;
  10482. };
  10483. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10484. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10485. };
  10486. TargetCamera.prototype._updatePosition = function () {
  10487. this.position.addInPlace(this.cameraDirection);
  10488. };
  10489. TargetCamera.prototype._checkInputs = function () {
  10490. var needToMove = this._decideIfNeedsToMove();
  10491. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10492. // Move
  10493. if (needToMove) {
  10494. this._updatePosition();
  10495. }
  10496. // Rotate
  10497. if (needToRotate) {
  10498. this.rotation.x += this.cameraRotation.x;
  10499. this.rotation.y += this.cameraRotation.y;
  10500. if (!this.noRotationConstraint) {
  10501. var limit = (Math.PI / 2) * 0.95;
  10502. if (this.rotation.x > limit)
  10503. this.rotation.x = limit;
  10504. if (this.rotation.x < -limit)
  10505. this.rotation.x = -limit;
  10506. }
  10507. }
  10508. // Inertia
  10509. if (needToMove) {
  10510. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10511. this.cameraDirection.x = 0;
  10512. }
  10513. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10514. this.cameraDirection.y = 0;
  10515. }
  10516. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10517. this.cameraDirection.z = 0;
  10518. }
  10519. this.cameraDirection.scaleInPlace(this.inertia);
  10520. }
  10521. if (needToRotate) {
  10522. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10523. this.cameraRotation.x = 0;
  10524. }
  10525. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10526. this.cameraRotation.y = 0;
  10527. }
  10528. this.cameraRotation.scaleInPlace(this.inertia);
  10529. }
  10530. _super.prototype._checkInputs.call(this);
  10531. };
  10532. TargetCamera.prototype._getViewMatrix = function () {
  10533. if (!this.lockedTarget) {
  10534. // Compute
  10535. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10536. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10537. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10538. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10539. this._lookAtTemp.invert();
  10540. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10541. }
  10542. else {
  10543. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10544. }
  10545. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10546. // Computing target and final matrix
  10547. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10548. }
  10549. else {
  10550. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10551. }
  10552. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10553. return this._viewMatrix;
  10554. };
  10555. TargetCamera.prototype._getVRViewMatrix = function () {
  10556. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10557. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10558. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10559. // Computing target and final matrix
  10560. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10561. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10562. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10563. return this._viewMatrix;
  10564. };
  10565. /**
  10566. * @override
  10567. * Override Camera.createRigCamera
  10568. */
  10569. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10570. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10571. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10572. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10573. rigCamera._cameraRigParams = {};
  10574. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10575. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10576. }
  10577. return rigCamera;
  10578. }
  10579. return null;
  10580. };
  10581. /**
  10582. * @override
  10583. * Override Camera._updateRigCameras
  10584. */
  10585. TargetCamera.prototype._updateRigCameras = function () {
  10586. switch (this.cameraRigMode) {
  10587. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10588. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10589. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10590. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10591. case BABYLON.Camera.RIG_MODE_VR:
  10592. var camLeft = this._rigCameras[0];
  10593. var camRight = this._rigCameras[1];
  10594. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10595. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10596. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10597. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10598. camLeft.position.copyFrom(this.position);
  10599. camRight.position.copyFrom(this.position);
  10600. }
  10601. else {
  10602. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10603. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10604. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10605. camLeft.setTarget(this.getTarget());
  10606. camRight.setTarget(this.getTarget());
  10607. }
  10608. break;
  10609. }
  10610. _super.prototype._updateRigCameras.call(this);
  10611. };
  10612. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10613. if (!this._rigCamTransformMatrix) {
  10614. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10615. }
  10616. var target = this.getTarget();
  10617. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10618. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10619. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10620. };
  10621. return TargetCamera;
  10622. })(BABYLON.Camera);
  10623. BABYLON.TargetCamera = TargetCamera;
  10624. })(BABYLON || (BABYLON = {}));
  10625. var BABYLON;
  10626. (function (BABYLON) {
  10627. var FreeCamera = (function (_super) {
  10628. __extends(FreeCamera, _super);
  10629. function FreeCamera(name, position, scene) {
  10630. var _this = this;
  10631. _super.call(this, name, position, scene);
  10632. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10633. this.keysUp = [38];
  10634. this.keysDown = [40];
  10635. this.keysLeft = [37];
  10636. this.keysRight = [39];
  10637. this.checkCollisions = false;
  10638. this.applyGravity = false;
  10639. this.angularSensibility = 2000.0;
  10640. this._keys = [];
  10641. this._collider = new BABYLON.Collider();
  10642. this._needMoveForGravity = false;
  10643. this._oldPosition = BABYLON.Vector3.Zero();
  10644. this._diffPosition = BABYLON.Vector3.Zero();
  10645. this._newPosition = BABYLON.Vector3.Zero();
  10646. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10647. if (collidedMesh === void 0) { collidedMesh = null; }
  10648. //TODO move this to the collision coordinator!
  10649. if (_this.getScene().workerCollisions)
  10650. newPosition.multiplyInPlace(_this._collider.radius);
  10651. var updatePosition = function (newPos) {
  10652. _this._newPosition.copyFrom(newPos);
  10653. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10654. var oldPosition = _this.position.clone();
  10655. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10656. _this.position.addInPlace(_this._diffPosition);
  10657. if (_this.onCollide && collidedMesh) {
  10658. _this.onCollide(collidedMesh);
  10659. }
  10660. }
  10661. };
  10662. updatePosition(newPosition);
  10663. };
  10664. }
  10665. // Controls
  10666. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10667. var _this = this;
  10668. var previousPosition;
  10669. var engine = this.getEngine();
  10670. if (this._attachedElement) {
  10671. return;
  10672. }
  10673. this._attachedElement = element;
  10674. if (this._onMouseDown === undefined) {
  10675. this._onMouseDown = function (evt) {
  10676. previousPosition = {
  10677. x: evt.clientX,
  10678. y: evt.clientY
  10679. };
  10680. if (!noPreventDefault) {
  10681. evt.preventDefault();
  10682. }
  10683. };
  10684. this._onMouseUp = function (evt) {
  10685. previousPosition = null;
  10686. if (!noPreventDefault) {
  10687. evt.preventDefault();
  10688. }
  10689. };
  10690. this._onMouseOut = function (evt) {
  10691. previousPosition = null;
  10692. _this._keys = [];
  10693. if (!noPreventDefault) {
  10694. evt.preventDefault();
  10695. }
  10696. };
  10697. this._onMouseMove = function (evt) {
  10698. if (!previousPosition && !engine.isPointerLock) {
  10699. return;
  10700. }
  10701. var offsetX;
  10702. var offsetY;
  10703. if (!engine.isPointerLock) {
  10704. offsetX = evt.clientX - previousPosition.x;
  10705. offsetY = evt.clientY - previousPosition.y;
  10706. }
  10707. else {
  10708. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10709. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10710. }
  10711. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10712. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10713. previousPosition = {
  10714. x: evt.clientX,
  10715. y: evt.clientY
  10716. };
  10717. if (!noPreventDefault) {
  10718. evt.preventDefault();
  10719. }
  10720. };
  10721. this._onKeyDown = function (evt) {
  10722. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10723. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10724. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10725. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10726. var index = _this._keys.indexOf(evt.keyCode);
  10727. if (index === -1) {
  10728. _this._keys.push(evt.keyCode);
  10729. }
  10730. if (!noPreventDefault) {
  10731. evt.preventDefault();
  10732. }
  10733. }
  10734. };
  10735. this._onKeyUp = function (evt) {
  10736. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10737. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10738. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10739. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10740. var index = _this._keys.indexOf(evt.keyCode);
  10741. if (index >= 0) {
  10742. _this._keys.splice(index, 1);
  10743. }
  10744. if (!noPreventDefault) {
  10745. evt.preventDefault();
  10746. }
  10747. }
  10748. };
  10749. this._onLostFocus = function () {
  10750. _this._keys = [];
  10751. };
  10752. this._reset = function () {
  10753. _this._keys = [];
  10754. previousPosition = null;
  10755. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10756. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10757. };
  10758. }
  10759. element.addEventListener("mousedown", this._onMouseDown, false);
  10760. element.addEventListener("mouseup", this._onMouseUp, false);
  10761. element.addEventListener("mouseout", this._onMouseOut, false);
  10762. element.addEventListener("mousemove", this._onMouseMove, false);
  10763. BABYLON.Tools.RegisterTopRootEvents([
  10764. { name: "keydown", handler: this._onKeyDown },
  10765. { name: "keyup", handler: this._onKeyUp },
  10766. { name: "blur", handler: this._onLostFocus }
  10767. ]);
  10768. };
  10769. FreeCamera.prototype.detachControl = function (element) {
  10770. if (this._attachedElement != element) {
  10771. return;
  10772. }
  10773. element.removeEventListener("mousedown", this._onMouseDown);
  10774. element.removeEventListener("mouseup", this._onMouseUp);
  10775. element.removeEventListener("mouseout", this._onMouseOut);
  10776. element.removeEventListener("mousemove", this._onMouseMove);
  10777. BABYLON.Tools.UnregisterTopRootEvents([
  10778. { name: "keydown", handler: this._onKeyDown },
  10779. { name: "keyup", handler: this._onKeyUp },
  10780. { name: "blur", handler: this._onLostFocus }
  10781. ]);
  10782. this._attachedElement = null;
  10783. if (this._reset) {
  10784. this._reset();
  10785. }
  10786. };
  10787. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10788. var globalPosition;
  10789. if (this.parent) {
  10790. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10791. }
  10792. else {
  10793. globalPosition = this.position;
  10794. }
  10795. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10796. this._collider.radius = this.ellipsoid;
  10797. //no need for clone, as long as gravity is not on.
  10798. var actualVelocity = velocity;
  10799. //add gravity to the velocity to prevent the dual-collision checking
  10800. if (this.applyGravity) {
  10801. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10802. actualVelocity = velocity.add(this.getScene().gravity);
  10803. }
  10804. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10805. };
  10806. FreeCamera.prototype._checkInputs = function () {
  10807. if (!this._localDirection) {
  10808. this._localDirection = BABYLON.Vector3.Zero();
  10809. this._transformedDirection = BABYLON.Vector3.Zero();
  10810. }
  10811. // Keyboard
  10812. for (var index = 0; index < this._keys.length; index++) {
  10813. var keyCode = this._keys[index];
  10814. var speed = this._computeLocalCameraSpeed();
  10815. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10816. this._localDirection.copyFromFloats(-speed, 0, 0);
  10817. }
  10818. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10819. this._localDirection.copyFromFloats(0, 0, speed);
  10820. }
  10821. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10822. this._localDirection.copyFromFloats(speed, 0, 0);
  10823. }
  10824. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10825. this._localDirection.copyFromFloats(0, 0, -speed);
  10826. }
  10827. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10828. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10829. this.cameraDirection.addInPlace(this._transformedDirection);
  10830. }
  10831. _super.prototype._checkInputs.call(this);
  10832. };
  10833. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10834. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10835. };
  10836. FreeCamera.prototype._updatePosition = function () {
  10837. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10838. this._collideWithWorld(this.cameraDirection);
  10839. }
  10840. else {
  10841. this.position.addInPlace(this.cameraDirection);
  10842. }
  10843. };
  10844. return FreeCamera;
  10845. })(BABYLON.TargetCamera);
  10846. BABYLON.FreeCamera = FreeCamera;
  10847. })(BABYLON || (BABYLON = {}));
  10848. var BABYLON;
  10849. (function (BABYLON) {
  10850. var FollowCamera = (function (_super) {
  10851. __extends(FollowCamera, _super);
  10852. function FollowCamera(name, position, scene) {
  10853. _super.call(this, name, position, scene);
  10854. this.radius = 12;
  10855. this.rotationOffset = 0;
  10856. this.heightOffset = 4;
  10857. this.cameraAcceleration = 0.05;
  10858. this.maxCameraSpeed = 20;
  10859. }
  10860. FollowCamera.prototype.getRadians = function (degrees) {
  10861. return degrees * Math.PI / 180;
  10862. };
  10863. FollowCamera.prototype.follow = function (cameraTarget) {
  10864. if (!cameraTarget)
  10865. return;
  10866. var yRotation;
  10867. if (cameraTarget.rotationQuaternion) {
  10868. var rotMatrix = new BABYLON.Matrix();
  10869. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10870. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10871. }
  10872. else {
  10873. yRotation = cameraTarget.rotation.y;
  10874. }
  10875. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10876. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10877. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10878. var dx = targetX - this.position.x;
  10879. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10880. var dz = (targetZ) - this.position.z;
  10881. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10882. var vy = dy * this.cameraAcceleration;
  10883. var vz = dz * this.cameraAcceleration * 2;
  10884. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10885. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10886. }
  10887. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10888. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10889. }
  10890. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10891. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10892. }
  10893. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10894. this.setTarget(cameraTarget.position);
  10895. };
  10896. FollowCamera.prototype._checkInputs = function () {
  10897. _super.prototype._checkInputs.call(this);
  10898. this.follow(this.target);
  10899. };
  10900. return FollowCamera;
  10901. })(BABYLON.TargetCamera);
  10902. BABYLON.FollowCamera = FollowCamera;
  10903. var ArcFollowCamera = (function (_super) {
  10904. __extends(ArcFollowCamera, _super);
  10905. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10906. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10907. this.alpha = alpha;
  10908. this.beta = beta;
  10909. this.radius = radius;
  10910. this.target = target;
  10911. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10912. this.follow();
  10913. }
  10914. ArcFollowCamera.prototype.follow = function () {
  10915. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10916. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10917. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10918. this.position = this.target.position.add(this._cartesianCoordinates);
  10919. this.setTarget(this.target.position);
  10920. };
  10921. ArcFollowCamera.prototype._checkInputs = function () {
  10922. _super.prototype._checkInputs.call(this);
  10923. this.follow();
  10924. };
  10925. return ArcFollowCamera;
  10926. })(BABYLON.TargetCamera);
  10927. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10928. })(BABYLON || (BABYLON = {}));
  10929. var BABYLON;
  10930. (function (BABYLON) {
  10931. // We're mainly based on the logic defined into the FreeCamera code
  10932. var TouchCamera = (function (_super) {
  10933. __extends(TouchCamera, _super);
  10934. function TouchCamera(name, position, scene) {
  10935. _super.call(this, name, position, scene);
  10936. this._offsetX = null;
  10937. this._offsetY = null;
  10938. this._pointerCount = 0;
  10939. this._pointerPressed = [];
  10940. this.angularSensibility = 200000.0;
  10941. this.moveSensibility = 500.0;
  10942. }
  10943. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10944. var _this = this;
  10945. var previousPosition;
  10946. if (this._attachedCanvas) {
  10947. return;
  10948. }
  10949. this._attachedCanvas = canvas;
  10950. if (this._onPointerDown === undefined) {
  10951. this._onPointerDown = function (evt) {
  10952. if (!noPreventDefault) {
  10953. evt.preventDefault();
  10954. }
  10955. _this._pointerPressed.push(evt.pointerId);
  10956. if (_this._pointerPressed.length !== 1) {
  10957. return;
  10958. }
  10959. previousPosition = {
  10960. x: evt.clientX,
  10961. y: evt.clientY
  10962. };
  10963. };
  10964. this._onPointerUp = function (evt) {
  10965. if (!noPreventDefault) {
  10966. evt.preventDefault();
  10967. }
  10968. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10969. if (index === -1) {
  10970. return;
  10971. }
  10972. _this._pointerPressed.splice(index, 1);
  10973. if (index != 0) {
  10974. return;
  10975. }
  10976. previousPosition = null;
  10977. _this._offsetX = null;
  10978. _this._offsetY = null;
  10979. };
  10980. this._onPointerMove = function (evt) {
  10981. if (!noPreventDefault) {
  10982. evt.preventDefault();
  10983. }
  10984. if (!previousPosition) {
  10985. return;
  10986. }
  10987. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10988. if (index != 0) {
  10989. return;
  10990. }
  10991. _this._offsetX = evt.clientX - previousPosition.x;
  10992. _this._offsetY = -(evt.clientY - previousPosition.y);
  10993. };
  10994. this._onLostFocus = function () {
  10995. _this._offsetX = null;
  10996. _this._offsetY = null;
  10997. };
  10998. }
  10999. canvas.addEventListener("pointerdown", this._onPointerDown);
  11000. canvas.addEventListener("pointerup", this._onPointerUp);
  11001. canvas.addEventListener("pointerout", this._onPointerUp);
  11002. canvas.addEventListener("pointermove", this._onPointerMove);
  11003. BABYLON.Tools.RegisterTopRootEvents([
  11004. { name: "blur", handler: this._onLostFocus }
  11005. ]);
  11006. };
  11007. TouchCamera.prototype.detachControl = function (canvas) {
  11008. if (this._attachedCanvas != canvas) {
  11009. return;
  11010. }
  11011. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11012. canvas.removeEventListener("pointerup", this._onPointerUp);
  11013. canvas.removeEventListener("pointerout", this._onPointerUp);
  11014. canvas.removeEventListener("pointermove", this._onPointerMove);
  11015. BABYLON.Tools.UnregisterTopRootEvents([
  11016. { name: "blur", handler: this._onLostFocus }
  11017. ]);
  11018. this._attachedCanvas = null;
  11019. };
  11020. TouchCamera.prototype._checkInputs = function () {
  11021. if (this._offsetX) {
  11022. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11023. if (this._pointerPressed.length > 1) {
  11024. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11025. }
  11026. else {
  11027. var speed = this._computeLocalCameraSpeed();
  11028. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11029. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11030. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11031. }
  11032. }
  11033. _super.prototype._checkInputs.call(this);
  11034. };
  11035. return TouchCamera;
  11036. })(BABYLON.FreeCamera);
  11037. BABYLON.TouchCamera = TouchCamera;
  11038. })(BABYLON || (BABYLON = {}));
  11039. var BABYLON;
  11040. (function (BABYLON) {
  11041. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11042. var ArcRotateCamera = (function (_super) {
  11043. __extends(ArcRotateCamera, _super);
  11044. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11045. var _this = this;
  11046. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11047. this.alpha = alpha;
  11048. this.beta = beta;
  11049. this.radius = radius;
  11050. this.target = target;
  11051. this.inertialAlphaOffset = 0;
  11052. this.inertialBetaOffset = 0;
  11053. this.inertialRadiusOffset = 0;
  11054. this.lowerAlphaLimit = null;
  11055. this.upperAlphaLimit = null;
  11056. this.lowerBetaLimit = 0.01;
  11057. this.upperBetaLimit = Math.PI;
  11058. this.lowerRadiusLimit = null;
  11059. this.upperRadiusLimit = null;
  11060. this.angularSensibilityX = 1000.0;
  11061. this.angularSensibilityY = 1000.0;
  11062. this.wheelPrecision = 3.0;
  11063. this.pinchPrecision = 2.0;
  11064. this.panningSensibility = 50.0;
  11065. this.inertialPanningX = 0;
  11066. this.inertialPanningY = 0;
  11067. this.keysUp = [38];
  11068. this.keysDown = [40];
  11069. this.keysLeft = [37];
  11070. this.keysRight = [39];
  11071. this.zoomOnFactor = 1;
  11072. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11073. this.pinchInwards = true;
  11074. this.allowUpsideDown = true;
  11075. this._keys = [];
  11076. this._viewMatrix = new BABYLON.Matrix();
  11077. this._isRightClick = false;
  11078. this._isCtrlPushed = false;
  11079. this.checkCollisions = false;
  11080. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11081. this._collider = new BABYLON.Collider();
  11082. this._previousPosition = BABYLON.Vector3.Zero();
  11083. this._collisionVelocity = BABYLON.Vector3.Zero();
  11084. this._newPosition = BABYLON.Vector3.Zero();
  11085. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11086. if (collidedMesh === void 0) { collidedMesh = null; }
  11087. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11088. newPosition.multiplyInPlace(_this._collider.radius);
  11089. }
  11090. if (!collidedMesh) {
  11091. _this._previousPosition.copyFrom(_this.position);
  11092. }
  11093. else {
  11094. _this.setPosition(_this.position);
  11095. if (_this.onCollide) {
  11096. _this.onCollide(collidedMesh);
  11097. }
  11098. }
  11099. // Recompute because of constraints
  11100. var cosa = Math.cos(_this.alpha);
  11101. var sina = Math.sin(_this.alpha);
  11102. var cosb = Math.cos(_this.beta);
  11103. var sinb = Math.sin(_this.beta);
  11104. var target = _this._getTargetPosition();
  11105. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11106. _this.position.copyFrom(_this._newPosition);
  11107. var up = _this.upVector;
  11108. if (_this.allowUpsideDown && _this.beta < 0) {
  11109. var up = up.clone();
  11110. up = up.negate();
  11111. }
  11112. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11113. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11114. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11115. _this._collisionTriggered = false;
  11116. };
  11117. if (!this.target) {
  11118. this.target = BABYLON.Vector3.Zero();
  11119. }
  11120. this.getViewMatrix();
  11121. }
  11122. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11123. //deprecated angularSensibility support
  11124. get: function () {
  11125. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11126. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11127. },
  11128. //deprecated angularSensibility support
  11129. set: function (value) {
  11130. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11131. this.angularSensibilityX = value;
  11132. this.angularSensibilityY = value;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. ArcRotateCamera.prototype._getTargetPosition = function () {
  11138. return this.target.position || this.target;
  11139. };
  11140. // Cache
  11141. ArcRotateCamera.prototype._initCache = function () {
  11142. _super.prototype._initCache.call(this);
  11143. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11144. this._cache.alpha = undefined;
  11145. this._cache.beta = undefined;
  11146. this._cache.radius = undefined;
  11147. this._cache.targetScreenOffset = undefined;
  11148. };
  11149. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11150. if (!ignoreParentClass) {
  11151. _super.prototype._updateCache.call(this);
  11152. }
  11153. this._cache.target.copyFrom(this._getTargetPosition());
  11154. this._cache.alpha = this.alpha;
  11155. this._cache.beta = this.beta;
  11156. this._cache.radius = this.radius;
  11157. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11158. };
  11159. // Synchronized
  11160. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11161. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11162. return false;
  11163. return this._cache.target.equals(this._getTargetPosition())
  11164. && this._cache.alpha === this.alpha
  11165. && this._cache.beta === this.beta
  11166. && this._cache.radius === this.radius
  11167. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11168. };
  11169. // Methods
  11170. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11171. var _this = this;
  11172. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11173. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11174. var previousPinchDistance = 0;
  11175. var pointers = new BABYLON.SmartCollection();
  11176. if (this._attachedElement) {
  11177. return;
  11178. }
  11179. this._attachedElement = element;
  11180. var engine = this.getEngine();
  11181. if (this._onPointerDown === undefined) {
  11182. this._onPointerDown = function (evt) {
  11183. // Manage panning with right click
  11184. _this._isRightClick = evt.button === 2 ? true : false;
  11185. // manage pointers
  11186. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11187. cacheSoloPointer = pointers.item(evt.pointerId);
  11188. if (!noPreventDefault) {
  11189. evt.preventDefault();
  11190. }
  11191. };
  11192. this._onPointerUp = function (evt) {
  11193. cacheSoloPointer = null;
  11194. previousPinchDistance = 0;
  11195. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11196. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11197. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11198. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11199. pointers.empty();
  11200. if (!noPreventDefault) {
  11201. evt.preventDefault();
  11202. }
  11203. };
  11204. this._onContextMenu = function (evt) {
  11205. evt.preventDefault();
  11206. };
  11207. this._onPointerMove = function (evt) {
  11208. if (!noPreventDefault) {
  11209. evt.preventDefault();
  11210. }
  11211. switch (pointers.count) {
  11212. case 1:
  11213. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11214. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11215. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11216. }
  11217. else {
  11218. var offsetX = evt.clientX - cacheSoloPointer.x;
  11219. var offsetY = evt.clientY - cacheSoloPointer.y;
  11220. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11221. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11222. }
  11223. cacheSoloPointer.x = evt.clientX;
  11224. cacheSoloPointer.y = evt.clientY;
  11225. break;
  11226. case 2:
  11227. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11228. pointers.item(evt.pointerId).x = evt.clientX;
  11229. pointers.item(evt.pointerId).y = evt.clientY;
  11230. var direction = _this.pinchInwards ? 1 : -1;
  11231. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11232. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11233. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11234. if (previousPinchDistance === 0) {
  11235. previousPinchDistance = pinchSquaredDistance;
  11236. return;
  11237. }
  11238. if (pinchSquaredDistance !== previousPinchDistance) {
  11239. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11240. previousPinchDistance = pinchSquaredDistance;
  11241. }
  11242. break;
  11243. default:
  11244. if (pointers.item(evt.pointerId)) {
  11245. pointers.item(evt.pointerId).x = evt.clientX;
  11246. pointers.item(evt.pointerId).y = evt.clientY;
  11247. }
  11248. }
  11249. };
  11250. this._onMouseMove = function (evt) {
  11251. if (!engine.isPointerLock) {
  11252. return;
  11253. }
  11254. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11255. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11256. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11257. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11258. if (!noPreventDefault) {
  11259. evt.preventDefault();
  11260. }
  11261. };
  11262. this._wheel = function (event) {
  11263. var delta = 0;
  11264. if (event.wheelDelta) {
  11265. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11266. }
  11267. else if (event.detail) {
  11268. delta = -event.detail / _this.wheelPrecision;
  11269. }
  11270. if (delta)
  11271. _this.inertialRadiusOffset += delta;
  11272. if (event.preventDefault) {
  11273. if (!noPreventDefault) {
  11274. event.preventDefault();
  11275. }
  11276. }
  11277. };
  11278. this._onKeyDown = function (evt) {
  11279. _this._isCtrlPushed = evt.ctrlKey;
  11280. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11281. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11282. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11283. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11284. var index = _this._keys.indexOf(evt.keyCode);
  11285. if (index === -1) {
  11286. _this._keys.push(evt.keyCode);
  11287. }
  11288. if (evt.preventDefault) {
  11289. if (!noPreventDefault) {
  11290. evt.preventDefault();
  11291. }
  11292. }
  11293. }
  11294. };
  11295. this._onKeyUp = function (evt) {
  11296. _this._isCtrlPushed = evt.ctrlKey;
  11297. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11298. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11299. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11300. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11301. var index = _this._keys.indexOf(evt.keyCode);
  11302. if (index >= 0) {
  11303. _this._keys.splice(index, 1);
  11304. }
  11305. if (evt.preventDefault) {
  11306. if (!noPreventDefault) {
  11307. evt.preventDefault();
  11308. }
  11309. }
  11310. }
  11311. };
  11312. this._onLostFocus = function () {
  11313. _this._keys = [];
  11314. pointers.empty();
  11315. previousPinchDistance = 0;
  11316. cacheSoloPointer = null;
  11317. };
  11318. this._onGestureStart = function (e) {
  11319. if (window.MSGesture === undefined) {
  11320. return;
  11321. }
  11322. if (!_this._MSGestureHandler) {
  11323. _this._MSGestureHandler = new MSGesture();
  11324. _this._MSGestureHandler.target = element;
  11325. }
  11326. _this._MSGestureHandler.addPointer(e.pointerId);
  11327. };
  11328. this._onGesture = function (e) {
  11329. _this.radius *= e.scale;
  11330. if (e.preventDefault) {
  11331. if (!noPreventDefault) {
  11332. e.stopPropagation();
  11333. e.preventDefault();
  11334. }
  11335. }
  11336. };
  11337. this._reset = function () {
  11338. _this._keys = [];
  11339. _this.inertialAlphaOffset = 0;
  11340. _this.inertialBetaOffset = 0;
  11341. _this.inertialRadiusOffset = 0;
  11342. pointers.empty();
  11343. previousPinchDistance = 0;
  11344. cacheSoloPointer = null;
  11345. };
  11346. }
  11347. if (!useCtrlForPanning) {
  11348. element.addEventListener("contextmenu", this._onContextMenu, false);
  11349. }
  11350. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11351. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11352. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11353. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11354. element.addEventListener("mousemove", this._onMouseMove, false);
  11355. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11356. element.addEventListener("MSGestureChange", this._onGesture, false);
  11357. element.addEventListener('mousewheel', this._wheel, false);
  11358. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11359. BABYLON.Tools.RegisterTopRootEvents([
  11360. { name: "keydown", handler: this._onKeyDown },
  11361. { name: "keyup", handler: this._onKeyUp },
  11362. { name: "blur", handler: this._onLostFocus }
  11363. ]);
  11364. };
  11365. ArcRotateCamera.prototype.detachControl = function (element) {
  11366. if (this._attachedElement !== element) {
  11367. return;
  11368. }
  11369. element.removeEventListener("contextmenu", this._onContextMenu);
  11370. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11371. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11372. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11373. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11374. element.removeEventListener("mousemove", this._onMouseMove);
  11375. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11376. element.removeEventListener("MSGestureChange", this._onGesture);
  11377. element.removeEventListener('mousewheel', this._wheel);
  11378. element.removeEventListener('DOMMouseScroll', this._wheel);
  11379. BABYLON.Tools.UnregisterTopRootEvents([
  11380. { name: "keydown", handler: this._onKeyDown },
  11381. { name: "keyup", handler: this._onKeyUp },
  11382. { name: "blur", handler: this._onLostFocus }
  11383. ]);
  11384. this._MSGestureHandler = null;
  11385. this._attachedElement = null;
  11386. if (this._reset) {
  11387. this._reset();
  11388. }
  11389. };
  11390. ArcRotateCamera.prototype._checkInputs = function () {
  11391. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11392. if (this._collisionTriggered) {
  11393. return;
  11394. }
  11395. // Keyboard
  11396. for (var index = 0; index < this._keys.length; index++) {
  11397. var keyCode = this._keys[index];
  11398. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11399. this.inertialAlphaOffset -= 0.01;
  11400. }
  11401. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11402. this.inertialBetaOffset -= 0.01;
  11403. }
  11404. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11405. this.inertialAlphaOffset += 0.01;
  11406. }
  11407. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11408. this.inertialBetaOffset += 0.01;
  11409. }
  11410. }
  11411. // Inertia
  11412. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11413. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11414. this.beta += this.inertialBetaOffset;
  11415. this.radius -= this.inertialRadiusOffset;
  11416. this.inertialAlphaOffset *= this.inertia;
  11417. this.inertialBetaOffset *= this.inertia;
  11418. this.inertialRadiusOffset *= this.inertia;
  11419. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11420. this.inertialAlphaOffset = 0;
  11421. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11422. this.inertialBetaOffset = 0;
  11423. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11424. this.inertialRadiusOffset = 0;
  11425. }
  11426. // Panning inertia
  11427. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11428. if (!this._localDirection) {
  11429. this._localDirection = BABYLON.Vector3.Zero();
  11430. this._transformedDirection = BABYLON.Vector3.Zero();
  11431. }
  11432. this.inertialPanningX *= this.inertia;
  11433. this.inertialPanningY *= this.inertia;
  11434. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11435. this.inertialPanningX = 0;
  11436. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11437. this.inertialPanningY = 0;
  11438. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11439. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11440. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11441. this.target.addInPlace(this._transformedDirection);
  11442. }
  11443. // Limits
  11444. this._checkLimits();
  11445. _super.prototype._checkInputs.call(this);
  11446. };
  11447. ArcRotateCamera.prototype._checkLimits = function () {
  11448. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11449. if (this.allowUpsideDown && this.beta > Math.PI) {
  11450. this.beta = this.beta - (2 * Math.PI);
  11451. }
  11452. }
  11453. else {
  11454. if (this.beta < this.lowerBetaLimit) {
  11455. this.beta = this.lowerBetaLimit;
  11456. }
  11457. }
  11458. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11459. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11460. this.beta = this.beta + (2 * Math.PI);
  11461. }
  11462. }
  11463. else {
  11464. if (this.beta > this.upperBetaLimit) {
  11465. this.beta = this.upperBetaLimit;
  11466. }
  11467. }
  11468. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11469. this.alpha = this.lowerAlphaLimit;
  11470. }
  11471. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11472. this.alpha = this.upperAlphaLimit;
  11473. }
  11474. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11475. this.radius = this.lowerRadiusLimit;
  11476. }
  11477. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11478. this.radius = this.upperRadiusLimit;
  11479. }
  11480. };
  11481. ArcRotateCamera.prototype.setPosition = function (position) {
  11482. var radiusv3 = position.subtract(this._getTargetPosition());
  11483. this.radius = radiusv3.length();
  11484. // Alpha
  11485. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11486. if (radiusv3.z < 0) {
  11487. this.alpha = 2 * Math.PI - this.alpha;
  11488. }
  11489. // Beta
  11490. this.beta = Math.acos(radiusv3.y / this.radius);
  11491. this._checkLimits();
  11492. };
  11493. ArcRotateCamera.prototype.setTarget = function (target) {
  11494. this.target = target;
  11495. };
  11496. ArcRotateCamera.prototype._getViewMatrix = function () {
  11497. // Compute
  11498. var cosa = Math.cos(this.alpha);
  11499. var sina = Math.sin(this.alpha);
  11500. var cosb = Math.cos(this.beta);
  11501. var sinb = Math.sin(this.beta);
  11502. var target = this._getTargetPosition();
  11503. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11504. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11505. this._collider.radius = this.collisionRadius;
  11506. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11507. this._collisionTriggered = true;
  11508. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11509. }
  11510. else {
  11511. this.position.copyFrom(this._newPosition);
  11512. var up = this.upVector;
  11513. if (this.allowUpsideDown && this.beta < 0) {
  11514. var up = up.clone();
  11515. up = up.negate();
  11516. }
  11517. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11518. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11519. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11520. }
  11521. return this._viewMatrix;
  11522. };
  11523. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11524. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11525. meshes = meshes || this.getScene().meshes;
  11526. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11527. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11528. this.radius = distance * this.zoomOnFactor;
  11529. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11530. };
  11531. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11532. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11533. var meshesOrMinMaxVector;
  11534. var distance;
  11535. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11536. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11537. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11538. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11539. }
  11540. else {
  11541. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11542. distance = meshesOrMinMaxVectorAndDistance.distance;
  11543. }
  11544. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11545. if (!doNotUpdateMaxZ) {
  11546. this.maxZ = distance * 2;
  11547. }
  11548. };
  11549. /**
  11550. * @override
  11551. * Override Camera.createRigCamera
  11552. */
  11553. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11554. switch (this.cameraRigMode) {
  11555. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11556. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11559. case BABYLON.Camera.RIG_MODE_VR:
  11560. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11561. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11562. }
  11563. };
  11564. /**
  11565. * @override
  11566. * Override Camera._updateRigCameras
  11567. */
  11568. ArcRotateCamera.prototype._updateRigCameras = function () {
  11569. switch (this.cameraRigMode) {
  11570. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11571. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11572. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11573. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11574. case BABYLON.Camera.RIG_MODE_VR:
  11575. var camLeft = this._rigCameras[0];
  11576. var camRight = this._rigCameras[1];
  11577. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11578. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11579. camLeft.beta = camRight.beta = this.beta;
  11580. camLeft.radius = camRight.radius = this.radius;
  11581. break;
  11582. }
  11583. _super.prototype._updateRigCameras.call(this);
  11584. };
  11585. return ArcRotateCamera;
  11586. })(BABYLON.TargetCamera);
  11587. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11588. })(BABYLON || (BABYLON = {}));
  11589. var BABYLON;
  11590. (function (BABYLON) {
  11591. // We're mainly based on the logic defined into the FreeCamera code
  11592. var DeviceOrientationCamera = (function (_super) {
  11593. __extends(DeviceOrientationCamera, _super);
  11594. function DeviceOrientationCamera(name, position, scene) {
  11595. var _this = this;
  11596. _super.call(this, name, position, scene);
  11597. this._offsetX = null;
  11598. this._offsetY = null;
  11599. this._orientationGamma = 0;
  11600. this._orientationBeta = 0;
  11601. this._initialOrientationGamma = 0;
  11602. this._initialOrientationBeta = 0;
  11603. this.angularSensibility = 10000.0;
  11604. this.moveSensibility = 50.0;
  11605. window.addEventListener("resize", function () {
  11606. _this._initialOrientationGamma = null;
  11607. }, false);
  11608. }
  11609. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11610. var _this = this;
  11611. if (this._attachedCanvas) {
  11612. return;
  11613. }
  11614. this._attachedCanvas = canvas;
  11615. if (!this._orientationChanged) {
  11616. this._orientationChanged = function (evt) {
  11617. if (!_this._initialOrientationGamma) {
  11618. _this._initialOrientationGamma = evt.gamma;
  11619. _this._initialOrientationBeta = evt.beta;
  11620. }
  11621. _this._orientationGamma = evt.gamma;
  11622. _this._orientationBeta = evt.beta;
  11623. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11624. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11625. };
  11626. }
  11627. window.addEventListener("deviceorientation", this._orientationChanged);
  11628. };
  11629. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11630. if (this._attachedCanvas != canvas) {
  11631. return;
  11632. }
  11633. window.removeEventListener("deviceorientation", this._orientationChanged);
  11634. this._attachedCanvas = null;
  11635. this._orientationGamma = 0;
  11636. this._orientationBeta = 0;
  11637. this._initialOrientationGamma = 0;
  11638. this._initialOrientationBeta = 0;
  11639. };
  11640. DeviceOrientationCamera.prototype._checkInputs = function () {
  11641. if (!this._offsetX) {
  11642. return;
  11643. }
  11644. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11645. var speed = this._computeLocalCameraSpeed();
  11646. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11647. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11648. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11649. _super.prototype._checkInputs.call(this);
  11650. };
  11651. return DeviceOrientationCamera;
  11652. })(BABYLON.FreeCamera);
  11653. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11654. })(BABYLON || (BABYLON = {}));
  11655. var BABYLON;
  11656. (function (BABYLON) {
  11657. var Gamepads = (function () {
  11658. function Gamepads(ongamedpadconnected) {
  11659. var _this = this;
  11660. this.babylonGamepads = [];
  11661. this.oneGamepadConnected = false;
  11662. this.isMonitoring = false;
  11663. this.gamepadEventSupported = 'GamepadEvent' in window;
  11664. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11665. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11666. 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=";
  11667. this._callbackGamepadConnected = ongamedpadconnected;
  11668. if (this.gamepadSupportAvailable) {
  11669. // Checking if the gamepad connected event is supported (like in Firefox)
  11670. if (this.gamepadEventSupported) {
  11671. window.addEventListener('gamepadconnected', function (evt) {
  11672. _this._onGamepadConnected(evt);
  11673. }, false);
  11674. window.addEventListener('gamepaddisconnected', function (evt) {
  11675. _this._onGamepadDisconnected(evt);
  11676. }, false);
  11677. }
  11678. else {
  11679. this._startMonitoringGamepads();
  11680. }
  11681. if (!this.oneGamepadConnected) {
  11682. this._insertGamepadDOMInstructions();
  11683. }
  11684. }
  11685. else {
  11686. this._insertGamepadDOMNotSupported();
  11687. }
  11688. }
  11689. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11690. Gamepads.gamepadDOMInfo = document.createElement("div");
  11691. var buttonAImage = document.createElement("img");
  11692. buttonAImage.src = this.buttonADataURL;
  11693. var spanMessage = document.createElement("span");
  11694. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11695. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11696. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11697. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11698. Gamepads.gamepadDOMInfo.style.width = "100%";
  11699. Gamepads.gamepadDOMInfo.style.height = "48px";
  11700. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11701. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11702. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11703. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11704. buttonAImage.style.position = "relative";
  11705. buttonAImage.style.bottom = "8px";
  11706. spanMessage.style.position = "relative";
  11707. spanMessage.style.fontSize = "32px";
  11708. spanMessage.style.bottom = "32px";
  11709. spanMessage.style.color = "green";
  11710. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11711. };
  11712. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11713. Gamepads.gamepadDOMInfo = document.createElement("div");
  11714. var spanMessage = document.createElement("span");
  11715. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11716. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11717. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11718. Gamepads.gamepadDOMInfo.style.width = "100%";
  11719. Gamepads.gamepadDOMInfo.style.height = "40px";
  11720. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11721. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11722. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11723. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11724. spanMessage.style.position = "relative";
  11725. spanMessage.style.fontSize = "32px";
  11726. spanMessage.style.color = "red";
  11727. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11728. };
  11729. Gamepads.prototype.dispose = function () {
  11730. if (Gamepads.gamepadDOMInfo) {
  11731. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11732. }
  11733. };
  11734. Gamepads.prototype._onGamepadConnected = function (evt) {
  11735. var newGamepad = this._addNewGamepad(evt.gamepad);
  11736. if (this._callbackGamepadConnected)
  11737. this._callbackGamepadConnected(newGamepad);
  11738. this._startMonitoringGamepads();
  11739. };
  11740. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11741. if (!this.oneGamepadConnected) {
  11742. this.oneGamepadConnected = true;
  11743. if (Gamepads.gamepadDOMInfo) {
  11744. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11745. Gamepads.gamepadDOMInfo = null;
  11746. }
  11747. }
  11748. var newGamepad;
  11749. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11750. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11751. }
  11752. else {
  11753. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11754. }
  11755. this.babylonGamepads.push(newGamepad);
  11756. return newGamepad;
  11757. };
  11758. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11759. // Remove the gamepad from the list of gamepads to monitor.
  11760. for (var i in this.babylonGamepads) {
  11761. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11762. this.babylonGamepads.splice(i, 1);
  11763. break;
  11764. }
  11765. }
  11766. // If no gamepads are left, stop the polling loop.
  11767. if (this.babylonGamepads.length == 0) {
  11768. this._stopMonitoringGamepads();
  11769. }
  11770. };
  11771. Gamepads.prototype._startMonitoringGamepads = function () {
  11772. if (!this.isMonitoring) {
  11773. this.isMonitoring = true;
  11774. this._checkGamepadsStatus();
  11775. }
  11776. };
  11777. Gamepads.prototype._stopMonitoringGamepads = function () {
  11778. this.isMonitoring = false;
  11779. };
  11780. Gamepads.prototype._checkGamepadsStatus = function () {
  11781. var _this = this;
  11782. // updating gamepad objects
  11783. this._updateGamepadObjects();
  11784. for (var i in this.babylonGamepads) {
  11785. this.babylonGamepads[i].update();
  11786. }
  11787. if (this.isMonitoring) {
  11788. if (window.requestAnimationFrame) {
  11789. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11790. }
  11791. else if (window.mozRequestAnimationFrame) {
  11792. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11793. }
  11794. else if (window.webkitRequestAnimationFrame) {
  11795. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11796. }
  11797. }
  11798. };
  11799. // This function is called only on Chrome, which does not yet support
  11800. // connection/disconnection events, but requires you to monitor
  11801. // an array for changes.
  11802. Gamepads.prototype._updateGamepadObjects = function () {
  11803. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11804. for (var i = 0; i < gamepads.length; i++) {
  11805. if (gamepads[i]) {
  11806. if (!(gamepads[i].index in this.babylonGamepads)) {
  11807. var newGamepad = this._addNewGamepad(gamepads[i]);
  11808. if (this._callbackGamepadConnected) {
  11809. this._callbackGamepadConnected(newGamepad);
  11810. }
  11811. }
  11812. else {
  11813. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11814. }
  11815. }
  11816. }
  11817. };
  11818. return Gamepads;
  11819. })();
  11820. BABYLON.Gamepads = Gamepads;
  11821. var StickValues = (function () {
  11822. function StickValues(x, y) {
  11823. this.x = x;
  11824. this.y = y;
  11825. }
  11826. return StickValues;
  11827. })();
  11828. BABYLON.StickValues = StickValues;
  11829. var Gamepad = (function () {
  11830. function Gamepad(id, index, browserGamepad) {
  11831. this.id = id;
  11832. this.index = index;
  11833. this.browserGamepad = browserGamepad;
  11834. if (this.browserGamepad.axes.length >= 2) {
  11835. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11836. }
  11837. if (this.browserGamepad.axes.length >= 4) {
  11838. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11839. }
  11840. }
  11841. Gamepad.prototype.onleftstickchanged = function (callback) {
  11842. this._onleftstickchanged = callback;
  11843. };
  11844. Gamepad.prototype.onrightstickchanged = function (callback) {
  11845. this._onrightstickchanged = callback;
  11846. };
  11847. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11848. get: function () {
  11849. return this._leftStick;
  11850. },
  11851. set: function (newValues) {
  11852. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11853. this._onleftstickchanged(newValues);
  11854. }
  11855. this._leftStick = newValues;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11861. get: function () {
  11862. return this._rightStick;
  11863. },
  11864. set: function (newValues) {
  11865. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11866. this._onrightstickchanged(newValues);
  11867. }
  11868. this._rightStick = newValues;
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Gamepad.prototype.update = function () {
  11874. if (this._leftStick) {
  11875. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11876. }
  11877. if (this._rightStick) {
  11878. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11879. }
  11880. };
  11881. return Gamepad;
  11882. })();
  11883. BABYLON.Gamepad = Gamepad;
  11884. var GenericPad = (function (_super) {
  11885. __extends(GenericPad, _super);
  11886. function GenericPad(id, index, gamepad) {
  11887. _super.call(this, id, index, gamepad);
  11888. this.id = id;
  11889. this.index = index;
  11890. this.gamepad = gamepad;
  11891. this._buttons = new Array(gamepad.buttons.length);
  11892. }
  11893. GenericPad.prototype.onbuttondown = function (callback) {
  11894. this._onbuttondown = callback;
  11895. };
  11896. GenericPad.prototype.onbuttonup = function (callback) {
  11897. this._onbuttonup = callback;
  11898. };
  11899. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11900. if (newValue !== currentValue) {
  11901. if (this._onbuttondown && newValue === 1) {
  11902. this._onbuttondown(buttonIndex);
  11903. }
  11904. if (this._onbuttonup && newValue === 0) {
  11905. this._onbuttonup(buttonIndex);
  11906. }
  11907. }
  11908. return newValue;
  11909. };
  11910. GenericPad.prototype.update = function () {
  11911. _super.prototype.update.call(this);
  11912. for (var index = 0; index < this._buttons.length; index++) {
  11913. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11914. }
  11915. };
  11916. return GenericPad;
  11917. })(Gamepad);
  11918. BABYLON.GenericPad = GenericPad;
  11919. (function (Xbox360Button) {
  11920. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11921. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11922. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11923. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11924. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11925. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11926. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11927. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11928. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11929. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11930. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11931. var Xbox360Button = BABYLON.Xbox360Button;
  11932. (function (Xbox360Dpad) {
  11933. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11934. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11935. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11936. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11937. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11938. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11939. var Xbox360Pad = (function (_super) {
  11940. __extends(Xbox360Pad, _super);
  11941. function Xbox360Pad() {
  11942. _super.apply(this, arguments);
  11943. this._leftTrigger = 0;
  11944. this._rightTrigger = 0;
  11945. this._buttonA = 0;
  11946. this._buttonB = 0;
  11947. this._buttonX = 0;
  11948. this._buttonY = 0;
  11949. this._buttonBack = 0;
  11950. this._buttonStart = 0;
  11951. this._buttonLB = 0;
  11952. this._buttonRB = 0;
  11953. this._buttonLeftStick = 0;
  11954. this._buttonRightStick = 0;
  11955. this._dPadUp = 0;
  11956. this._dPadDown = 0;
  11957. this._dPadLeft = 0;
  11958. this._dPadRight = 0;
  11959. }
  11960. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11961. this._onlefttriggerchanged = callback;
  11962. };
  11963. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11964. this._onrighttriggerchanged = callback;
  11965. };
  11966. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11967. get: function () {
  11968. return this._leftTrigger;
  11969. },
  11970. set: function (newValue) {
  11971. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11972. this._onlefttriggerchanged(newValue);
  11973. }
  11974. this._leftTrigger = newValue;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11980. get: function () {
  11981. return this._rightTrigger;
  11982. },
  11983. set: function (newValue) {
  11984. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11985. this._onrighttriggerchanged(newValue);
  11986. }
  11987. this._rightTrigger = newValue;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11993. this._onbuttondown = callback;
  11994. };
  11995. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11996. this._onbuttonup = callback;
  11997. };
  11998. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11999. this._ondpaddown = callback;
  12000. };
  12001. Xbox360Pad.prototype.ondpadup = function (callback) {
  12002. this._ondpadup = callback;
  12003. };
  12004. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  12005. if (newValue !== currentValue) {
  12006. if (this._onbuttondown && newValue === 1) {
  12007. this._onbuttondown(buttonType);
  12008. }
  12009. if (this._onbuttonup && newValue === 0) {
  12010. this._onbuttonup(buttonType);
  12011. }
  12012. }
  12013. return newValue;
  12014. };
  12015. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  12016. if (newValue !== currentValue) {
  12017. if (this._ondpaddown && newValue === 1) {
  12018. this._ondpaddown(buttonType);
  12019. }
  12020. if (this._ondpadup && newValue === 0) {
  12021. this._ondpadup(buttonType);
  12022. }
  12023. }
  12024. return newValue;
  12025. };
  12026. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  12027. get: function () {
  12028. return this._buttonA;
  12029. },
  12030. set: function (value) {
  12031. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  12037. get: function () {
  12038. return this._buttonB;
  12039. },
  12040. set: function (value) {
  12041. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  12047. get: function () {
  12048. return this._buttonX;
  12049. },
  12050. set: function (value) {
  12051. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  12057. get: function () {
  12058. return this._buttonY;
  12059. },
  12060. set: function (value) {
  12061. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  12067. get: function () {
  12068. return this._buttonStart;
  12069. },
  12070. set: function (value) {
  12071. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12077. get: function () {
  12078. return this._buttonBack;
  12079. },
  12080. set: function (value) {
  12081. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12087. get: function () {
  12088. return this._buttonLB;
  12089. },
  12090. set: function (value) {
  12091. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12097. get: function () {
  12098. return this._buttonRB;
  12099. },
  12100. set: function (value) {
  12101. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12107. get: function () {
  12108. return this._buttonLeftStick;
  12109. },
  12110. set: function (value) {
  12111. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12117. get: function () {
  12118. return this._buttonRightStick;
  12119. },
  12120. set: function (value) {
  12121. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12127. get: function () {
  12128. return this._dPadUp;
  12129. },
  12130. set: function (value) {
  12131. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12132. },
  12133. enumerable: true,
  12134. configurable: true
  12135. });
  12136. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12137. get: function () {
  12138. return this._dPadDown;
  12139. },
  12140. set: function (value) {
  12141. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12147. get: function () {
  12148. return this._dPadLeft;
  12149. },
  12150. set: function (value) {
  12151. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12157. get: function () {
  12158. return this._dPadRight;
  12159. },
  12160. set: function (value) {
  12161. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12162. },
  12163. enumerable: true,
  12164. configurable: true
  12165. });
  12166. Xbox360Pad.prototype.update = function () {
  12167. _super.prototype.update.call(this);
  12168. this.buttonA = this.browserGamepad.buttons[0].value;
  12169. this.buttonB = this.browserGamepad.buttons[1].value;
  12170. this.buttonX = this.browserGamepad.buttons[2].value;
  12171. this.buttonY = this.browserGamepad.buttons[3].value;
  12172. this.buttonLB = this.browserGamepad.buttons[4].value;
  12173. this.buttonRB = this.browserGamepad.buttons[5].value;
  12174. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12175. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12176. this.buttonBack = this.browserGamepad.buttons[8].value;
  12177. this.buttonStart = this.browserGamepad.buttons[9].value;
  12178. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12179. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12180. this.dPadUp = this.browserGamepad.buttons[12].value;
  12181. this.dPadDown = this.browserGamepad.buttons[13].value;
  12182. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12183. this.dPadRight = this.browserGamepad.buttons[15].value;
  12184. };
  12185. return Xbox360Pad;
  12186. })(Gamepad);
  12187. BABYLON.Xbox360Pad = Xbox360Pad;
  12188. })(BABYLON || (BABYLON = {}));
  12189. var BABYLON;
  12190. (function (BABYLON) {
  12191. // We're mainly based on the logic defined into the FreeCamera code
  12192. var GamepadCamera = (function (_super) {
  12193. __extends(GamepadCamera, _super);
  12194. function GamepadCamera(name, position, scene) {
  12195. var _this = this;
  12196. _super.call(this, name, position, scene);
  12197. this.angularSensibility = 200;
  12198. this.moveSensibility = 75;
  12199. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12200. }
  12201. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12202. // Only the first gamepad can control the camera
  12203. if (gamepad.index === 0) {
  12204. this._gamepad = gamepad;
  12205. }
  12206. };
  12207. GamepadCamera.prototype._checkInputs = function () {
  12208. if (this._gamepad) {
  12209. var LSValues = this._gamepad.leftStick;
  12210. var normalizedLX = LSValues.x / this.moveSensibility;
  12211. var normalizedLY = LSValues.y / this.moveSensibility;
  12212. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12213. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12214. var RSValues = this._gamepad.rightStick;
  12215. var normalizedRX = RSValues.x / this.angularSensibility;
  12216. var normalizedRY = RSValues.y / this.angularSensibility;
  12217. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12218. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12219. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12220. var speed = this._computeLocalCameraSpeed() * 50.0;
  12221. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12222. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12223. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12224. }
  12225. _super.prototype._checkInputs.call(this);
  12226. };
  12227. GamepadCamera.prototype.dispose = function () {
  12228. this._gamepads.dispose();
  12229. _super.prototype.dispose.call(this);
  12230. };
  12231. return GamepadCamera;
  12232. })(BABYLON.FreeCamera);
  12233. BABYLON.GamepadCamera = GamepadCamera;
  12234. })(BABYLON || (BABYLON = {}));
  12235. var BABYLON;
  12236. (function (BABYLON) {
  12237. var RenderingManager = (function () {
  12238. function RenderingManager(scene) {
  12239. this._renderingGroups = new Array();
  12240. this._scene = scene;
  12241. }
  12242. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12243. if (this._scene._activeParticleSystems.length === 0) {
  12244. return;
  12245. }
  12246. // Particles
  12247. var activeCamera = this._scene.activeCamera;
  12248. var beforeParticlesDate = BABYLON.Tools.Now;
  12249. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12250. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12251. if (particleSystem.renderingGroupId !== index) {
  12252. continue;
  12253. }
  12254. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12255. continue;
  12256. }
  12257. this._clearDepthBuffer();
  12258. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12259. this._scene._activeParticles += particleSystem.render();
  12260. }
  12261. }
  12262. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12263. };
  12264. RenderingManager.prototype._renderSprites = function (index) {
  12265. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12266. return;
  12267. }
  12268. // Sprites
  12269. var activeCamera = this._scene.activeCamera;
  12270. var beforeSpritessDate = BABYLON.Tools.Now;
  12271. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12272. var spriteManager = this._scene.spriteManagers[id];
  12273. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12274. this._clearDepthBuffer();
  12275. spriteManager.render();
  12276. }
  12277. }
  12278. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12279. };
  12280. RenderingManager.prototype._clearDepthBuffer = function () {
  12281. if (this._depthBufferAlreadyCleaned) {
  12282. return;
  12283. }
  12284. this._scene.getEngine().clear(0, false, true);
  12285. this._depthBufferAlreadyCleaned = true;
  12286. };
  12287. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12288. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12289. this._depthBufferAlreadyCleaned = false;
  12290. var renderingGroup = this._renderingGroups[index];
  12291. var needToStepBack = false;
  12292. if (renderingGroup) {
  12293. this._clearDepthBuffer();
  12294. if (!renderingGroup.render(customRenderFunction)) {
  12295. this._renderingGroups.splice(index, 1);
  12296. needToStepBack = true;
  12297. }
  12298. }
  12299. if (renderSprites) {
  12300. this._renderSprites(index);
  12301. }
  12302. if (renderParticles) {
  12303. this._renderParticles(index, activeMeshes);
  12304. }
  12305. if (needToStepBack) {
  12306. index--;
  12307. }
  12308. }
  12309. };
  12310. RenderingManager.prototype.reset = function () {
  12311. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12312. if (renderingGroup) {
  12313. renderingGroup.prepare();
  12314. }
  12315. });
  12316. };
  12317. RenderingManager.prototype.dispatch = function (subMesh) {
  12318. var mesh = subMesh.getMesh();
  12319. var renderingGroupId = mesh.renderingGroupId || 0;
  12320. if (!this._renderingGroups[renderingGroupId]) {
  12321. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12322. }
  12323. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12324. };
  12325. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12326. return RenderingManager;
  12327. })();
  12328. BABYLON.RenderingManager = RenderingManager;
  12329. })(BABYLON || (BABYLON = {}));
  12330. var BABYLON;
  12331. (function (BABYLON) {
  12332. var RenderingGroup = (function () {
  12333. function RenderingGroup(index, scene) {
  12334. this.index = index;
  12335. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12336. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12337. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12338. this._scene = scene;
  12339. }
  12340. RenderingGroup.prototype.render = function (customRenderFunction) {
  12341. if (customRenderFunction) {
  12342. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12343. return true;
  12344. }
  12345. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12346. return false;
  12347. }
  12348. var engine = this._scene.getEngine();
  12349. // Opaque
  12350. var subIndex;
  12351. var submesh;
  12352. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12353. submesh = this._opaqueSubMeshes.data[subIndex];
  12354. submesh.render(false);
  12355. }
  12356. // Alpha test
  12357. engine.setAlphaTesting(true);
  12358. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12359. submesh = this._alphaTestSubMeshes.data[subIndex];
  12360. submesh.render(false);
  12361. }
  12362. engine.setAlphaTesting(false);
  12363. // Transparent
  12364. if (this._transparentSubMeshes.length) {
  12365. // Sorting
  12366. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12367. submesh = this._transparentSubMeshes.data[subIndex];
  12368. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12369. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12370. }
  12371. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12372. sortedArray.sort(function (a, b) {
  12373. // Alpha index first
  12374. if (a._alphaIndex > b._alphaIndex) {
  12375. return 1;
  12376. }
  12377. if (a._alphaIndex < b._alphaIndex) {
  12378. return -1;
  12379. }
  12380. // Then distance to camera
  12381. if (a._distanceToCamera < b._distanceToCamera) {
  12382. return 1;
  12383. }
  12384. if (a._distanceToCamera > b._distanceToCamera) {
  12385. return -1;
  12386. }
  12387. return 0;
  12388. });
  12389. // Rendering
  12390. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12391. submesh = sortedArray[subIndex];
  12392. submesh.render(true);
  12393. }
  12394. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12395. }
  12396. return true;
  12397. };
  12398. RenderingGroup.prototype.prepare = function () {
  12399. this._opaqueSubMeshes.reset();
  12400. this._transparentSubMeshes.reset();
  12401. this._alphaTestSubMeshes.reset();
  12402. };
  12403. RenderingGroup.prototype.dispatch = function (subMesh) {
  12404. var material = subMesh.getMaterial();
  12405. var mesh = subMesh.getMesh();
  12406. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12407. this._transparentSubMeshes.push(subMesh);
  12408. }
  12409. else if (material.needAlphaTesting()) {
  12410. this._alphaTestSubMeshes.push(subMesh);
  12411. }
  12412. else {
  12413. this._opaqueSubMeshes.push(subMesh); // Opaque
  12414. }
  12415. };
  12416. return RenderingGroup;
  12417. })();
  12418. BABYLON.RenderingGroup = RenderingGroup;
  12419. })(BABYLON || (BABYLON = {}));
  12420. var BABYLON;
  12421. (function (BABYLON) {
  12422. /**
  12423. * Represents a scene to be rendered by the engine.
  12424. * @see http://doc.babylonjs.com/page.php?p=21911
  12425. */
  12426. var Scene = (function () {
  12427. /**
  12428. * @constructor
  12429. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12430. */
  12431. function Scene(engine) {
  12432. // Members
  12433. this.autoClear = true;
  12434. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12435. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12436. this.forceWireframe = false;
  12437. this.forcePointsCloud = false;
  12438. this.forceShowBoundingBoxes = false;
  12439. this.animationsEnabled = true;
  12440. 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
  12441. // Fog
  12442. /**
  12443. * is fog enabled on this scene.
  12444. * @type {boolean}
  12445. */
  12446. this.fogEnabled = true;
  12447. this.fogMode = Scene.FOGMODE_NONE;
  12448. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12449. this.fogDensity = 0.1;
  12450. this.fogStart = 0;
  12451. this.fogEnd = 1000.0;
  12452. // Lights
  12453. /**
  12454. * is shadow enabled on this scene.
  12455. * @type {boolean}
  12456. */
  12457. this.shadowsEnabled = true;
  12458. /**
  12459. * is light enabled on this scene.
  12460. * @type {boolean}
  12461. */
  12462. this.lightsEnabled = true;
  12463. /**
  12464. * All of the lights added to this scene.
  12465. * @see BABYLON.Light
  12466. * @type {BABYLON.Light[]}
  12467. */
  12468. this.lights = new Array();
  12469. // Cameras
  12470. /**
  12471. * All of the cameras added to this scene.
  12472. * @see BABYLON.Camera
  12473. * @type {BABYLON.Camera[]}
  12474. */
  12475. this.cameras = new Array();
  12476. this.activeCameras = new Array();
  12477. // Meshes
  12478. /**
  12479. * All of the (abstract) meshes added to this scene.
  12480. * @see BABYLON.AbstractMesh
  12481. * @type {BABYLON.AbstractMesh[]}
  12482. */
  12483. this.meshes = new Array();
  12484. // Geometries
  12485. this._geometries = new Array();
  12486. this.materials = new Array();
  12487. this.multiMaterials = new Array();
  12488. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12489. // Textures
  12490. this.texturesEnabled = true;
  12491. this.textures = new Array();
  12492. // Particles
  12493. this.particlesEnabled = true;
  12494. this.particleSystems = new Array();
  12495. // Sprites
  12496. this.spritesEnabled = true;
  12497. this.spriteManagers = new Array();
  12498. // Layers
  12499. this.layers = new Array();
  12500. // Skeletons
  12501. this.skeletonsEnabled = true;
  12502. this.skeletons = new Array();
  12503. // Lens flares
  12504. this.lensFlaresEnabled = true;
  12505. this.lensFlareSystems = new Array();
  12506. // Collisions
  12507. this.collisionsEnabled = true;
  12508. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12509. // Postprocesses
  12510. this.postProcessesEnabled = true;
  12511. // Customs render targets
  12512. this.renderTargetsEnabled = true;
  12513. this.dumpNextRenderTargets = false;
  12514. this.customRenderTargets = new Array();
  12515. // Imported meshes
  12516. this.importedMeshesFiles = new Array();
  12517. // Probes
  12518. this.probesEnabled = true;
  12519. this.reflectionProbes = new Array();
  12520. this._actionManagers = new Array();
  12521. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12522. // Procedural textures
  12523. this.proceduralTexturesEnabled = true;
  12524. this._proceduralTextures = new Array();
  12525. this.soundTracks = new Array();
  12526. this._audioEnabled = true;
  12527. this._headphone = false;
  12528. this._totalVertices = 0;
  12529. this._activeIndices = 0;
  12530. this._activeParticles = 0;
  12531. this._lastFrameDuration = 0;
  12532. this._evaluateActiveMeshesDuration = 0;
  12533. this._renderTargetsDuration = 0;
  12534. this._particlesDuration = 0;
  12535. this._renderDuration = 0;
  12536. this._spritesDuration = 0;
  12537. this._animationRatio = 0;
  12538. this._renderId = 0;
  12539. this._executeWhenReadyTimeoutId = -1;
  12540. this._toBeDisposed = new BABYLON.SmartArray(256);
  12541. this._onReadyCallbacks = new Array();
  12542. this._pendingData = []; //ANY
  12543. this._onBeforeRenderCallbacks = new Array();
  12544. this._onAfterRenderCallbacks = new Array();
  12545. this._activeMeshes = new BABYLON.SmartArray(256);
  12546. this._processedMaterials = new BABYLON.SmartArray(256);
  12547. this._renderTargets = new BABYLON.SmartArray(256);
  12548. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12549. this._activeSkeletons = new BABYLON.SmartArray(32);
  12550. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12551. this._activeBones = 0;
  12552. this._activeAnimatables = new Array();
  12553. this._transformMatrix = BABYLON.Matrix.Zero();
  12554. this._edgesRenderers = new BABYLON.SmartArray(16);
  12555. this._uniqueIdCounter = 0;
  12556. this._engine = engine;
  12557. engine.scenes.push(this);
  12558. this._renderingManager = new BABYLON.RenderingManager(this);
  12559. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12560. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12561. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12562. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12563. this.attachControl();
  12564. this._debugLayer = new BABYLON.DebugLayer(this);
  12565. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12566. //simplification queue
  12567. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12568. //collision coordinator initialization. For now legacy per default.
  12569. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12570. }
  12571. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12572. get: function () {
  12573. return Scene._FOGMODE_NONE;
  12574. },
  12575. enumerable: true,
  12576. configurable: true
  12577. });
  12578. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12579. get: function () {
  12580. return Scene._FOGMODE_EXP;
  12581. },
  12582. enumerable: true,
  12583. configurable: true
  12584. });
  12585. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12586. get: function () {
  12587. return Scene._FOGMODE_EXP2;
  12588. },
  12589. enumerable: true,
  12590. configurable: true
  12591. });
  12592. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12593. get: function () {
  12594. return Scene._FOGMODE_LINEAR;
  12595. },
  12596. enumerable: true,
  12597. configurable: true
  12598. });
  12599. Object.defineProperty(Scene.prototype, "debugLayer", {
  12600. // Properties
  12601. get: function () {
  12602. return this._debugLayer;
  12603. },
  12604. enumerable: true,
  12605. configurable: true
  12606. });
  12607. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12608. get: function () {
  12609. return this._workerCollisions;
  12610. },
  12611. set: function (enabled) {
  12612. enabled = (enabled && !!Worker);
  12613. this._workerCollisions = enabled;
  12614. if (this.collisionCoordinator) {
  12615. this.collisionCoordinator.destroy();
  12616. }
  12617. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12618. this.collisionCoordinator.init(this);
  12619. },
  12620. enumerable: true,
  12621. configurable: true
  12622. });
  12623. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12624. get: function () {
  12625. return this._selectionOctree;
  12626. },
  12627. enumerable: true,
  12628. configurable: true
  12629. });
  12630. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12631. /**
  12632. * The mesh that is currently under the pointer.
  12633. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12634. */
  12635. get: function () {
  12636. return this._meshUnderPointer;
  12637. },
  12638. enumerable: true,
  12639. configurable: true
  12640. });
  12641. Object.defineProperty(Scene.prototype, "pointerX", {
  12642. /**
  12643. * Current on-screen X position of the pointer
  12644. * @return {number} X position of the pointer
  12645. */
  12646. get: function () {
  12647. return this._pointerX;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(Scene.prototype, "pointerY", {
  12653. /**
  12654. * Current on-screen Y position of the pointer
  12655. * @return {number} Y position of the pointer
  12656. */
  12657. get: function () {
  12658. return this._pointerY;
  12659. },
  12660. enumerable: true,
  12661. configurable: true
  12662. });
  12663. Scene.prototype.getCachedMaterial = function () {
  12664. return this._cachedMaterial;
  12665. };
  12666. Scene.prototype.getBoundingBoxRenderer = function () {
  12667. return this._boundingBoxRenderer;
  12668. };
  12669. Scene.prototype.getOutlineRenderer = function () {
  12670. return this._outlineRenderer;
  12671. };
  12672. Scene.prototype.getEngine = function () {
  12673. return this._engine;
  12674. };
  12675. Scene.prototype.getTotalVertices = function () {
  12676. return this._totalVertices;
  12677. };
  12678. Scene.prototype.getActiveIndices = function () {
  12679. return this._activeIndices;
  12680. };
  12681. Scene.prototype.getActiveParticles = function () {
  12682. return this._activeParticles;
  12683. };
  12684. Scene.prototype.getActiveBones = function () {
  12685. return this._activeBones;
  12686. };
  12687. // Stats
  12688. Scene.prototype.getLastFrameDuration = function () {
  12689. return this._lastFrameDuration;
  12690. };
  12691. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12692. return this._evaluateActiveMeshesDuration;
  12693. };
  12694. Scene.prototype.getActiveMeshes = function () {
  12695. return this._activeMeshes;
  12696. };
  12697. Scene.prototype.getRenderTargetsDuration = function () {
  12698. return this._renderTargetsDuration;
  12699. };
  12700. Scene.prototype.getRenderDuration = function () {
  12701. return this._renderDuration;
  12702. };
  12703. Scene.prototype.getParticlesDuration = function () {
  12704. return this._particlesDuration;
  12705. };
  12706. Scene.prototype.getSpritesDuration = function () {
  12707. return this._spritesDuration;
  12708. };
  12709. Scene.prototype.getAnimationRatio = function () {
  12710. return this._animationRatio;
  12711. };
  12712. Scene.prototype.getRenderId = function () {
  12713. return this._renderId;
  12714. };
  12715. Scene.prototype.incrementRenderId = function () {
  12716. this._renderId++;
  12717. };
  12718. Scene.prototype._updatePointerPosition = function (evt) {
  12719. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12720. this._pointerX = evt.clientX - canvasRect.left;
  12721. this._pointerY = evt.clientY - canvasRect.top;
  12722. if (this.cameraToUseForPointers) {
  12723. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12724. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12725. }
  12726. };
  12727. // Pointers handling
  12728. Scene.prototype.attachControl = function () {
  12729. var _this = this;
  12730. this._onPointerMove = function (evt) {
  12731. var canvas = _this._engine.getRenderingCanvas();
  12732. _this._updatePointerPosition(evt);
  12733. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12734. if (pickResult.hit) {
  12735. _this._meshUnderPointer = pickResult.pickedMesh;
  12736. _this.setPointerOverMesh(pickResult.pickedMesh);
  12737. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12738. canvas.style.cursor = "pointer";
  12739. }
  12740. else {
  12741. canvas.style.cursor = "";
  12742. }
  12743. }
  12744. else {
  12745. _this.setPointerOverMesh(null);
  12746. canvas.style.cursor = "";
  12747. _this._meshUnderPointer = null;
  12748. }
  12749. };
  12750. this._onPointerDown = function (evt) {
  12751. var predicate = null;
  12752. if (!_this.onPointerDown) {
  12753. predicate = function (mesh) {
  12754. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12755. };
  12756. }
  12757. _this._updatePointerPosition(evt);
  12758. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12759. if (pickResult.hit) {
  12760. if (pickResult.pickedMesh.actionManager) {
  12761. switch (evt.button) {
  12762. case 0:
  12763. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12764. break;
  12765. case 1:
  12766. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12767. break;
  12768. case 2:
  12769. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12770. break;
  12771. }
  12772. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12773. }
  12774. }
  12775. if (_this.onPointerDown) {
  12776. _this.onPointerDown(evt, pickResult);
  12777. }
  12778. };
  12779. this._onPointerUp = function (evt) {
  12780. var predicate = null;
  12781. if (!_this.onPointerUp) {
  12782. predicate = function (mesh) {
  12783. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12784. };
  12785. }
  12786. _this._updatePointerPosition(evt);
  12787. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12788. if (pickResult.hit) {
  12789. if (pickResult.pickedMesh.actionManager) {
  12790. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12791. }
  12792. }
  12793. if (_this.onPointerUp) {
  12794. _this.onPointerUp(evt, pickResult);
  12795. }
  12796. };
  12797. this._onKeyDown = function (evt) {
  12798. if (_this.actionManager) {
  12799. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12800. }
  12801. };
  12802. this._onKeyUp = function (evt) {
  12803. if (_this.actionManager) {
  12804. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12805. }
  12806. };
  12807. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12808. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12809. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12810. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12811. // Wheel
  12812. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12813. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12814. BABYLON.Tools.RegisterTopRootEvents([
  12815. { name: "keydown", handler: this._onKeyDown },
  12816. { name: "keyup", handler: this._onKeyUp }
  12817. ]);
  12818. };
  12819. Scene.prototype.detachControl = function () {
  12820. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12821. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12822. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12823. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12824. // Wheel
  12825. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12826. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12827. BABYLON.Tools.UnregisterTopRootEvents([
  12828. { name: "keydown", handler: this._onKeyDown },
  12829. { name: "keyup", handler: this._onKeyUp }
  12830. ]);
  12831. };
  12832. // Ready
  12833. Scene.prototype.isReady = function () {
  12834. if (this._pendingData.length > 0) {
  12835. return false;
  12836. }
  12837. var index;
  12838. for (index = 0; index < this._geometries.length; index++) {
  12839. var geometry = this._geometries[index];
  12840. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12841. return false;
  12842. }
  12843. }
  12844. for (index = 0; index < this.meshes.length; index++) {
  12845. var mesh = this.meshes[index];
  12846. if (!mesh.isReady()) {
  12847. return false;
  12848. }
  12849. var mat = mesh.material;
  12850. if (mat) {
  12851. if (!mat.isReady(mesh)) {
  12852. return false;
  12853. }
  12854. }
  12855. }
  12856. return true;
  12857. };
  12858. Scene.prototype.resetCachedMaterial = function () {
  12859. this._cachedMaterial = null;
  12860. };
  12861. Scene.prototype.registerBeforeRender = function (func) {
  12862. this._onBeforeRenderCallbacks.push(func);
  12863. };
  12864. Scene.prototype.unregisterBeforeRender = function (func) {
  12865. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12866. if (index > -1) {
  12867. this._onBeforeRenderCallbacks.splice(index, 1);
  12868. }
  12869. };
  12870. Scene.prototype.registerAfterRender = function (func) {
  12871. this._onAfterRenderCallbacks.push(func);
  12872. };
  12873. Scene.prototype.unregisterAfterRender = function (func) {
  12874. var index = this._onAfterRenderCallbacks.indexOf(func);
  12875. if (index > -1) {
  12876. this._onAfterRenderCallbacks.splice(index, 1);
  12877. }
  12878. };
  12879. Scene.prototype._addPendingData = function (data) {
  12880. this._pendingData.push(data);
  12881. };
  12882. Scene.prototype._removePendingData = function (data) {
  12883. var index = this._pendingData.indexOf(data);
  12884. if (index !== -1) {
  12885. this._pendingData.splice(index, 1);
  12886. }
  12887. };
  12888. Scene.prototype.getWaitingItemsCount = function () {
  12889. return this._pendingData.length;
  12890. };
  12891. /**
  12892. * Registers a function to be executed when the scene is ready.
  12893. * @param {Function} func - the function to be executed.
  12894. */
  12895. Scene.prototype.executeWhenReady = function (func) {
  12896. var _this = this;
  12897. this._onReadyCallbacks.push(func);
  12898. if (this._executeWhenReadyTimeoutId !== -1) {
  12899. return;
  12900. }
  12901. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12902. _this._checkIsReady();
  12903. }, 150);
  12904. };
  12905. Scene.prototype._checkIsReady = function () {
  12906. var _this = this;
  12907. if (this.isReady()) {
  12908. this._onReadyCallbacks.forEach(function (func) {
  12909. func();
  12910. });
  12911. this._onReadyCallbacks = [];
  12912. this._executeWhenReadyTimeoutId = -1;
  12913. return;
  12914. }
  12915. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12916. _this._checkIsReady();
  12917. }, 150);
  12918. };
  12919. // Animations
  12920. /**
  12921. * Will start the animation sequence of a given target
  12922. * @param target - the target
  12923. * @param {number} from - from which frame should animation start
  12924. * @param {number} to - till which frame should animation run.
  12925. * @param {boolean} [loop] - should the animation loop
  12926. * @param {number} [speedRatio] - the speed in which to run the animation
  12927. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12928. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12929. * @return {BABYLON.Animatable} the animatable object created for this animation
  12930. * @see BABYLON.Animatable
  12931. * @see http://doc.babylonjs.com/page.php?p=22081
  12932. */
  12933. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12934. if (speedRatio === void 0) { speedRatio = 1.0; }
  12935. this.stopAnimation(target);
  12936. if (!animatable) {
  12937. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12938. }
  12939. // Local animations
  12940. if (target.animations) {
  12941. animatable.appendAnimations(target, target.animations);
  12942. }
  12943. // Children animations
  12944. if (target.getAnimatables) {
  12945. var animatables = target.getAnimatables();
  12946. for (var index = 0; index < animatables.length; index++) {
  12947. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12948. }
  12949. }
  12950. return animatable;
  12951. };
  12952. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12953. if (speedRatio === undefined) {
  12954. speedRatio = 1.0;
  12955. }
  12956. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12957. return animatable;
  12958. };
  12959. Scene.prototype.getAnimatableByTarget = function (target) {
  12960. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12961. if (this._activeAnimatables[index].target === target) {
  12962. return this._activeAnimatables[index];
  12963. }
  12964. }
  12965. return null;
  12966. };
  12967. /**
  12968. * Will stop the animation of the given target
  12969. * @param target - the target
  12970. * @see beginAnimation
  12971. */
  12972. Scene.prototype.stopAnimation = function (target) {
  12973. var animatable = this.getAnimatableByTarget(target);
  12974. if (animatable) {
  12975. animatable.stop();
  12976. }
  12977. };
  12978. Scene.prototype._animate = function () {
  12979. if (!this.animationsEnabled) {
  12980. return;
  12981. }
  12982. if (!this._animationStartDate) {
  12983. this._animationStartDate = BABYLON.Tools.Now;
  12984. }
  12985. // Getting time
  12986. var now = BABYLON.Tools.Now;
  12987. var delay = now - this._animationStartDate;
  12988. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12989. this._activeAnimatables[index]._animate(delay);
  12990. }
  12991. };
  12992. // Matrix
  12993. Scene.prototype.getViewMatrix = function () {
  12994. return this._viewMatrix;
  12995. };
  12996. Scene.prototype.getProjectionMatrix = function () {
  12997. return this._projectionMatrix;
  12998. };
  12999. Scene.prototype.getTransformMatrix = function () {
  13000. return this._transformMatrix;
  13001. };
  13002. Scene.prototype.setTransformMatrix = function (view, projection) {
  13003. this._viewMatrix = view;
  13004. this._projectionMatrix = projection;
  13005. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13006. };
  13007. // Methods
  13008. Scene.prototype.addMesh = function (newMesh) {
  13009. newMesh.uniqueId = this._uniqueIdCounter++;
  13010. var position = this.meshes.push(newMesh);
  13011. //notify the collision coordinator
  13012. this.collisionCoordinator.onMeshAdded(newMesh);
  13013. if (this.onNewMeshAdded) {
  13014. this.onNewMeshAdded(newMesh, position, this);
  13015. }
  13016. };
  13017. Scene.prototype.removeMesh = function (toRemove) {
  13018. var index = this.meshes.indexOf(toRemove);
  13019. if (index !== -1) {
  13020. // Remove from the scene if mesh found
  13021. this.meshes.splice(index, 1);
  13022. }
  13023. //notify the collision coordinator
  13024. this.collisionCoordinator.onMeshRemoved(toRemove);
  13025. if (this.onMeshRemoved) {
  13026. this.onMeshRemoved(toRemove);
  13027. }
  13028. return index;
  13029. };
  13030. Scene.prototype.removeLight = function (toRemove) {
  13031. var index = this.lights.indexOf(toRemove);
  13032. if (index !== -1) {
  13033. // Remove from the scene if mesh found
  13034. this.lights.splice(index, 1);
  13035. }
  13036. if (this.onLightRemoved) {
  13037. this.onLightRemoved(toRemove);
  13038. }
  13039. return index;
  13040. };
  13041. Scene.prototype.removeCamera = function (toRemove) {
  13042. var index = this.cameras.indexOf(toRemove);
  13043. if (index !== -1) {
  13044. // Remove from the scene if mesh found
  13045. this.cameras.splice(index, 1);
  13046. }
  13047. // Remove from activeCameras
  13048. var index2 = this.activeCameras.indexOf(toRemove);
  13049. if (index2 !== -1) {
  13050. // Remove from the scene if mesh found
  13051. this.activeCameras.splice(index2, 1);
  13052. }
  13053. // Reset the activeCamera
  13054. if (this.activeCamera === toRemove) {
  13055. if (this.cameras.length > 0) {
  13056. this.activeCamera = this.cameras[0];
  13057. }
  13058. else {
  13059. this.activeCamera = null;
  13060. }
  13061. }
  13062. if (this.onCameraRemoved) {
  13063. this.onCameraRemoved(toRemove);
  13064. }
  13065. return index;
  13066. };
  13067. Scene.prototype.addLight = function (newLight) {
  13068. newLight.uniqueId = this._uniqueIdCounter++;
  13069. var position = this.lights.push(newLight);
  13070. if (this.onNewLightAdded) {
  13071. this.onNewLightAdded(newLight, position, this);
  13072. }
  13073. };
  13074. Scene.prototype.addCamera = function (newCamera) {
  13075. newCamera.uniqueId = this._uniqueIdCounter++;
  13076. var position = this.cameras.push(newCamera);
  13077. if (this.onNewCameraAdded) {
  13078. this.onNewCameraAdded(newCamera, position, this);
  13079. }
  13080. };
  13081. /**
  13082. * sets the active camera of the scene using its ID
  13083. * @param {string} id - the camera's ID
  13084. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13085. * @see activeCamera
  13086. */
  13087. Scene.prototype.setActiveCameraByID = function (id) {
  13088. var camera = this.getCameraByID(id);
  13089. if (camera) {
  13090. this.activeCamera = camera;
  13091. return camera;
  13092. }
  13093. return null;
  13094. };
  13095. /**
  13096. * sets the active camera of the scene using its name
  13097. * @param {string} name - the camera's name
  13098. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13099. * @see activeCamera
  13100. */
  13101. Scene.prototype.setActiveCameraByName = function (name) {
  13102. var camera = this.getCameraByName(name);
  13103. if (camera) {
  13104. this.activeCamera = camera;
  13105. return camera;
  13106. }
  13107. return null;
  13108. };
  13109. /**
  13110. * get a material using its id
  13111. * @param {string} the material's ID
  13112. * @return {BABYLON.Material|null} the material or null if none found.
  13113. */
  13114. Scene.prototype.getMaterialByID = function (id) {
  13115. for (var index = 0; index < this.materials.length; index++) {
  13116. if (this.materials[index].id === id) {
  13117. return this.materials[index];
  13118. }
  13119. }
  13120. return null;
  13121. };
  13122. /**
  13123. * get a material using its name
  13124. * @param {string} the material's name
  13125. * @return {BABYLON.Material|null} the material or null if none found.
  13126. */
  13127. Scene.prototype.getMaterialByName = function (name) {
  13128. for (var index = 0; index < this.materials.length; index++) {
  13129. if (this.materials[index].name === name) {
  13130. return this.materials[index];
  13131. }
  13132. }
  13133. return null;
  13134. };
  13135. Scene.prototype.getLensFlareSystemByName = function (name) {
  13136. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13137. if (this.lensFlareSystems[index].name === name) {
  13138. return this.lensFlareSystems[index];
  13139. }
  13140. }
  13141. return null;
  13142. };
  13143. Scene.prototype.getCameraByID = function (id) {
  13144. for (var index = 0; index < this.cameras.length; index++) {
  13145. if (this.cameras[index].id === id) {
  13146. return this.cameras[index];
  13147. }
  13148. }
  13149. return null;
  13150. };
  13151. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13152. for (var index = 0; index < this.cameras.length; index++) {
  13153. if (this.cameras[index].uniqueId === uniqueId) {
  13154. return this.cameras[index];
  13155. }
  13156. }
  13157. return null;
  13158. };
  13159. /**
  13160. * get a camera using its name
  13161. * @param {string} the camera's name
  13162. * @return {BABYLON.Camera|null} the camera or null if none found.
  13163. */
  13164. Scene.prototype.getCameraByName = function (name) {
  13165. for (var index = 0; index < this.cameras.length; index++) {
  13166. if (this.cameras[index].name === name) {
  13167. return this.cameras[index];
  13168. }
  13169. }
  13170. return null;
  13171. };
  13172. /**
  13173. * get a light node using its name
  13174. * @param {string} the light's name
  13175. * @return {BABYLON.Light|null} the light or null if none found.
  13176. */
  13177. Scene.prototype.getLightByName = function (name) {
  13178. for (var index = 0; index < this.lights.length; index++) {
  13179. if (this.lights[index].name === name) {
  13180. return this.lights[index];
  13181. }
  13182. }
  13183. return null;
  13184. };
  13185. /**
  13186. * get a light node using its ID
  13187. * @param {string} the light's id
  13188. * @return {BABYLON.Light|null} the light or null if none found.
  13189. */
  13190. Scene.prototype.getLightByID = function (id) {
  13191. for (var index = 0; index < this.lights.length; index++) {
  13192. if (this.lights[index].id === id) {
  13193. return this.lights[index];
  13194. }
  13195. }
  13196. return null;
  13197. };
  13198. /**
  13199. * get a light node using its scene-generated unique ID
  13200. * @param {number} the light's unique id
  13201. * @return {BABYLON.Light|null} the light or null if none found.
  13202. */
  13203. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13204. for (var index = 0; index < this.lights.length; index++) {
  13205. if (this.lights[index].uniqueId === uniqueId) {
  13206. return this.lights[index];
  13207. }
  13208. }
  13209. return null;
  13210. };
  13211. /**
  13212. * get a geometry using its ID
  13213. * @param {string} the geometry's id
  13214. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13215. */
  13216. Scene.prototype.getGeometryByID = function (id) {
  13217. for (var index = 0; index < this._geometries.length; index++) {
  13218. if (this._geometries[index].id === id) {
  13219. return this._geometries[index];
  13220. }
  13221. }
  13222. return null;
  13223. };
  13224. /**
  13225. * add a new geometry to this scene.
  13226. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13227. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13228. * @return {boolean} was the geometry added or not
  13229. */
  13230. Scene.prototype.pushGeometry = function (geometry, force) {
  13231. if (!force && this.getGeometryByID(geometry.id)) {
  13232. return false;
  13233. }
  13234. this._geometries.push(geometry);
  13235. //notify the collision coordinator
  13236. this.collisionCoordinator.onGeometryAdded(geometry);
  13237. if (this.onGeometryAdded) {
  13238. this.onGeometryAdded(geometry);
  13239. }
  13240. return true;
  13241. };
  13242. /**
  13243. * Removes an existing geometry
  13244. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13245. * @return {boolean} was the geometry removed or not
  13246. */
  13247. Scene.prototype.removeGeometry = function (geometry) {
  13248. var index = this._geometries.indexOf(geometry);
  13249. if (index > -1) {
  13250. this._geometries.splice(index, 1);
  13251. //notify the collision coordinator
  13252. this.collisionCoordinator.onGeometryDeleted(geometry);
  13253. if (this.onGeometryRemoved) {
  13254. this.onGeometryRemoved(geometry);
  13255. }
  13256. return true;
  13257. }
  13258. return false;
  13259. };
  13260. Scene.prototype.getGeometries = function () {
  13261. return this._geometries;
  13262. };
  13263. /**
  13264. * Get the first added mesh found of a given ID
  13265. * @param {string} id - the id to search for
  13266. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13267. */
  13268. Scene.prototype.getMeshByID = function (id) {
  13269. for (var index = 0; index < this.meshes.length; index++) {
  13270. if (this.meshes[index].id === id) {
  13271. return this.meshes[index];
  13272. }
  13273. }
  13274. return null;
  13275. };
  13276. /**
  13277. * Get a mesh with its auto-generated unique id
  13278. * @param {number} uniqueId - the unique id to search for
  13279. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13280. */
  13281. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13282. for (var index = 0; index < this.meshes.length; index++) {
  13283. if (this.meshes[index].uniqueId === uniqueId) {
  13284. return this.meshes[index];
  13285. }
  13286. }
  13287. return null;
  13288. };
  13289. /**
  13290. * Get a the last added mesh found of a given ID
  13291. * @param {string} id - the id to search for
  13292. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13293. */
  13294. Scene.prototype.getLastMeshByID = function (id) {
  13295. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13296. if (this.meshes[index].id === id) {
  13297. return this.meshes[index];
  13298. }
  13299. }
  13300. return null;
  13301. };
  13302. /**
  13303. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13304. * @param {string} id - the id to search for
  13305. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13306. */
  13307. Scene.prototype.getLastEntryByID = function (id) {
  13308. var index;
  13309. for (index = this.meshes.length - 1; index >= 0; index--) {
  13310. if (this.meshes[index].id === id) {
  13311. return this.meshes[index];
  13312. }
  13313. }
  13314. for (index = this.cameras.length - 1; index >= 0; index--) {
  13315. if (this.cameras[index].id === id) {
  13316. return this.cameras[index];
  13317. }
  13318. }
  13319. for (index = this.lights.length - 1; index >= 0; index--) {
  13320. if (this.lights[index].id === id) {
  13321. return this.lights[index];
  13322. }
  13323. }
  13324. return null;
  13325. };
  13326. Scene.prototype.getNodeByID = function (id) {
  13327. var mesh = this.getMeshByID(id);
  13328. if (mesh) {
  13329. return mesh;
  13330. }
  13331. var light = this.getLightByID(id);
  13332. if (light) {
  13333. return light;
  13334. }
  13335. return this.getCameraByID(id);
  13336. };
  13337. Scene.prototype.getNodeByName = function (name) {
  13338. var mesh = this.getMeshByName(name);
  13339. if (mesh) {
  13340. return mesh;
  13341. }
  13342. var light = this.getLightByName(name);
  13343. if (light) {
  13344. return light;
  13345. }
  13346. return this.getCameraByName(name);
  13347. };
  13348. Scene.prototype.getMeshByName = function (name) {
  13349. for (var index = 0; index < this.meshes.length; index++) {
  13350. if (this.meshes[index].name === name) {
  13351. return this.meshes[index];
  13352. }
  13353. }
  13354. return null;
  13355. };
  13356. Scene.prototype.getSoundByName = function (name) {
  13357. var index;
  13358. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13359. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13360. return this.mainSoundTrack.soundCollection[index];
  13361. }
  13362. }
  13363. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13364. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13365. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13366. return this.soundTracks[sdIndex].soundCollection[index];
  13367. }
  13368. }
  13369. }
  13370. return null;
  13371. };
  13372. Scene.prototype.getLastSkeletonByID = function (id) {
  13373. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13374. if (this.skeletons[index].id === id) {
  13375. return this.skeletons[index];
  13376. }
  13377. }
  13378. return null;
  13379. };
  13380. Scene.prototype.getSkeletonById = function (id) {
  13381. for (var index = 0; index < this.skeletons.length; index++) {
  13382. if (this.skeletons[index].id === id) {
  13383. return this.skeletons[index];
  13384. }
  13385. }
  13386. return null;
  13387. };
  13388. Scene.prototype.getSkeletonByName = function (name) {
  13389. for (var index = 0; index < this.skeletons.length; index++) {
  13390. if (this.skeletons[index].name === name) {
  13391. return this.skeletons[index];
  13392. }
  13393. }
  13394. return null;
  13395. };
  13396. Scene.prototype.isActiveMesh = function (mesh) {
  13397. return (this._activeMeshes.indexOf(mesh) !== -1);
  13398. };
  13399. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13400. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13401. var material = subMesh.getMaterial();
  13402. if (mesh.showSubMeshesBoundingBox) {
  13403. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13404. }
  13405. if (material) {
  13406. // Render targets
  13407. if (material.getRenderTargetTextures) {
  13408. if (this._processedMaterials.indexOf(material) === -1) {
  13409. this._processedMaterials.push(material);
  13410. this._renderTargets.concat(material.getRenderTargetTextures());
  13411. }
  13412. }
  13413. // Dispatch
  13414. this._activeIndices += subMesh.indexCount;
  13415. this._renderingManager.dispatch(subMesh);
  13416. }
  13417. }
  13418. };
  13419. Scene.prototype._evaluateActiveMeshes = function () {
  13420. this.activeCamera._activeMeshes.reset();
  13421. this._activeMeshes.reset();
  13422. this._renderingManager.reset();
  13423. this._processedMaterials.reset();
  13424. this._activeParticleSystems.reset();
  13425. this._activeSkeletons.reset();
  13426. this._softwareSkinnedMeshes.reset();
  13427. this._boundingBoxRenderer.reset();
  13428. this._edgesRenderers.reset();
  13429. if (!this._frustumPlanes) {
  13430. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13431. }
  13432. else {
  13433. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13434. }
  13435. // Meshes
  13436. var meshes;
  13437. var len;
  13438. if (this._selectionOctree) {
  13439. var selection = this._selectionOctree.select(this._frustumPlanes);
  13440. meshes = selection.data;
  13441. len = selection.length;
  13442. }
  13443. else {
  13444. len = this.meshes.length;
  13445. meshes = this.meshes;
  13446. }
  13447. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13448. var mesh = meshes[meshIndex];
  13449. if (mesh.isBlocked) {
  13450. continue;
  13451. }
  13452. this._totalVertices += mesh.getTotalVertices();
  13453. if (!mesh.isReady() || !mesh.isEnabled()) {
  13454. continue;
  13455. }
  13456. mesh.computeWorldMatrix();
  13457. // Intersections
  13458. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13459. this._meshesForIntersections.pushNoDuplicate(mesh);
  13460. }
  13461. // Switch to current LOD
  13462. var meshLOD = mesh.getLOD(this.activeCamera);
  13463. if (!meshLOD) {
  13464. continue;
  13465. }
  13466. mesh._preActivate();
  13467. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13468. this._activeMeshes.push(mesh);
  13469. this.activeCamera._activeMeshes.push(mesh);
  13470. mesh._activate(this._renderId);
  13471. this._activeMesh(meshLOD);
  13472. }
  13473. }
  13474. // Particle systems
  13475. var beforeParticlesDate = BABYLON.Tools.Now;
  13476. if (this.particlesEnabled) {
  13477. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13478. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13479. var particleSystem = this.particleSystems[particleIndex];
  13480. if (!particleSystem.isStarted()) {
  13481. continue;
  13482. }
  13483. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13484. this._activeParticleSystems.push(particleSystem);
  13485. particleSystem.animate();
  13486. }
  13487. }
  13488. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13489. }
  13490. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13491. };
  13492. Scene.prototype._activeMesh = function (mesh) {
  13493. if (mesh.skeleton && this.skeletonsEnabled) {
  13494. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13495. if (!mesh.computeBonesUsingShaders) {
  13496. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13497. }
  13498. }
  13499. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13500. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13501. }
  13502. if (mesh._edgesRenderer) {
  13503. this._edgesRenderers.push(mesh._edgesRenderer);
  13504. }
  13505. if (mesh && mesh.subMeshes) {
  13506. // Submeshes Octrees
  13507. var len;
  13508. var subMeshes;
  13509. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13510. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13511. len = intersections.length;
  13512. subMeshes = intersections.data;
  13513. }
  13514. else {
  13515. subMeshes = mesh.subMeshes;
  13516. len = subMeshes.length;
  13517. }
  13518. for (var subIndex = 0; subIndex < len; subIndex++) {
  13519. var subMesh = subMeshes[subIndex];
  13520. this._evaluateSubMesh(subMesh, mesh);
  13521. }
  13522. }
  13523. };
  13524. Scene.prototype.updateTransformMatrix = function (force) {
  13525. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13526. };
  13527. Scene.prototype._renderForCamera = function (camera) {
  13528. var engine = this._engine;
  13529. this.activeCamera = camera;
  13530. if (!this.activeCamera)
  13531. throw new Error("Active camera not set");
  13532. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13533. // Viewport
  13534. engine.setViewport(this.activeCamera.viewport);
  13535. // Camera
  13536. this.resetCachedMaterial();
  13537. this._renderId++;
  13538. this.updateTransformMatrix();
  13539. if (this.beforeCameraRender) {
  13540. this.beforeCameraRender(this.activeCamera);
  13541. }
  13542. // Meshes
  13543. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13544. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13545. this._evaluateActiveMeshes();
  13546. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13547. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13548. // Skeletons
  13549. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13550. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13551. skeleton.prepare();
  13552. }
  13553. // Software skinning
  13554. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13555. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13556. mesh.applySkeleton(mesh.skeleton);
  13557. }
  13558. // Render targets
  13559. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13560. if (this.renderTargetsEnabled) {
  13561. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13562. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13563. var renderTarget = this._renderTargets.data[renderIndex];
  13564. if (renderTarget._shouldRender()) {
  13565. this._renderId++;
  13566. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13567. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13568. }
  13569. }
  13570. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13571. this._renderId++;
  13572. }
  13573. if (this._renderTargets.length > 0) {
  13574. engine.restoreDefaultFramebuffer();
  13575. }
  13576. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13577. // Prepare Frame
  13578. this.postProcessManager._prepareFrame();
  13579. var beforeRenderDate = BABYLON.Tools.Now;
  13580. // Backgrounds
  13581. var layerIndex;
  13582. var layer;
  13583. if (this.layers.length) {
  13584. engine.setDepthBuffer(false);
  13585. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13586. layer = this.layers[layerIndex];
  13587. if (layer.isBackground) {
  13588. layer.render();
  13589. }
  13590. }
  13591. engine.setDepthBuffer(true);
  13592. }
  13593. // Render
  13594. BABYLON.Tools.StartPerformanceCounter("Main render");
  13595. this._renderingManager.render(null, null, true, true);
  13596. BABYLON.Tools.EndPerformanceCounter("Main render");
  13597. // Bounding boxes
  13598. this._boundingBoxRenderer.render();
  13599. // Edges
  13600. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13601. this._edgesRenderers.data[edgesRendererIndex].render();
  13602. }
  13603. // Lens flares
  13604. if (this.lensFlaresEnabled) {
  13605. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13606. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13607. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13608. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13609. lensFlareSystem.render();
  13610. }
  13611. }
  13612. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13613. }
  13614. // Foregrounds
  13615. if (this.layers.length) {
  13616. engine.setDepthBuffer(false);
  13617. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13618. layer = this.layers[layerIndex];
  13619. if (!layer.isBackground) {
  13620. layer.render();
  13621. }
  13622. }
  13623. engine.setDepthBuffer(true);
  13624. }
  13625. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13626. // Finalize frame
  13627. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13628. // Update camera
  13629. this.activeCamera._updateFromScene();
  13630. // Reset some special arrays
  13631. this._renderTargets.reset();
  13632. if (this.afterCameraRender) {
  13633. this.afterCameraRender(this.activeCamera);
  13634. }
  13635. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13636. };
  13637. Scene.prototype._processSubCameras = function (camera) {
  13638. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13639. this._renderForCamera(camera);
  13640. return;
  13641. }
  13642. // rig cameras
  13643. for (var index = 0; index < camera._rigCameras.length; index++) {
  13644. this._renderForCamera(camera._rigCameras[index]);
  13645. }
  13646. this.activeCamera = camera;
  13647. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13648. // Update camera
  13649. this.activeCamera._updateFromScene();
  13650. };
  13651. Scene.prototype._checkIntersections = function () {
  13652. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13653. var sourceMesh = this._meshesForIntersections.data[index];
  13654. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13655. var action = sourceMesh.actionManager.actions[actionIndex];
  13656. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13657. var parameters = action.getTriggerParameter();
  13658. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13659. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13660. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13661. if (areIntersecting && currentIntersectionInProgress === -1) {
  13662. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13663. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13664. sourceMesh._intersectionsInProgress.push(otherMesh);
  13665. }
  13666. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13667. sourceMesh._intersectionsInProgress.push(otherMesh);
  13668. }
  13669. }
  13670. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13671. //They intersected, and now they don't.
  13672. //is this trigger an exit trigger? execute an event.
  13673. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13674. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13675. }
  13676. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13677. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13678. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13679. }
  13680. }
  13681. }
  13682. }
  13683. }
  13684. };
  13685. Scene.prototype.render = function () {
  13686. var startDate = BABYLON.Tools.Now;
  13687. this._particlesDuration = 0;
  13688. this._spritesDuration = 0;
  13689. this._activeParticles = 0;
  13690. this._renderDuration = 0;
  13691. this._renderTargetsDuration = 0;
  13692. this._evaluateActiveMeshesDuration = 0;
  13693. this._totalVertices = 0;
  13694. this._activeIndices = 0;
  13695. this._activeBones = 0;
  13696. this.getEngine().resetDrawCalls();
  13697. this._meshesForIntersections.reset();
  13698. this.resetCachedMaterial();
  13699. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13700. // Actions
  13701. if (this.actionManager) {
  13702. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13703. }
  13704. //Simplification Queue
  13705. if (!this.simplificationQueue.running) {
  13706. this.simplificationQueue.executeNext();
  13707. }
  13708. // Animations
  13709. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13710. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13711. this._animate();
  13712. // Physics
  13713. if (this._physicsEngine) {
  13714. BABYLON.Tools.StartPerformanceCounter("Physics");
  13715. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13716. BABYLON.Tools.EndPerformanceCounter("Physics");
  13717. }
  13718. // Before render
  13719. if (this.beforeRender) {
  13720. this.beforeRender();
  13721. }
  13722. var callbackIndex;
  13723. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13724. this._onBeforeRenderCallbacks[callbackIndex]();
  13725. }
  13726. // Customs render targets
  13727. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13728. var engine = this.getEngine();
  13729. var currentActiveCamera = this.activeCamera;
  13730. if (this.renderTargetsEnabled) {
  13731. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13732. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13733. var renderTarget = this.customRenderTargets[customIndex];
  13734. if (renderTarget._shouldRender()) {
  13735. this._renderId++;
  13736. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13737. if (!this.activeCamera)
  13738. throw new Error("Active camera not set");
  13739. // Viewport
  13740. engine.setViewport(this.activeCamera.viewport);
  13741. // Camera
  13742. this.updateTransformMatrix();
  13743. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13744. }
  13745. }
  13746. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13747. this._renderId++;
  13748. }
  13749. if (this.customRenderTargets.length > 0) {
  13750. engine.restoreDefaultFramebuffer();
  13751. }
  13752. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13753. this.activeCamera = currentActiveCamera;
  13754. // Procedural textures
  13755. if (this.proceduralTexturesEnabled) {
  13756. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13757. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13758. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13759. if (proceduralTexture._shouldRender()) {
  13760. proceduralTexture.render();
  13761. }
  13762. }
  13763. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13764. }
  13765. // Clear
  13766. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13767. // Shadows
  13768. if (this.shadowsEnabled) {
  13769. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13770. var light = this.lights[lightIndex];
  13771. var shadowGenerator = light.getShadowGenerator();
  13772. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13773. this._renderTargets.push(shadowGenerator.getShadowMap());
  13774. }
  13775. }
  13776. }
  13777. // Depth renderer
  13778. if (this._depthRenderer) {
  13779. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13780. }
  13781. // RenderPipeline
  13782. this.postProcessRenderPipelineManager.update();
  13783. // Multi-cameras?
  13784. if (this.activeCameras.length > 0) {
  13785. var currentRenderId = this._renderId;
  13786. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13787. this._renderId = currentRenderId;
  13788. this._processSubCameras(this.activeCameras[cameraIndex]);
  13789. }
  13790. }
  13791. else {
  13792. if (!this.activeCamera) {
  13793. throw new Error("No camera defined");
  13794. }
  13795. this._processSubCameras(this.activeCamera);
  13796. }
  13797. // Intersection checks
  13798. this._checkIntersections();
  13799. // Update the audio listener attached to the camera
  13800. this._updateAudioParameters();
  13801. // After render
  13802. if (this.afterRender) {
  13803. this.afterRender();
  13804. }
  13805. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13806. this._onAfterRenderCallbacks[callbackIndex]();
  13807. }
  13808. // Cleaning
  13809. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13810. this._toBeDisposed.data[index].dispose();
  13811. this._toBeDisposed[index] = null;
  13812. }
  13813. this._toBeDisposed.reset();
  13814. if (this.dumpNextRenderTargets) {
  13815. this.dumpNextRenderTargets = false;
  13816. }
  13817. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13818. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13819. };
  13820. Scene.prototype._updateAudioParameters = function () {
  13821. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13822. return;
  13823. }
  13824. var listeningCamera;
  13825. var audioEngine = BABYLON.Engine.audioEngine;
  13826. if (this.activeCameras.length > 0) {
  13827. listeningCamera = this.activeCameras[0];
  13828. }
  13829. else {
  13830. listeningCamera = this.activeCamera;
  13831. }
  13832. if (listeningCamera && audioEngine.canUseWebAudio) {
  13833. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13834. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13835. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13836. cameraDirection.normalize();
  13837. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13838. var i;
  13839. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13840. var sound = this.mainSoundTrack.soundCollection[i];
  13841. if (sound.useCustomAttenuation) {
  13842. sound.updateDistanceFromListener();
  13843. }
  13844. }
  13845. for (i = 0; i < this.soundTracks.length; i++) {
  13846. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13847. sound = this.soundTracks[i].soundCollection[j];
  13848. if (sound.useCustomAttenuation) {
  13849. sound.updateDistanceFromListener();
  13850. }
  13851. }
  13852. }
  13853. }
  13854. };
  13855. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13856. // Audio
  13857. get: function () {
  13858. return this._audioEnabled;
  13859. },
  13860. set: function (value) {
  13861. this._audioEnabled = value;
  13862. if (this._audioEnabled) {
  13863. this._enableAudio();
  13864. }
  13865. else {
  13866. this._disableAudio();
  13867. }
  13868. },
  13869. enumerable: true,
  13870. configurable: true
  13871. });
  13872. Scene.prototype._disableAudio = function () {
  13873. var i;
  13874. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13875. this.mainSoundTrack.soundCollection[i].pause();
  13876. }
  13877. for (i = 0; i < this.soundTracks.length; i++) {
  13878. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13879. this.soundTracks[i].soundCollection[j].pause();
  13880. }
  13881. }
  13882. };
  13883. Scene.prototype._enableAudio = function () {
  13884. var i;
  13885. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13886. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13887. this.mainSoundTrack.soundCollection[i].play();
  13888. }
  13889. }
  13890. for (i = 0; i < this.soundTracks.length; i++) {
  13891. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13892. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13893. this.soundTracks[i].soundCollection[j].play();
  13894. }
  13895. }
  13896. }
  13897. };
  13898. Object.defineProperty(Scene.prototype, "headphone", {
  13899. get: function () {
  13900. return this._headphone;
  13901. },
  13902. set: function (value) {
  13903. this._headphone = value;
  13904. if (this._headphone) {
  13905. this._switchAudioModeForHeadphones();
  13906. }
  13907. else {
  13908. this._switchAudioModeForNormalSpeakers();
  13909. }
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Scene.prototype._switchAudioModeForHeadphones = function () {
  13915. this.mainSoundTrack.switchPanningModelToHRTF();
  13916. for (var i = 0; i < this.soundTracks.length; i++) {
  13917. this.soundTracks[i].switchPanningModelToHRTF();
  13918. }
  13919. };
  13920. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13921. this.mainSoundTrack.switchPanningModelToEqualPower();
  13922. for (var i = 0; i < this.soundTracks.length; i++) {
  13923. this.soundTracks[i].switchPanningModelToEqualPower();
  13924. }
  13925. };
  13926. Scene.prototype.enableDepthRenderer = function () {
  13927. if (this._depthRenderer) {
  13928. return this._depthRenderer;
  13929. }
  13930. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13931. return this._depthRenderer;
  13932. };
  13933. Scene.prototype.disableDepthRenderer = function () {
  13934. if (!this._depthRenderer) {
  13935. return;
  13936. }
  13937. this._depthRenderer.dispose();
  13938. this._depthRenderer = null;
  13939. };
  13940. Scene.prototype.dispose = function () {
  13941. this.beforeRender = null;
  13942. this.afterRender = null;
  13943. this.skeletons = [];
  13944. this._boundingBoxRenderer.dispose();
  13945. if (this._depthRenderer) {
  13946. this._depthRenderer.dispose();
  13947. }
  13948. // Debug layer
  13949. this.debugLayer.hide();
  13950. // Events
  13951. if (this.onDispose) {
  13952. this.onDispose();
  13953. }
  13954. this._onBeforeRenderCallbacks = [];
  13955. this._onAfterRenderCallbacks = [];
  13956. this.detachControl();
  13957. // Release sounds & sounds tracks
  13958. this.disposeSounds();
  13959. // Detach cameras
  13960. var canvas = this._engine.getRenderingCanvas();
  13961. var index;
  13962. for (index = 0; index < this.cameras.length; index++) {
  13963. this.cameras[index].detachControl(canvas);
  13964. }
  13965. // Release lights
  13966. while (this.lights.length) {
  13967. this.lights[0].dispose();
  13968. }
  13969. // Release meshes
  13970. while (this.meshes.length) {
  13971. this.meshes[0].dispose(true);
  13972. }
  13973. // Release cameras
  13974. while (this.cameras.length) {
  13975. this.cameras[0].dispose();
  13976. }
  13977. // Release materials
  13978. while (this.materials.length) {
  13979. this.materials[0].dispose();
  13980. }
  13981. // Release particles
  13982. while (this.particleSystems.length) {
  13983. this.particleSystems[0].dispose();
  13984. }
  13985. // Release sprites
  13986. while (this.spriteManagers.length) {
  13987. this.spriteManagers[0].dispose();
  13988. }
  13989. // Release layers
  13990. while (this.layers.length) {
  13991. this.layers[0].dispose();
  13992. }
  13993. // Release textures
  13994. while (this.textures.length) {
  13995. this.textures[0].dispose();
  13996. }
  13997. // Post-processes
  13998. this.postProcessManager.dispose();
  13999. // Physics
  14000. if (this._physicsEngine) {
  14001. this.disablePhysicsEngine();
  14002. }
  14003. // Remove from engine
  14004. index = this._engine.scenes.indexOf(this);
  14005. if (index > -1) {
  14006. this._engine.scenes.splice(index, 1);
  14007. }
  14008. this._engine.wipeCaches();
  14009. };
  14010. // Release sounds & sounds tracks
  14011. Scene.prototype.disposeSounds = function () {
  14012. this.mainSoundTrack.dispose();
  14013. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14014. this.soundTracks[scIndex].dispose();
  14015. }
  14016. };
  14017. // Octrees
  14018. Scene.prototype.getWorldExtends = function () {
  14019. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14020. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14021. for (var index = 0; index < this.meshes.length; index++) {
  14022. var mesh = this.meshes[index];
  14023. mesh.computeWorldMatrix(true);
  14024. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14025. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14026. BABYLON.Tools.CheckExtends(minBox, min, max);
  14027. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14028. }
  14029. return {
  14030. min: min,
  14031. max: max
  14032. };
  14033. };
  14034. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14035. if (maxCapacity === void 0) { maxCapacity = 64; }
  14036. if (maxDepth === void 0) { maxDepth = 2; }
  14037. if (!this._selectionOctree) {
  14038. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14039. }
  14040. var worldExtends = this.getWorldExtends();
  14041. // Update octree
  14042. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14043. return this._selectionOctree;
  14044. };
  14045. // Picking
  14046. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  14047. var engine = this._engine;
  14048. if (!camera) {
  14049. if (!this.activeCamera)
  14050. throw new Error("Active camera not set");
  14051. camera = this.activeCamera;
  14052. }
  14053. var cameraViewport = camera.viewport;
  14054. var viewport = cameraViewport.toGlobal(engine);
  14055. // Moving coordinates to local viewport world
  14056. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14057. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14058. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14059. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14060. };
  14061. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14062. var pickingInfo = null;
  14063. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14064. var mesh = this.meshes[meshIndex];
  14065. if (predicate) {
  14066. if (!predicate(mesh)) {
  14067. continue;
  14068. }
  14069. }
  14070. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14071. continue;
  14072. }
  14073. var world = mesh.getWorldMatrix();
  14074. var ray = rayFunction(world);
  14075. var result = mesh.intersects(ray, fastCheck);
  14076. if (!result || !result.hit)
  14077. continue;
  14078. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14079. continue;
  14080. pickingInfo = result;
  14081. if (fastCheck) {
  14082. break;
  14083. }
  14084. }
  14085. return pickingInfo || new BABYLON.PickingInfo();
  14086. };
  14087. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14088. var _this = this;
  14089. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14090. /// <param name="x">X position on screen</param>
  14091. /// <param name="y">Y position on screen</param>
  14092. /// <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>
  14093. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14094. /// <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>
  14095. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14096. };
  14097. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14098. var _this = this;
  14099. return this._internalPick(function (world) {
  14100. if (!_this._pickWithRayInverseMatrix) {
  14101. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14102. }
  14103. world.invertToRef(_this._pickWithRayInverseMatrix);
  14104. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14105. }, predicate, fastCheck);
  14106. };
  14107. Scene.prototype.setPointerOverMesh = function (mesh) {
  14108. if (this._pointerOverMesh === mesh) {
  14109. return;
  14110. }
  14111. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14112. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14113. }
  14114. this._pointerOverMesh = mesh;
  14115. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14116. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14117. }
  14118. };
  14119. Scene.prototype.getPointerOverMesh = function () {
  14120. return this._pointerOverMesh;
  14121. };
  14122. // Physics
  14123. Scene.prototype.getPhysicsEngine = function () {
  14124. return this._physicsEngine;
  14125. };
  14126. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14127. if (this._physicsEngine) {
  14128. return true;
  14129. }
  14130. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14131. if (!this._physicsEngine.isSupported()) {
  14132. this._physicsEngine = null;
  14133. return false;
  14134. }
  14135. this._physicsEngine._initialize(gravity);
  14136. return true;
  14137. };
  14138. Scene.prototype.disablePhysicsEngine = function () {
  14139. if (!this._physicsEngine) {
  14140. return;
  14141. }
  14142. this._physicsEngine.dispose();
  14143. this._physicsEngine = undefined;
  14144. };
  14145. Scene.prototype.isPhysicsEnabled = function () {
  14146. return this._physicsEngine !== undefined;
  14147. };
  14148. Scene.prototype.setGravity = function (gravity) {
  14149. if (!this._physicsEngine) {
  14150. return;
  14151. }
  14152. this._physicsEngine._setGravity(gravity);
  14153. };
  14154. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14155. if (parts.parts) {
  14156. options = parts;
  14157. parts = parts.parts;
  14158. }
  14159. if (!this._physicsEngine) {
  14160. return null;
  14161. }
  14162. for (var index = 0; index < parts.length; index++) {
  14163. var mesh = parts[index].mesh;
  14164. mesh._physicImpostor = parts[index].impostor;
  14165. mesh._physicsMass = options.mass / parts.length;
  14166. mesh._physicsFriction = options.friction;
  14167. mesh._physicRestitution = options.restitution;
  14168. }
  14169. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14170. };
  14171. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14172. for (var index = 0; index < compound.parts.length; index++) {
  14173. var mesh = compound.parts[index].mesh;
  14174. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14175. this._physicsEngine._unregisterMesh(mesh);
  14176. }
  14177. };
  14178. // Misc.
  14179. Scene.prototype.createDefaultCameraOrLight = function () {
  14180. // Light
  14181. if (this.lights.length === 0) {
  14182. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14183. }
  14184. // Camera
  14185. if (!this.activeCamera) {
  14186. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14187. // Compute position
  14188. var worldExtends = this.getWorldExtends();
  14189. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14190. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14191. camera.setTarget(worldCenter);
  14192. this.activeCamera = camera;
  14193. }
  14194. };
  14195. // Tags
  14196. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14197. if (tagsQuery === undefined) {
  14198. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14199. return list;
  14200. }
  14201. var listByTags = [];
  14202. forEach = forEach || (function (item) { return; });
  14203. for (var i in list) {
  14204. var item = list[i];
  14205. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14206. listByTags.push(item);
  14207. forEach(item);
  14208. }
  14209. }
  14210. return listByTags;
  14211. };
  14212. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14213. return this._getByTags(this.meshes, tagsQuery, forEach);
  14214. };
  14215. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14216. return this._getByTags(this.cameras, tagsQuery, forEach);
  14217. };
  14218. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14219. return this._getByTags(this.lights, tagsQuery, forEach);
  14220. };
  14221. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14222. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14223. };
  14224. // Statics
  14225. Scene._FOGMODE_NONE = 0;
  14226. Scene._FOGMODE_EXP = 1;
  14227. Scene._FOGMODE_EXP2 = 2;
  14228. Scene._FOGMODE_LINEAR = 3;
  14229. Scene.MinDeltaTime = 1.0;
  14230. Scene.MaxDeltaTime = 1000.0;
  14231. return Scene;
  14232. })();
  14233. BABYLON.Scene = Scene;
  14234. })(BABYLON || (BABYLON = {}));
  14235. var BABYLON;
  14236. (function (BABYLON) {
  14237. var VertexBuffer = (function () {
  14238. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14239. if (engine instanceof BABYLON.Mesh) {
  14240. this._engine = engine.getScene().getEngine();
  14241. }
  14242. else {
  14243. this._engine = engine;
  14244. }
  14245. this._updatable = updatable;
  14246. this._data = data;
  14247. if (!postponeInternalCreation) {
  14248. this.create();
  14249. }
  14250. this._kind = kind;
  14251. if (stride) {
  14252. this._strideSize = stride;
  14253. return;
  14254. }
  14255. // Deduce stride from kind
  14256. switch (kind) {
  14257. case VertexBuffer.PositionKind:
  14258. this._strideSize = 3;
  14259. break;
  14260. case VertexBuffer.NormalKind:
  14261. this._strideSize = 3;
  14262. break;
  14263. case VertexBuffer.UVKind:
  14264. case VertexBuffer.UV2Kind:
  14265. case VertexBuffer.UV3Kind:
  14266. case VertexBuffer.UV4Kind:
  14267. case VertexBuffer.UV5Kind:
  14268. case VertexBuffer.UV6Kind:
  14269. this._strideSize = 2;
  14270. break;
  14271. case VertexBuffer.ColorKind:
  14272. this._strideSize = 4;
  14273. break;
  14274. case VertexBuffer.MatricesIndicesKind:
  14275. this._strideSize = 4;
  14276. break;
  14277. case VertexBuffer.MatricesWeightsKind:
  14278. this._strideSize = 4;
  14279. break;
  14280. }
  14281. }
  14282. // Properties
  14283. VertexBuffer.prototype.isUpdatable = function () {
  14284. return this._updatable;
  14285. };
  14286. VertexBuffer.prototype.getData = function () {
  14287. return this._data;
  14288. };
  14289. VertexBuffer.prototype.getBuffer = function () {
  14290. return this._buffer;
  14291. };
  14292. VertexBuffer.prototype.getStrideSize = function () {
  14293. return this._strideSize;
  14294. };
  14295. // Methods
  14296. VertexBuffer.prototype.create = function (data) {
  14297. if (!data && this._buffer) {
  14298. return; // nothing to do
  14299. }
  14300. data = data || this._data;
  14301. if (!this._buffer) {
  14302. if (this._updatable) {
  14303. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14304. }
  14305. else {
  14306. this._buffer = this._engine.createVertexBuffer(data);
  14307. }
  14308. }
  14309. if (this._updatable) {
  14310. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14311. this._data = data;
  14312. }
  14313. };
  14314. VertexBuffer.prototype.update = function (data) {
  14315. this.create(data);
  14316. };
  14317. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14318. if (!this._buffer) {
  14319. return;
  14320. }
  14321. if (this._updatable) {
  14322. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14323. this._data = null;
  14324. }
  14325. };
  14326. VertexBuffer.prototype.dispose = function () {
  14327. if (!this._buffer) {
  14328. return;
  14329. }
  14330. if (this._engine._releaseBuffer(this._buffer)) {
  14331. this._buffer = null;
  14332. }
  14333. };
  14334. Object.defineProperty(VertexBuffer, "PositionKind", {
  14335. get: function () {
  14336. return VertexBuffer._PositionKind;
  14337. },
  14338. enumerable: true,
  14339. configurable: true
  14340. });
  14341. Object.defineProperty(VertexBuffer, "NormalKind", {
  14342. get: function () {
  14343. return VertexBuffer._NormalKind;
  14344. },
  14345. enumerable: true,
  14346. configurable: true
  14347. });
  14348. Object.defineProperty(VertexBuffer, "UVKind", {
  14349. get: function () {
  14350. return VertexBuffer._UVKind;
  14351. },
  14352. enumerable: true,
  14353. configurable: true
  14354. });
  14355. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14356. get: function () {
  14357. return VertexBuffer._UV2Kind;
  14358. },
  14359. enumerable: true,
  14360. configurable: true
  14361. });
  14362. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14363. get: function () {
  14364. return VertexBuffer._UV3Kind;
  14365. },
  14366. enumerable: true,
  14367. configurable: true
  14368. });
  14369. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14370. get: function () {
  14371. return VertexBuffer._UV4Kind;
  14372. },
  14373. enumerable: true,
  14374. configurable: true
  14375. });
  14376. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14377. get: function () {
  14378. return VertexBuffer._UV5Kind;
  14379. },
  14380. enumerable: true,
  14381. configurable: true
  14382. });
  14383. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14384. get: function () {
  14385. return VertexBuffer._UV6Kind;
  14386. },
  14387. enumerable: true,
  14388. configurable: true
  14389. });
  14390. Object.defineProperty(VertexBuffer, "ColorKind", {
  14391. get: function () {
  14392. return VertexBuffer._ColorKind;
  14393. },
  14394. enumerable: true,
  14395. configurable: true
  14396. });
  14397. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14398. get: function () {
  14399. return VertexBuffer._MatricesIndicesKind;
  14400. },
  14401. enumerable: true,
  14402. configurable: true
  14403. });
  14404. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14405. get: function () {
  14406. return VertexBuffer._MatricesWeightsKind;
  14407. },
  14408. enumerable: true,
  14409. configurable: true
  14410. });
  14411. // Enums
  14412. VertexBuffer._PositionKind = "position";
  14413. VertexBuffer._NormalKind = "normal";
  14414. VertexBuffer._UVKind = "uv";
  14415. VertexBuffer._UV2Kind = "uv2";
  14416. VertexBuffer._UV3Kind = "uv3";
  14417. VertexBuffer._UV4Kind = "uv4";
  14418. VertexBuffer._UV5Kind = "uv5";
  14419. VertexBuffer._UV6Kind = "uv6";
  14420. VertexBuffer._ColorKind = "color";
  14421. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14422. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14423. return VertexBuffer;
  14424. })();
  14425. BABYLON.VertexBuffer = VertexBuffer;
  14426. })(BABYLON || (BABYLON = {}));
  14427. var BABYLON;
  14428. (function (BABYLON) {
  14429. /**
  14430. * Creates an instance based on a source mesh.
  14431. */
  14432. var InstancedMesh = (function (_super) {
  14433. __extends(InstancedMesh, _super);
  14434. function InstancedMesh(name, source) {
  14435. _super.call(this, name, source.getScene());
  14436. source.instances.push(this);
  14437. this._sourceMesh = source;
  14438. this.position.copyFrom(source.position);
  14439. this.rotation.copyFrom(source.rotation);
  14440. this.scaling.copyFrom(source.scaling);
  14441. if (source.rotationQuaternion) {
  14442. this.rotationQuaternion = source.rotationQuaternion.clone();
  14443. }
  14444. this.infiniteDistance = source.infiniteDistance;
  14445. this.setPivotMatrix(source.getPivotMatrix());
  14446. this.refreshBoundingInfo();
  14447. this._syncSubMeshes();
  14448. }
  14449. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14450. // Methods
  14451. get: function () {
  14452. return this._sourceMesh.receiveShadows;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. Object.defineProperty(InstancedMesh.prototype, "material", {
  14458. get: function () {
  14459. return this._sourceMesh.material;
  14460. },
  14461. enumerable: true,
  14462. configurable: true
  14463. });
  14464. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14465. get: function () {
  14466. return this._sourceMesh.visibility;
  14467. },
  14468. enumerable: true,
  14469. configurable: true
  14470. });
  14471. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14472. get: function () {
  14473. return this._sourceMesh.skeleton;
  14474. },
  14475. enumerable: true,
  14476. configurable: true
  14477. });
  14478. InstancedMesh.prototype.getTotalVertices = function () {
  14479. return this._sourceMesh.getTotalVertices();
  14480. };
  14481. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14482. get: function () {
  14483. return this._sourceMesh;
  14484. },
  14485. enumerable: true,
  14486. configurable: true
  14487. });
  14488. InstancedMesh.prototype.getVerticesData = function (kind) {
  14489. return this._sourceMesh.getVerticesData(kind);
  14490. };
  14491. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14492. return this._sourceMesh.isVerticesDataPresent(kind);
  14493. };
  14494. InstancedMesh.prototype.getIndices = function () {
  14495. return this._sourceMesh.getIndices();
  14496. };
  14497. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14498. get: function () {
  14499. return this._sourceMesh._positions;
  14500. },
  14501. enumerable: true,
  14502. configurable: true
  14503. });
  14504. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14505. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14506. if (data) {
  14507. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14508. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14509. }
  14510. this._updateBoundingInfo();
  14511. };
  14512. InstancedMesh.prototype._preActivate = function () {
  14513. if (this._currentLOD) {
  14514. this._currentLOD._preActivate();
  14515. }
  14516. };
  14517. InstancedMesh.prototype._activate = function (renderId) {
  14518. if (this._currentLOD) {
  14519. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14520. }
  14521. };
  14522. InstancedMesh.prototype.getLOD = function (camera) {
  14523. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14524. if (this._currentLOD === this.sourceMesh) {
  14525. return this;
  14526. }
  14527. return this._currentLOD;
  14528. };
  14529. InstancedMesh.prototype._syncSubMeshes = function () {
  14530. this.releaseSubMeshes();
  14531. if (this._sourceMesh.subMeshes) {
  14532. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14533. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14534. }
  14535. }
  14536. };
  14537. InstancedMesh.prototype._generatePointsArray = function () {
  14538. return this._sourceMesh._generatePointsArray();
  14539. };
  14540. // Clone
  14541. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14542. var result = this._sourceMesh.createInstance(name);
  14543. // Deep copy
  14544. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14545. // Bounding info
  14546. this.refreshBoundingInfo();
  14547. // Parent
  14548. if (newParent) {
  14549. result.parent = newParent;
  14550. }
  14551. if (!doNotCloneChildren) {
  14552. // Children
  14553. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14554. var mesh = this.getScene().meshes[index];
  14555. if (mesh.parent === this) {
  14556. mesh.clone(mesh.name, result);
  14557. }
  14558. }
  14559. }
  14560. result.computeWorldMatrix(true);
  14561. return result;
  14562. };
  14563. // Dispoe
  14564. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14565. // Remove from mesh
  14566. var index = this._sourceMesh.instances.indexOf(this);
  14567. this._sourceMesh.instances.splice(index, 1);
  14568. _super.prototype.dispose.call(this, doNotRecurse);
  14569. };
  14570. return InstancedMesh;
  14571. })(BABYLON.AbstractMesh);
  14572. BABYLON.InstancedMesh = InstancedMesh;
  14573. })(BABYLON || (BABYLON = {}));
  14574. var BABYLON;
  14575. (function (BABYLON) {
  14576. var _InstancesBatch = (function () {
  14577. function _InstancesBatch() {
  14578. this.mustReturn = false;
  14579. this.visibleInstances = new Array();
  14580. this.renderSelf = new Array();
  14581. }
  14582. return _InstancesBatch;
  14583. })();
  14584. BABYLON._InstancesBatch = _InstancesBatch;
  14585. var Mesh = (function (_super) {
  14586. __extends(Mesh, _super);
  14587. /**
  14588. * @constructor
  14589. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14590. * @param {Scene} scene - The scene to add this mesh to.
  14591. * @param {Node} parent - The parent of this mesh, if it has one
  14592. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14593. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14594. * When false, achieved by calling a clone(), also passing False.
  14595. * This will make creation of children, recursive.
  14596. */
  14597. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14598. if (parent === void 0) { parent = null; }
  14599. _super.call(this, name, scene);
  14600. // Members
  14601. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14602. this.instances = new Array();
  14603. this._LODLevels = new Array();
  14604. this._onBeforeRenderCallbacks = new Array();
  14605. this._onAfterRenderCallbacks = new Array();
  14606. this._visibleInstances = {};
  14607. this._renderIdForInstances = new Array();
  14608. this._batchCache = new _InstancesBatch();
  14609. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14610. this._sideOrientation = Mesh._DEFAULTSIDE;
  14611. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14612. if (source) {
  14613. // Geometry
  14614. if (source._geometry) {
  14615. source._geometry.applyToMesh(this);
  14616. }
  14617. // Deep copy
  14618. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14619. this.id = name + "." + source.id;
  14620. // Material
  14621. this.material = source.material;
  14622. var index;
  14623. if (!doNotCloneChildren) {
  14624. // Children
  14625. for (index = 0; index < scene.meshes.length; index++) {
  14626. var mesh = scene.meshes[index];
  14627. if (mesh.parent === source) {
  14628. // doNotCloneChildren is always going to be False
  14629. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14630. }
  14631. }
  14632. }
  14633. // Particles
  14634. for (index = 0; index < scene.particleSystems.length; index++) {
  14635. var system = scene.particleSystems[index];
  14636. if (system.emitter === source) {
  14637. system.clone(system.name, this);
  14638. }
  14639. }
  14640. this.computeWorldMatrix(true);
  14641. }
  14642. // Parent
  14643. if (parent !== null) {
  14644. this.parent = parent;
  14645. }
  14646. }
  14647. Object.defineProperty(Mesh, "FRONTSIDE", {
  14648. get: function () {
  14649. return Mesh._FRONTSIDE;
  14650. },
  14651. enumerable: true,
  14652. configurable: true
  14653. });
  14654. Object.defineProperty(Mesh, "BACKSIDE", {
  14655. get: function () {
  14656. return Mesh._BACKSIDE;
  14657. },
  14658. enumerable: true,
  14659. configurable: true
  14660. });
  14661. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14662. get: function () {
  14663. return Mesh._DOUBLESIDE;
  14664. },
  14665. enumerable: true,
  14666. configurable: true
  14667. });
  14668. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14669. get: function () {
  14670. return Mesh._DEFAULTSIDE;
  14671. },
  14672. enumerable: true,
  14673. configurable: true
  14674. });
  14675. Object.defineProperty(Mesh, "NO_CAP", {
  14676. get: function () {
  14677. return Mesh._NO_CAP;
  14678. },
  14679. enumerable: true,
  14680. configurable: true
  14681. });
  14682. Object.defineProperty(Mesh, "CAP_START", {
  14683. get: function () {
  14684. return Mesh._CAP_START;
  14685. },
  14686. enumerable: true,
  14687. configurable: true
  14688. });
  14689. Object.defineProperty(Mesh, "CAP_END", {
  14690. get: function () {
  14691. return Mesh._CAP_END;
  14692. },
  14693. enumerable: true,
  14694. configurable: true
  14695. });
  14696. Object.defineProperty(Mesh, "CAP_ALL", {
  14697. get: function () {
  14698. return Mesh._CAP_ALL;
  14699. },
  14700. enumerable: true,
  14701. configurable: true
  14702. });
  14703. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14704. // Methods
  14705. get: function () {
  14706. return this._LODLevels.length > 0;
  14707. },
  14708. enumerable: true,
  14709. configurable: true
  14710. });
  14711. Mesh.prototype._sortLODLevels = function () {
  14712. this._LODLevels.sort(function (a, b) {
  14713. if (a.distance < b.distance) {
  14714. return 1;
  14715. }
  14716. if (a.distance > b.distance) {
  14717. return -1;
  14718. }
  14719. return 0;
  14720. });
  14721. };
  14722. /**
  14723. * Add a mesh as LOD level triggered at the given distance.
  14724. * @param {number} distance - the distance from the center of the object to show this level
  14725. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14726. * @return {BABYLON.Mesh} this mesh (for chaining)
  14727. */
  14728. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14729. if (mesh && mesh._masterMesh) {
  14730. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14731. return this;
  14732. }
  14733. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14734. this._LODLevels.push(level);
  14735. if (mesh) {
  14736. mesh._masterMesh = this;
  14737. }
  14738. this._sortLODLevels();
  14739. return this;
  14740. };
  14741. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14742. for (var index = 0; index < this._LODLevels.length; index++) {
  14743. var level = this._LODLevels[index];
  14744. if (level.distance === distance) {
  14745. return level.mesh;
  14746. }
  14747. }
  14748. return null;
  14749. };
  14750. /**
  14751. * Remove a mesh from the LOD array
  14752. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14753. * @return {BABYLON.Mesh} this mesh (for chaining)
  14754. */
  14755. Mesh.prototype.removeLODLevel = function (mesh) {
  14756. for (var index = 0; index < this._LODLevels.length; index++) {
  14757. if (this._LODLevels[index].mesh === mesh) {
  14758. this._LODLevels.splice(index, 1);
  14759. if (mesh) {
  14760. mesh._masterMesh = null;
  14761. }
  14762. }
  14763. }
  14764. this._sortLODLevels();
  14765. return this;
  14766. };
  14767. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14768. if (!this._LODLevels || this._LODLevels.length === 0) {
  14769. return this;
  14770. }
  14771. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14772. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14773. if (this.onLODLevelSelection) {
  14774. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14775. }
  14776. return this;
  14777. }
  14778. for (var index = 0; index < this._LODLevels.length; index++) {
  14779. var level = this._LODLevels[index];
  14780. if (level.distance < distanceToCamera) {
  14781. if (level.mesh) {
  14782. level.mesh._preActivate();
  14783. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14784. }
  14785. if (this.onLODLevelSelection) {
  14786. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14787. }
  14788. return level.mesh;
  14789. }
  14790. }
  14791. if (this.onLODLevelSelection) {
  14792. this.onLODLevelSelection(distanceToCamera, this, this);
  14793. }
  14794. return this;
  14795. };
  14796. Object.defineProperty(Mesh.prototype, "geometry", {
  14797. get: function () {
  14798. return this._geometry;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Mesh.prototype.getTotalVertices = function () {
  14804. if (!this._geometry) {
  14805. return 0;
  14806. }
  14807. return this._geometry.getTotalVertices();
  14808. };
  14809. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14810. if (!this._geometry) {
  14811. return null;
  14812. }
  14813. return this._geometry.getVerticesData(kind, copyWhenShared);
  14814. };
  14815. Mesh.prototype.getVertexBuffer = function (kind) {
  14816. if (!this._geometry) {
  14817. return undefined;
  14818. }
  14819. return this._geometry.getVertexBuffer(kind);
  14820. };
  14821. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14822. if (!this._geometry) {
  14823. if (this._delayInfo) {
  14824. return this._delayInfo.indexOf(kind) !== -1;
  14825. }
  14826. return false;
  14827. }
  14828. return this._geometry.isVerticesDataPresent(kind);
  14829. };
  14830. Mesh.prototype.getVerticesDataKinds = function () {
  14831. if (!this._geometry) {
  14832. var result = [];
  14833. if (this._delayInfo) {
  14834. for (var kind in this._delayInfo) {
  14835. result.push(kind);
  14836. }
  14837. }
  14838. return result;
  14839. }
  14840. return this._geometry.getVerticesDataKinds();
  14841. };
  14842. Mesh.prototype.getTotalIndices = function () {
  14843. if (!this._geometry) {
  14844. return 0;
  14845. }
  14846. return this._geometry.getTotalIndices();
  14847. };
  14848. Mesh.prototype.getIndices = function (copyWhenShared) {
  14849. if (!this._geometry) {
  14850. return [];
  14851. }
  14852. return this._geometry.getIndices(copyWhenShared);
  14853. };
  14854. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14855. get: function () {
  14856. return this._masterMesh !== null && this._masterMesh !== undefined;
  14857. },
  14858. enumerable: true,
  14859. configurable: true
  14860. });
  14861. Mesh.prototype.isReady = function () {
  14862. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14863. return false;
  14864. }
  14865. return _super.prototype.isReady.call(this);
  14866. };
  14867. Mesh.prototype.isDisposed = function () {
  14868. return this._isDisposed;
  14869. };
  14870. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14871. get: function () {
  14872. return this._sideOrientation;
  14873. },
  14874. set: function (sideO) {
  14875. this._sideOrientation = sideO;
  14876. },
  14877. enumerable: true,
  14878. configurable: true
  14879. });
  14880. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14881. get: function () {
  14882. return this._areNormalsFrozen;
  14883. },
  14884. enumerable: true,
  14885. configurable: true
  14886. });
  14887. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14888. Mesh.prototype.freezeNormals = function () {
  14889. this._areNormalsFrozen = true;
  14890. };
  14891. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14892. Mesh.prototype.unfreezeNormals = function () {
  14893. this._areNormalsFrozen = false;
  14894. };
  14895. // Methods
  14896. Mesh.prototype._preActivate = function () {
  14897. var sceneRenderId = this.getScene().getRenderId();
  14898. if (this._preActivateId === sceneRenderId) {
  14899. return;
  14900. }
  14901. this._preActivateId = sceneRenderId;
  14902. this._visibleInstances = null;
  14903. };
  14904. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14905. if (!this._visibleInstances) {
  14906. this._visibleInstances = {};
  14907. this._visibleInstances.defaultRenderId = renderId;
  14908. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14909. }
  14910. if (!this._visibleInstances[renderId]) {
  14911. this._visibleInstances[renderId] = new Array();
  14912. }
  14913. this._visibleInstances[renderId].push(instance);
  14914. };
  14915. Mesh.prototype.refreshBoundingInfo = function () {
  14916. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14917. if (data) {
  14918. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14919. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14920. }
  14921. if (this.subMeshes) {
  14922. for (var index = 0; index < this.subMeshes.length; index++) {
  14923. this.subMeshes[index].refreshBoundingInfo();
  14924. }
  14925. }
  14926. this._updateBoundingInfo();
  14927. };
  14928. Mesh.prototype._createGlobalSubMesh = function () {
  14929. var totalVertices = this.getTotalVertices();
  14930. if (!totalVertices || !this.getIndices()) {
  14931. return null;
  14932. }
  14933. this.releaseSubMeshes();
  14934. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14935. };
  14936. Mesh.prototype.subdivide = function (count) {
  14937. if (count < 1) {
  14938. return;
  14939. }
  14940. var totalIndices = this.getTotalIndices();
  14941. var subdivisionSize = (totalIndices / count) | 0;
  14942. var offset = 0;
  14943. // Ensure that subdivisionSize is a multiple of 3
  14944. while (subdivisionSize % 3 !== 0) {
  14945. subdivisionSize++;
  14946. }
  14947. this.releaseSubMeshes();
  14948. for (var index = 0; index < count; index++) {
  14949. if (offset >= totalIndices) {
  14950. break;
  14951. }
  14952. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14953. offset += subdivisionSize;
  14954. }
  14955. this.synchronizeInstances();
  14956. };
  14957. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14958. if (kind instanceof Array) {
  14959. var temp = data;
  14960. data = kind;
  14961. kind = temp;
  14962. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14963. }
  14964. if (!this._geometry) {
  14965. var vertexData = new BABYLON.VertexData();
  14966. vertexData.set(data, kind);
  14967. var scene = this.getScene();
  14968. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14969. }
  14970. else {
  14971. this._geometry.setVerticesData(kind, data, updatable, stride);
  14972. }
  14973. };
  14974. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14975. if (!this._geometry) {
  14976. return;
  14977. }
  14978. if (!makeItUnique) {
  14979. this._geometry.updateVerticesData(kind, data, updateExtends);
  14980. }
  14981. else {
  14982. this.makeGeometryUnique();
  14983. this.updateVerticesData(kind, data, updateExtends, false);
  14984. }
  14985. };
  14986. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14987. if (!this._geometry) {
  14988. return;
  14989. }
  14990. if (!makeItUnique) {
  14991. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14992. }
  14993. else {
  14994. this.makeGeometryUnique();
  14995. this.updateVerticesDataDirectly(kind, data, offset, false);
  14996. }
  14997. };
  14998. // Mesh positions update function :
  14999. // updates the mesh positions according to the positionFunction returned values.
  15000. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15001. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15002. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15003. if (computeNormals === void 0) { computeNormals = true; }
  15004. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15005. positionFunction(positions);
  15006. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15007. if (computeNormals) {
  15008. var indices = this.getIndices();
  15009. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15010. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15011. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15012. }
  15013. };
  15014. Mesh.prototype.makeGeometryUnique = function () {
  15015. if (!this._geometry) {
  15016. return;
  15017. }
  15018. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15019. geometry.applyToMesh(this);
  15020. };
  15021. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15022. if (!this._geometry) {
  15023. var vertexData = new BABYLON.VertexData();
  15024. vertexData.indices = indices;
  15025. var scene = this.getScene();
  15026. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15027. }
  15028. else {
  15029. this._geometry.setIndices(indices, totalVertices);
  15030. }
  15031. };
  15032. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15033. var engine = this.getScene().getEngine();
  15034. // Wireframe
  15035. var indexToBind;
  15036. switch (fillMode) {
  15037. case BABYLON.Material.PointFillMode:
  15038. indexToBind = null;
  15039. break;
  15040. case BABYLON.Material.WireFrameFillMode:
  15041. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15042. break;
  15043. default:
  15044. case BABYLON.Material.TriangleFillMode:
  15045. indexToBind = this._geometry.getIndexBuffer();
  15046. break;
  15047. }
  15048. // VBOs
  15049. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15050. };
  15051. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15052. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15053. return;
  15054. }
  15055. var engine = this.getScene().getEngine();
  15056. // Draw order
  15057. switch (fillMode) {
  15058. case BABYLON.Material.PointFillMode:
  15059. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15060. break;
  15061. case BABYLON.Material.WireFrameFillMode:
  15062. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15063. break;
  15064. default:
  15065. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15066. }
  15067. };
  15068. Mesh.prototype.registerBeforeRender = function (func) {
  15069. this._onBeforeRenderCallbacks.push(func);
  15070. };
  15071. Mesh.prototype.unregisterBeforeRender = function (func) {
  15072. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15073. if (index > -1) {
  15074. this._onBeforeRenderCallbacks.splice(index, 1);
  15075. }
  15076. };
  15077. Mesh.prototype.registerAfterRender = function (func) {
  15078. this._onAfterRenderCallbacks.push(func);
  15079. };
  15080. Mesh.prototype.unregisterAfterRender = function (func) {
  15081. var index = this._onAfterRenderCallbacks.indexOf(func);
  15082. if (index > -1) {
  15083. this._onAfterRenderCallbacks.splice(index, 1);
  15084. }
  15085. };
  15086. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15087. var scene = this.getScene();
  15088. this._batchCache.mustReturn = false;
  15089. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15090. this._batchCache.visibleInstances[subMeshId] = null;
  15091. if (this._visibleInstances) {
  15092. var currentRenderId = scene.getRenderId();
  15093. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15094. var selfRenderId = this._renderId;
  15095. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15096. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15097. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15098. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15099. }
  15100. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15101. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15102. this._batchCache.mustReturn = true;
  15103. return this._batchCache;
  15104. }
  15105. if (currentRenderId !== selfRenderId) {
  15106. this._batchCache.renderSelf[subMeshId] = false;
  15107. }
  15108. }
  15109. this._renderIdForInstances[subMeshId] = currentRenderId;
  15110. }
  15111. return this._batchCache;
  15112. };
  15113. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15114. var visibleInstances = batch.visibleInstances[subMesh._id];
  15115. var matricesCount = visibleInstances.length + 1;
  15116. var bufferSize = matricesCount * 16 * 4;
  15117. while (this._instancesBufferSize < bufferSize) {
  15118. this._instancesBufferSize *= 2;
  15119. }
  15120. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15121. if (this._worldMatricesInstancesBuffer) {
  15122. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15123. }
  15124. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15125. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15126. }
  15127. var offset = 0;
  15128. var instancesCount = 0;
  15129. var world = this.getWorldMatrix();
  15130. if (batch.renderSelf[subMesh._id]) {
  15131. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15132. offset += 16;
  15133. instancesCount++;
  15134. }
  15135. if (visibleInstances) {
  15136. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15137. var instance = visibleInstances[instanceIndex];
  15138. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15139. offset += 16;
  15140. instancesCount++;
  15141. }
  15142. }
  15143. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15144. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15145. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15146. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15147. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15148. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15149. this._draw(subMesh, fillMode, instancesCount);
  15150. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15151. };
  15152. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15153. var scene = this.getScene();
  15154. var engine = scene.getEngine();
  15155. if (hardwareInstancedRendering) {
  15156. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15157. }
  15158. else {
  15159. if (batch.renderSelf[subMesh._id]) {
  15160. // Draw
  15161. if (onBeforeDraw) {
  15162. onBeforeDraw(false, this.getWorldMatrix());
  15163. }
  15164. this._draw(subMesh, fillMode);
  15165. }
  15166. if (batch.visibleInstances[subMesh._id]) {
  15167. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15168. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15169. // World
  15170. var world = instance.getWorldMatrix();
  15171. if (onBeforeDraw) {
  15172. onBeforeDraw(true, world);
  15173. }
  15174. // Draw
  15175. this._draw(subMesh, fillMode);
  15176. }
  15177. }
  15178. }
  15179. };
  15180. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15181. var scene = this.getScene();
  15182. // Managing instances
  15183. var batch = this._getInstancesRenderList(subMesh._id);
  15184. if (batch.mustReturn) {
  15185. return;
  15186. }
  15187. // Checking geometry state
  15188. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15189. return;
  15190. }
  15191. var callbackIndex;
  15192. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15193. this._onBeforeRenderCallbacks[callbackIndex](this);
  15194. }
  15195. var engine = scene.getEngine();
  15196. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15197. // Material
  15198. var effectiveMaterial = subMesh.getMaterial();
  15199. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15200. return;
  15201. }
  15202. // Outline - step 1
  15203. var savedDepthWrite = engine.getDepthWrite();
  15204. if (this.renderOutline) {
  15205. engine.setDepthWrite(false);
  15206. scene.getOutlineRenderer().render(subMesh, batch);
  15207. engine.setDepthWrite(savedDepthWrite);
  15208. }
  15209. effectiveMaterial._preBind();
  15210. var effect = effectiveMaterial.getEffect();
  15211. // Bind
  15212. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15213. this._bind(subMesh, effect, fillMode);
  15214. var world = this.getWorldMatrix();
  15215. effectiveMaterial.bind(world, this);
  15216. // Alpha mode
  15217. if (enableAlphaMode) {
  15218. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15219. }
  15220. // Draw
  15221. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15222. if (isInstance) {
  15223. effectiveMaterial.bindOnlyWorldMatrix(world);
  15224. }
  15225. });
  15226. // Unbind
  15227. effectiveMaterial.unbind();
  15228. // Outline - step 2
  15229. if (this.renderOutline && savedDepthWrite) {
  15230. engine.setDepthWrite(true);
  15231. engine.setColorWrite(false);
  15232. scene.getOutlineRenderer().render(subMesh, batch);
  15233. engine.setColorWrite(true);
  15234. }
  15235. // Overlay
  15236. if (this.renderOverlay) {
  15237. var currentMode = engine.getAlphaMode();
  15238. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15239. scene.getOutlineRenderer().render(subMesh, batch, true);
  15240. engine.setAlphaMode(currentMode);
  15241. }
  15242. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15243. this._onAfterRenderCallbacks[callbackIndex](this);
  15244. }
  15245. };
  15246. Mesh.prototype.getEmittedParticleSystems = function () {
  15247. var results = new Array();
  15248. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15249. var particleSystem = this.getScene().particleSystems[index];
  15250. if (particleSystem.emitter === this) {
  15251. results.push(particleSystem);
  15252. }
  15253. }
  15254. return results;
  15255. };
  15256. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15257. var results = new Array();
  15258. var descendants = this.getDescendants();
  15259. descendants.push(this);
  15260. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15261. var particleSystem = this.getScene().particleSystems[index];
  15262. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15263. results.push(particleSystem);
  15264. }
  15265. }
  15266. return results;
  15267. };
  15268. Mesh.prototype.getChildren = function () {
  15269. var results = [];
  15270. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15271. var mesh = this.getScene().meshes[index];
  15272. if (mesh.parent === this) {
  15273. results.push(mesh);
  15274. }
  15275. }
  15276. return results;
  15277. };
  15278. Mesh.prototype._checkDelayState = function () {
  15279. var _this = this;
  15280. var that = this;
  15281. var scene = this.getScene();
  15282. if (this._geometry) {
  15283. this._geometry.load(scene);
  15284. }
  15285. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15286. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15287. scene._addPendingData(that);
  15288. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15289. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15290. if (data instanceof ArrayBuffer) {
  15291. _this._delayLoadingFunction(data, _this);
  15292. }
  15293. else {
  15294. _this._delayLoadingFunction(JSON.parse(data), _this);
  15295. }
  15296. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15297. scene._removePendingData(_this);
  15298. }, function () { }, scene.database, getBinaryData);
  15299. }
  15300. };
  15301. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15302. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15303. return false;
  15304. }
  15305. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15306. return false;
  15307. }
  15308. this._checkDelayState();
  15309. return true;
  15310. };
  15311. Mesh.prototype.setMaterialByID = function (id) {
  15312. var materials = this.getScene().materials;
  15313. var index;
  15314. for (index = 0; index < materials.length; index++) {
  15315. if (materials[index].id === id) {
  15316. this.material = materials[index];
  15317. return;
  15318. }
  15319. }
  15320. // Multi
  15321. var multiMaterials = this.getScene().multiMaterials;
  15322. for (index = 0; index < multiMaterials.length; index++) {
  15323. if (multiMaterials[index].id === id) {
  15324. this.material = multiMaterials[index];
  15325. return;
  15326. }
  15327. }
  15328. };
  15329. Mesh.prototype.getAnimatables = function () {
  15330. var results = [];
  15331. if (this.material) {
  15332. results.push(this.material);
  15333. }
  15334. if (this.skeleton) {
  15335. results.push(this.skeleton);
  15336. }
  15337. return results;
  15338. };
  15339. // Geometry
  15340. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15341. // Position
  15342. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15343. return;
  15344. }
  15345. this._resetPointsArrayCache();
  15346. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15347. var temp = [];
  15348. var index;
  15349. for (index = 0; index < data.length; index += 3) {
  15350. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15351. }
  15352. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15353. // Normals
  15354. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15355. return;
  15356. }
  15357. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15358. temp = [];
  15359. for (index = 0; index < data.length; index += 3) {
  15360. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15361. }
  15362. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15363. // flip faces?
  15364. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15365. this.flipFaces();
  15366. }
  15367. };
  15368. // Will apply current transform to mesh and reset world matrix
  15369. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15370. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15371. this.scaling.copyFromFloats(1, 1, 1);
  15372. this.position.copyFromFloats(0, 0, 0);
  15373. this.rotation.copyFromFloats(0, 0, 0);
  15374. //only if quaternion is already set
  15375. if (this.rotationQuaternion) {
  15376. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15377. }
  15378. this._worldMatrix = BABYLON.Matrix.Identity();
  15379. };
  15380. // Cache
  15381. Mesh.prototype._resetPointsArrayCache = function () {
  15382. this._positions = null;
  15383. };
  15384. Mesh.prototype._generatePointsArray = function () {
  15385. if (this._positions)
  15386. return true;
  15387. this._positions = [];
  15388. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15389. if (!data) {
  15390. return false;
  15391. }
  15392. for (var index = 0; index < data.length; index += 3) {
  15393. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15394. }
  15395. return true;
  15396. };
  15397. // Clone
  15398. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15399. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15400. };
  15401. // Dispose
  15402. Mesh.prototype.dispose = function (doNotRecurse) {
  15403. if (this._geometry) {
  15404. this._geometry.releaseForMesh(this, true);
  15405. }
  15406. // Instances
  15407. if (this._worldMatricesInstancesBuffer) {
  15408. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15409. this._worldMatricesInstancesBuffer = null;
  15410. }
  15411. while (this.instances.length) {
  15412. this.instances[0].dispose();
  15413. }
  15414. _super.prototype.dispose.call(this, doNotRecurse);
  15415. };
  15416. // Geometric tools
  15417. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15418. var _this = this;
  15419. var scene = this.getScene();
  15420. var onload = function (img) {
  15421. // Getting height map data
  15422. var canvas = document.createElement("canvas");
  15423. var context = canvas.getContext("2d");
  15424. var heightMapWidth = img.width;
  15425. var heightMapHeight = img.height;
  15426. canvas.width = heightMapWidth;
  15427. canvas.height = heightMapHeight;
  15428. context.drawImage(img, 0, 0);
  15429. // Create VertexData from map data
  15430. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15431. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15432. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15433. //execute success callback, if set
  15434. if (onSuccess) {
  15435. onSuccess(_this);
  15436. }
  15437. };
  15438. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15439. };
  15440. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15441. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15442. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15443. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15444. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15445. return;
  15446. }
  15447. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15448. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15449. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15450. var position = BABYLON.Vector3.Zero();
  15451. var normal = BABYLON.Vector3.Zero();
  15452. var uv = BABYLON.Vector2.Zero();
  15453. for (var index = 0; index < positions.length; index += 3) {
  15454. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15455. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15456. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15457. // Compute height
  15458. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15459. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15460. var pos = (u + v * heightMapWidth) * 4;
  15461. var r = buffer[pos] / 255.0;
  15462. var g = buffer[pos + 1] / 255.0;
  15463. var b = buffer[pos + 2] / 255.0;
  15464. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15465. normal.normalize();
  15466. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15467. position = position.add(normal);
  15468. position.toArray(positions, index);
  15469. }
  15470. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15471. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15472. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15473. };
  15474. Mesh.prototype.convertToFlatShadedMesh = function () {
  15475. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15476. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15477. var kinds = this.getVerticesDataKinds();
  15478. var vbs = [];
  15479. var data = [];
  15480. var newdata = [];
  15481. var updatableNormals = false;
  15482. var kindIndex;
  15483. var kind;
  15484. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15485. kind = kinds[kindIndex];
  15486. var vertexBuffer = this.getVertexBuffer(kind);
  15487. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15488. updatableNormals = vertexBuffer.isUpdatable();
  15489. kinds.splice(kindIndex, 1);
  15490. kindIndex--;
  15491. continue;
  15492. }
  15493. vbs[kind] = vertexBuffer;
  15494. data[kind] = vbs[kind].getData();
  15495. newdata[kind] = [];
  15496. }
  15497. // Save previous submeshes
  15498. var previousSubmeshes = this.subMeshes.slice(0);
  15499. var indices = this.getIndices();
  15500. var totalIndices = this.getTotalIndices();
  15501. // Generating unique vertices per face
  15502. var index;
  15503. for (index = 0; index < totalIndices; index++) {
  15504. var vertexIndex = indices[index];
  15505. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15506. kind = kinds[kindIndex];
  15507. var stride = vbs[kind].getStrideSize();
  15508. for (var offset = 0; offset < stride; offset++) {
  15509. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15510. }
  15511. }
  15512. }
  15513. // Updating faces & normal
  15514. var normals = [];
  15515. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15516. for (index = 0; index < totalIndices; index += 3) {
  15517. indices[index] = index;
  15518. indices[index + 1] = index + 1;
  15519. indices[index + 2] = index + 2;
  15520. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15521. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15522. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15523. var p1p2 = p1.subtract(p2);
  15524. var p3p2 = p3.subtract(p2);
  15525. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15526. // Store same normals for every vertex
  15527. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15528. normals.push(normal.x);
  15529. normals.push(normal.y);
  15530. normals.push(normal.z);
  15531. }
  15532. }
  15533. this.setIndices(indices);
  15534. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15535. // Updating vertex buffers
  15536. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15537. kind = kinds[kindIndex];
  15538. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15539. }
  15540. // Updating submeshes
  15541. this.releaseSubMeshes();
  15542. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15543. var previousOne = previousSubmeshes[submeshIndex];
  15544. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15545. }
  15546. this.synchronizeInstances();
  15547. };
  15548. // will inverse faces orientations, and invert normals too if specified
  15549. Mesh.prototype.flipFaces = function (flipNormals) {
  15550. if (flipNormals === void 0) { flipNormals = false; }
  15551. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15552. var i;
  15553. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15554. for (i = 0; i < vertex_data.normals.length; i++) {
  15555. vertex_data.normals[i] *= -1;
  15556. }
  15557. }
  15558. var temp;
  15559. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15560. // reassign indices
  15561. temp = vertex_data.indices[i + 1];
  15562. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15563. vertex_data.indices[i + 2] = temp;
  15564. }
  15565. vertex_data.applyToMesh(this);
  15566. };
  15567. // Instances
  15568. Mesh.prototype.createInstance = function (name) {
  15569. return new BABYLON.InstancedMesh(name, this);
  15570. };
  15571. Mesh.prototype.synchronizeInstances = function () {
  15572. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15573. var instance = this.instances[instanceIndex];
  15574. instance._syncSubMeshes();
  15575. }
  15576. };
  15577. /**
  15578. * Simplify the mesh according to the given array of settings.
  15579. * Function will return immediately and will simplify async.
  15580. * @param settings a collection of simplification settings.
  15581. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15582. * @param type the type of simplification to run.
  15583. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15584. */
  15585. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15586. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15587. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15588. this.getScene().simplificationQueue.addTask({
  15589. settings: settings,
  15590. parallelProcessing: parallelProcessing,
  15591. mesh: this,
  15592. simplificationType: simplificationType,
  15593. successCallback: successCallback
  15594. });
  15595. };
  15596. /**
  15597. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15598. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15599. * This should be used together with the simplification to avoid disappearing triangles.
  15600. * @param successCallback an optional success callback to be called after the optimization finished.
  15601. */
  15602. Mesh.prototype.optimizeIndices = function (successCallback) {
  15603. var _this = this;
  15604. var indices = this.getIndices();
  15605. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15606. var vectorPositions = [];
  15607. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15608. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15609. }
  15610. var dupes = [];
  15611. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15612. var realPos = vectorPositions.length - 1 - iteration;
  15613. var testedPosition = vectorPositions[realPos];
  15614. for (var j = 0; j < realPos; ++j) {
  15615. var againstPosition = vectorPositions[j];
  15616. if (testedPosition.equals(againstPosition)) {
  15617. dupes[realPos] = j;
  15618. break;
  15619. }
  15620. }
  15621. }, function () {
  15622. for (var i = 0; i < indices.length; ++i) {
  15623. indices[i] = dupes[indices[i]] || indices[i];
  15624. }
  15625. //indices are now reordered
  15626. var originalSubMeshes = _this.subMeshes.slice(0);
  15627. _this.setIndices(indices);
  15628. _this.subMeshes = originalSubMeshes;
  15629. if (successCallback) {
  15630. successCallback(_this);
  15631. }
  15632. });
  15633. };
  15634. Mesh.CreateRibbon = function (name, options, closeArrayOrScene, closePath, offset, scene, updatable, sideOrientation, instance) {
  15635. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15636. if (instance === void 0) { instance = null; }
  15637. var pathArray;
  15638. var closeArray;
  15639. if (Array.isArray(options)) {
  15640. pathArray = options;
  15641. closeArray = closeArrayOrScene;
  15642. if (!instance) {
  15643. options = {
  15644. pathArray: pathArray,
  15645. closeArray: closeArray,
  15646. closePath: closePath,
  15647. offset: offset,
  15648. updatable: updatable,
  15649. sideOrientation: sideOrientation
  15650. };
  15651. }
  15652. }
  15653. else {
  15654. scene = closeArrayOrScene;
  15655. pathArray = options.pathArray;
  15656. closeArray = options.closeArray;
  15657. closePath = options.closePath;
  15658. offset = options.offset;
  15659. sideOrientation = options.sideOrientation;
  15660. instance = options.instance;
  15661. updatable = options.updatable;
  15662. }
  15663. if (instance) {
  15664. // positionFunction : ribbon case
  15665. // only pathArray and sideOrientation parameters are taken into account for positions update
  15666. var positionFunction = function (positions) {
  15667. var minlg = pathArray[0].length;
  15668. var i = 0;
  15669. var ns = (instance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15670. for (var si = 1; si <= ns; si++) {
  15671. for (var p = 0; p < pathArray.length; p++) {
  15672. var path = pathArray[p];
  15673. var l = path.length;
  15674. minlg = (minlg < l) ? minlg : l;
  15675. var j = 0;
  15676. while (j < minlg) {
  15677. positions[i] = path[j].x;
  15678. positions[i + 1] = path[j].y;
  15679. positions[i + 2] = path[j].z;
  15680. j++;
  15681. i += 3;
  15682. }
  15683. if (instance._closePath) {
  15684. positions[i] = path[0].x;
  15685. positions[i + 1] = path[0].y;
  15686. positions[i + 2] = path[0].z;
  15687. i += 3;
  15688. }
  15689. }
  15690. }
  15691. };
  15692. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15693. positionFunction(positions);
  15694. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15695. if (!(instance.areNormalsFrozen)) {
  15696. var indices = instance.getIndices();
  15697. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15698. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15699. if (instance._closePath) {
  15700. var indexFirst = 0;
  15701. var indexLast = 0;
  15702. for (var p = 0; p < pathArray.length; p++) {
  15703. indexFirst = instance._idx[p] * 3;
  15704. if (p + 1 < pathArray.length) {
  15705. indexLast = (instance._idx[p + 1] - 1) * 3;
  15706. }
  15707. else {
  15708. indexLast = normals.length - 3;
  15709. }
  15710. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15711. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15712. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15713. normals[indexLast] = normals[indexFirst];
  15714. normals[indexLast + 1] = normals[indexFirst + 1];
  15715. normals[indexLast + 2] = normals[indexFirst + 2];
  15716. }
  15717. }
  15718. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15719. }
  15720. return instance;
  15721. }
  15722. else {
  15723. var ribbon = new Mesh(name, scene);
  15724. ribbon.sideOrientation = sideOrientation;
  15725. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15726. if (closePath) {
  15727. ribbon._idx = vertexData._idx;
  15728. }
  15729. ribbon._closePath = closePath;
  15730. ribbon._closeArray = closeArray;
  15731. vertexData.applyToMesh(ribbon, updatable);
  15732. return ribbon;
  15733. }
  15734. };
  15735. Mesh.CreateDisc = function (name, options, tessellationOrScene, scene, updatable, sideOrientation) {
  15736. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15737. if (tessellationOrScene instanceof BABYLON.Scene) {
  15738. scene = tessellationOrScene;
  15739. }
  15740. else {
  15741. var radius = options;
  15742. options = {
  15743. radius: radius,
  15744. tessellation: tessellationOrScene,
  15745. sideOrientation: sideOrientation
  15746. };
  15747. }
  15748. var disc = new Mesh(name, scene);
  15749. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15750. vertexData.applyToMesh(disc, updatable || options.updatable);
  15751. return disc;
  15752. };
  15753. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15754. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15755. // Check parameters
  15756. updatable = updatable || options.updatable;
  15757. if (typeof options === 'number') {
  15758. var size = options;
  15759. options = {
  15760. size: size,
  15761. sideOrientation: sideOrientation
  15762. };
  15763. }
  15764. var box = new Mesh(name, scene);
  15765. var vertexData = BABYLON.VertexData.CreateBox(options);
  15766. vertexData.applyToMesh(box, updatable);
  15767. return box;
  15768. };
  15769. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15770. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15771. if (diameterOrScene instanceof BABYLON.Scene) {
  15772. scene = diameterOrScene;
  15773. updatable = options.updatable;
  15774. }
  15775. else {
  15776. var segments = options;
  15777. options = {
  15778. segments: segments,
  15779. diameterX: diameterOrScene,
  15780. diameterY: diameterOrScene,
  15781. diameterZ: diameterOrScene,
  15782. sideOrientation: sideOrientation
  15783. };
  15784. }
  15785. var sphere = new Mesh(name, scene);
  15786. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15787. vertexData.applyToMesh(sphere, updatable);
  15788. return sphere;
  15789. };
  15790. Mesh.CreateCylinder = function (name, options, diameterTopOrScene, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15791. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15792. if (diameterTopOrScene instanceof BABYLON.Scene) {
  15793. scene = diameterTopOrScene;
  15794. updatable = options.updatable;
  15795. }
  15796. else {
  15797. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15798. if (scene !== undefined) {
  15799. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15800. updatable = scene;
  15801. }
  15802. scene = subdivisions;
  15803. subdivisions = 1;
  15804. }
  15805. var height = options;
  15806. options = {
  15807. height: height,
  15808. diameterTop: diameterTopOrScene,
  15809. diameterBottom: diameterBottom,
  15810. tessellation: tessellation,
  15811. subdivisions: subdivisions,
  15812. sideOrientation: sideOrientation
  15813. };
  15814. }
  15815. var cylinder = new Mesh(name, scene);
  15816. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15817. vertexData.applyToMesh(cylinder, updatable);
  15818. return cylinder;
  15819. };
  15820. Mesh.CreateTorus = function (name, options, thicknessOrScene, tessellation, scene, updatable, sideOrientation) {
  15821. if (thicknessOrScene instanceof BABYLON.Scene) {
  15822. scene = thicknessOrScene;
  15823. updatable = options.updatable;
  15824. }
  15825. else {
  15826. var diameter = options;
  15827. options = {
  15828. diameter: diameter,
  15829. thickness: thicknessOrScene,
  15830. tessellation: tessellation,
  15831. sideOrientation: sideOrientation
  15832. };
  15833. }
  15834. var torus = new Mesh(name, scene);
  15835. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15836. vertexData.applyToMesh(torus, updatable);
  15837. return torus;
  15838. };
  15839. Mesh.CreateTorusKnot = function (name, options, tubeOrScene, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15840. if (tubeOrScene instanceof BABYLON.Scene) {
  15841. scene = tubeOrScene;
  15842. updatable = options.updatable;
  15843. }
  15844. else {
  15845. var radius = options;
  15846. options = {
  15847. radius: radius,
  15848. tube: tubeOrScene,
  15849. radialSegments: radialSegments,
  15850. tubularSegments: tubularSegments,
  15851. p: p,
  15852. q: q,
  15853. sideOrientation: sideOrientation
  15854. };
  15855. }
  15856. var torusKnot = new Mesh(name, scene);
  15857. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15858. vertexData.applyToMesh(torusKnot, updatable);
  15859. return torusKnot;
  15860. };
  15861. Mesh.CreateLines = function (name, options, scene, updatable, instance) {
  15862. var points;
  15863. if (Array.isArray(options)) {
  15864. points = options;
  15865. if (!instance) {
  15866. options = {
  15867. points: points
  15868. };
  15869. }
  15870. }
  15871. else {
  15872. instance = options.instance;
  15873. points = options.points;
  15874. }
  15875. if (instance) {
  15876. var positionFunction = function (positions) {
  15877. var i = 0;
  15878. for (var p = 0; p < points.length; p++) {
  15879. positions[i] = points[p].x;
  15880. positions[i + 1] = points[p].y;
  15881. positions[i + 2] = points[p].z;
  15882. i += 3;
  15883. }
  15884. };
  15885. instance.updateMeshPositions(positionFunction, false);
  15886. return instance;
  15887. }
  15888. // lines creation
  15889. var lines = new BABYLON.LinesMesh(name, scene);
  15890. var vertexData = BABYLON.VertexData.CreateLines(options);
  15891. vertexData.applyToMesh(lines, updatable || options.updatable);
  15892. return lines;
  15893. };
  15894. Mesh.CreateDashedLines = function (name, options, dashSizeOrScene, gapSize, dashNb, scene, updatable, instance) {
  15895. var points;
  15896. var dashSize;
  15897. if (Array.isArray(options)) {
  15898. points = options;
  15899. dashSize = dashSizeOrScene;
  15900. if (!instance) {
  15901. options = {
  15902. points: points,
  15903. dashSize: dashSize,
  15904. gapSize: gapSize,
  15905. dashNb: dashNb
  15906. };
  15907. }
  15908. }
  15909. else {
  15910. scene = dashSizeOrScene,
  15911. points = options.points;
  15912. instance = options.instance;
  15913. gapSize = options.gapSize;
  15914. dashNb = options.dashNb;
  15915. dashSize = options.dashSize;
  15916. }
  15917. if (instance) {
  15918. var positionFunction = function (positions) {
  15919. var curvect = BABYLON.Vector3.Zero();
  15920. var nbSeg = positions.length / 6;
  15921. var lg = 0;
  15922. var nb = 0;
  15923. var shft = 0;
  15924. var dashshft = 0;
  15925. var curshft = 0;
  15926. var p = 0;
  15927. var i = 0;
  15928. var j = 0;
  15929. for (i = 0; i < points.length - 1; i++) {
  15930. points[i + 1].subtractToRef(points[i], curvect);
  15931. lg += curvect.length();
  15932. }
  15933. shft = lg / nbSeg;
  15934. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15935. for (i = 0; i < points.length - 1; i++) {
  15936. points[i + 1].subtractToRef(points[i], curvect);
  15937. nb = Math.floor(curvect.length() / shft);
  15938. curvect.normalize();
  15939. j = 0;
  15940. while (j < nb && p < positions.length) {
  15941. curshft = shft * j;
  15942. positions[p] = points[i].x + curshft * curvect.x;
  15943. positions[p + 1] = points[i].y + curshft * curvect.y;
  15944. positions[p + 2] = points[i].z + curshft * curvect.z;
  15945. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15946. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15947. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15948. p += 6;
  15949. j++;
  15950. }
  15951. }
  15952. while (p < positions.length) {
  15953. positions[p] = points[i].x;
  15954. positions[p + 1] = points[i].y;
  15955. positions[p + 2] = points[i].z;
  15956. p += 3;
  15957. }
  15958. };
  15959. instance.updateMeshPositions(positionFunction, false);
  15960. return instance;
  15961. }
  15962. // dashed lines creation
  15963. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15964. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15965. vertexData.applyToMesh(dashedLines, updatable || options.updatable);
  15966. dashedLines.dashSize = dashSize;
  15967. dashedLines.gapSize = gapSize;
  15968. return dashedLines;
  15969. };
  15970. Mesh.ExtrudeShape = function (name, options, pathOrScene, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15971. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15972. if (instance === void 0) { instance = null; }
  15973. var path;
  15974. var shape;
  15975. if (Array.isArray(options)) {
  15976. shape = options;
  15977. path = pathOrScene;
  15978. scale = scale || 1;
  15979. rotation = rotation || 0;
  15980. cap = (cap === 0) ? 0 : cap || Mesh.NO_CAP;
  15981. }
  15982. else {
  15983. scene = pathOrScene;
  15984. path = options.path;
  15985. shape = options.shape;
  15986. scale = options.scale || 1;
  15987. rotation = options.rotation || 0;
  15988. cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  15989. updatable = options.updatable;
  15990. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  15991. instance = options.instance;
  15992. }
  15993. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15994. return extruded;
  15995. };
  15996. Mesh.ExtrudeShapeCustom = function (name, options, pathOrScene, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15997. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15998. if (instance === void 0) { instance = null; }
  15999. var path;
  16000. var shape;
  16001. if (Array.isArray(options)) {
  16002. shape = options;
  16003. path = pathOrScene;
  16004. ribbonCloseArray = ribbonCloseArray || false;
  16005. ribbonClosePath = ribbonClosePath || false;
  16006. cap = (cap === 0) ? 0 : cap || Mesh.NO_CAP;
  16007. }
  16008. else {
  16009. scene = pathOrScene;
  16010. path = options.path;
  16011. shape = options.shape;
  16012. scaleFunction = options.scaleFunction || (function (i, distance) { return 1; });
  16013. rotationFunction = options.rotationFunction || (function (i, distance) { return 0; });
  16014. ribbonCloseArray = options.ribbonCloseArray || false;
  16015. ribbonClosePath = options.ribbonClosePath || false;
  16016. cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  16017. updatable = options.updatable;
  16018. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  16019. instance = options.instance;
  16020. }
  16021. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16022. return extrudedCustom;
  16023. };
  16024. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16025. // extrusion geometry
  16026. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16027. var tangents = path3D.getTangents();
  16028. var normals = path3D.getNormals();
  16029. var binormals = path3D.getBinormals();
  16030. var distances = path3D.getDistances();
  16031. var angle = 0;
  16032. var returnScale = function (i, distance) { return scale; };
  16033. var returnRotation = function (i, distance) { return rotation; };
  16034. var rotate = custom ? rotateFunction : returnRotation;
  16035. var scl = custom ? scaleFunction : returnScale;
  16036. var index = (cap === Mesh.NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  16037. var rotationMatrix = BABYLON.Matrix.Zero();
  16038. for (var i = 0; i < curve.length; i++) {
  16039. var shapePath = new Array();
  16040. var angleStep = rotate(i, distances[i]);
  16041. var scaleRatio = scl(i, distances[i]);
  16042. for (var p = 0; p < shape.length; p++) {
  16043. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16044. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16045. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16046. shapePath.push(rotated);
  16047. }
  16048. shapePaths[index] = shapePath;
  16049. angle += angleStep;
  16050. index++;
  16051. }
  16052. // cap
  16053. var capPath = function (shapePath) {
  16054. var pointCap = Array();
  16055. var barycenter = BABYLON.Vector3.Zero();
  16056. var i;
  16057. for (i = 0; i < shapePath.length; i++) {
  16058. barycenter.addInPlace(shapePath[i]);
  16059. }
  16060. barycenter.scaleInPlace(1 / shapePath.length);
  16061. for (i = 0; i < shapePath.length; i++) {
  16062. pointCap.push(barycenter);
  16063. }
  16064. return pointCap;
  16065. };
  16066. switch (cap) {
  16067. case Mesh.NO_CAP:
  16068. break;
  16069. case Mesh.CAP_START:
  16070. shapePaths[0] = capPath(shapePaths[2]);
  16071. shapePaths[1] = shapePaths[2].slice(0);
  16072. break;
  16073. case Mesh.CAP_END:
  16074. shapePaths[index] = shapePaths[index - 1];
  16075. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16076. break;
  16077. case Mesh.CAP_ALL:
  16078. shapePaths[0] = capPath(shapePaths[2]);
  16079. shapePaths[1] = shapePaths[2].slice(0);
  16080. shapePaths[index] = shapePaths[index - 1];
  16081. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16082. break;
  16083. default:
  16084. break;
  16085. }
  16086. return shapePaths;
  16087. };
  16088. var path3D;
  16089. var pathArray;
  16090. if (instance) {
  16091. path3D = (instance.path3D).update(curve);
  16092. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16093. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16094. return instance;
  16095. }
  16096. // extruded shape creation
  16097. path3D = new BABYLON.Path3D(curve);
  16098. var newShapePaths = new Array();
  16099. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16100. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16101. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16102. extrudedGeneric.pathArray = pathArray;
  16103. extrudedGeneric.path3D = path3D;
  16104. extrudedGeneric.cap = cap;
  16105. return extrudedGeneric;
  16106. };
  16107. Mesh.CreateLathe = function (name, options, radiusOrScene, tessellation, scene, updatable, sideOrientation) {
  16108. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16109. var shape;
  16110. var radius;
  16111. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  16112. var closed = (options.closed === undefined) ? true : options.closed;
  16113. if (Array.isArray(options)) {
  16114. shape = options;
  16115. radius = radiusOrScene || 1;
  16116. tessellation = tessellation || 64;
  16117. }
  16118. else {
  16119. scene = radiusOrScene;
  16120. shape = options.shape;
  16121. radius = options.radius || 1;
  16122. tessellation = options.tessellation || 64;
  16123. updatable = options.updatable;
  16124. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  16125. }
  16126. var pi2 = Math.PI * 2;
  16127. var shapeLathe = new Array();
  16128. // first rotatable point
  16129. var i = 0;
  16130. while (shape[i].x === 0) {
  16131. i++;
  16132. }
  16133. var pt = shape[i];
  16134. for (i = 0; i < shape.length; i++) {
  16135. shapeLathe.push(shape[i].subtract(pt));
  16136. }
  16137. // circle path
  16138. var step = pi2 / tessellation * arc;
  16139. var rotated;
  16140. var path = new Array();
  16141. ;
  16142. for (i = 0; i <= tessellation; i++) {
  16143. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16144. path.push(rotated);
  16145. }
  16146. if (closed) {
  16147. path.push(path[0]);
  16148. }
  16149. // extrusion
  16150. var scaleFunction = function () { return 1; };
  16151. var rotateFunction = function () { return 0; };
  16152. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  16153. return lathe;
  16154. };
  16155. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  16156. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16157. if (typeof options === 'number') {
  16158. var size = options;
  16159. options = {
  16160. size: size,
  16161. width: size,
  16162. height: size,
  16163. sideOrientation: sideOrientation
  16164. };
  16165. }
  16166. var plane = new Mesh(name, scene);
  16167. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16168. vertexData.applyToMesh(plane, updatable || options.updatable);
  16169. return plane;
  16170. };
  16171. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  16172. if (heightOrScene instanceof BABYLON.Scene) {
  16173. scene = heightOrScene;
  16174. updatable = options.updatable;
  16175. }
  16176. else {
  16177. var width = options;
  16178. options = {
  16179. width: width,
  16180. height: heightOrScene,
  16181. subdivisions: subdivisions
  16182. };
  16183. }
  16184. var ground = new BABYLON.GroundMesh(name, scene);
  16185. ground._setReady(false);
  16186. ground._subdivisions = options.subdivisions || 1;
  16187. var vertexData = BABYLON.VertexData.CreateGround(options);
  16188. vertexData.applyToMesh(ground, updatable || options.updatable);
  16189. ground._setReady(true);
  16190. return ground;
  16191. };
  16192. Mesh.CreateTiledGround = function (name, options, zminOrScene, xmax, zmax, subdivisions, precision, scene, updatable) {
  16193. var xmin;
  16194. var zmin;
  16195. if (typeof options === 'number') {
  16196. xmin = options || -1;
  16197. zmin = zminOrScene || -1;
  16198. xmax = xmax || 1;
  16199. zmax = zmax || 1;
  16200. subdivisions = subdivisions || { w: 6, h: 6 };
  16201. precision = precision || { w: 2, h: 2 };
  16202. }
  16203. else {
  16204. scene = zminOrScene;
  16205. xmin = options.xmin || -1;
  16206. zmin = options.zmin || -1;
  16207. xmax = options.xmax || 1;
  16208. zmax = options.zmax || 1;
  16209. subdivisions = options.subdivisions || { w: 6, h: 6 };
  16210. precision = options.precision || { w: 2, h: 2 };
  16211. }
  16212. var tiledGround = new Mesh(name, scene);
  16213. var vertexData = BABYLON.VertexData.CreateTiledGround({ xmin: xmin, zmin: zmin, xmax: xmax, zmax: zmax, subdivisions: subdivisions, precision: precision });
  16214. vertexData.applyToMesh(tiledGround, updatable);
  16215. return tiledGround;
  16216. };
  16217. Mesh.CreateGroundFromHeightMap = function (name, url, widthOrOptions, heightorScene, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16218. var width;
  16219. var height;
  16220. if (typeof widthOrOptions === "number") {
  16221. width = widthOrOptions;
  16222. height = heightorScene;
  16223. }
  16224. else {
  16225. width = widthOrOptions.width || 10;
  16226. height = widthOrOptions.height || 10;
  16227. subdivisions = widthOrOptions.subdivisions || 1;
  16228. minHeight = widthOrOptions.minHeight;
  16229. maxHeight = widthOrOptions.maxHeight || 10;
  16230. updatable = widthOrOptions.updatable;
  16231. onReady = widthOrOptions.onReady;
  16232. scene = heightorScene;
  16233. }
  16234. var ground = new BABYLON.GroundMesh(name, scene);
  16235. ground._subdivisions = subdivisions;
  16236. ground._setReady(false);
  16237. var onload = function (img) {
  16238. // Getting height map data
  16239. var canvas = document.createElement("canvas");
  16240. var context = canvas.getContext("2d");
  16241. var bufferWidth = img.width;
  16242. var bufferHeight = img.height;
  16243. canvas.width = bufferWidth;
  16244. canvas.height = bufferHeight;
  16245. context.drawImage(img, 0, 0);
  16246. // Create VertexData from map data
  16247. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16248. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16249. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16250. width: width, height: height,
  16251. subdivisions: subdivisions,
  16252. minHeight: minHeight, maxHeight: maxHeight,
  16253. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16254. });
  16255. vertexData.applyToMesh(ground, updatable);
  16256. ground._setReady(true);
  16257. //execute ready callback, if set
  16258. if (onReady) {
  16259. onReady(ground);
  16260. }
  16261. };
  16262. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16263. return ground;
  16264. };
  16265. Mesh.CreateTube = function (name, options, radiusOrScene, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16266. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16267. if (instance === void 0) { instance = null; }
  16268. var path;
  16269. var radius;
  16270. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  16271. ;
  16272. if (Array.isArray(options)) {
  16273. path = options;
  16274. radius = radiusOrScene;
  16275. }
  16276. else {
  16277. scene = radiusOrScene;
  16278. path = options.path;
  16279. radius = options.radius || 1;
  16280. tessellation = options.tessellation || 64;
  16281. radiusFunction = options.radiusFunction;
  16282. cap = options.cap || Mesh.NO_CAP,
  16283. updatable = options.updatable;
  16284. sideOrientation = options.sideOrientation || Mesh.DEFAULTSIDE,
  16285. instance = options.instance;
  16286. }
  16287. // tube geometry
  16288. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16289. var tangents = path3D.getTangents();
  16290. var normals = path3D.getNormals();
  16291. var distances = path3D.getDistances();
  16292. var pi2 = Math.PI * 2;
  16293. var step = pi2 / tessellation * arc;
  16294. var returnRadius = function (i, distance) { return radius; };
  16295. var radiusFunctionFinal = radiusFunction || returnRadius;
  16296. var circlePath;
  16297. var rad;
  16298. var normal;
  16299. var rotated;
  16300. var rotationMatrix = BABYLON.Matrix.Zero();
  16301. var index = (cap === Mesh._NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  16302. for (var i = 0; i < path.length; i++) {
  16303. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16304. circlePath = Array(); // current circle array
  16305. normal = normals[i]; // current normal
  16306. for (var t = 0; t < tessellation; t++) {
  16307. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16308. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16309. circlePath.push(rotated);
  16310. }
  16311. circlePaths[index] = circlePath;
  16312. index++;
  16313. }
  16314. // cap
  16315. var capPath = function (nbPoints, pathIndex) {
  16316. var pointCap = Array();
  16317. for (var i = 0; i < nbPoints; i++) {
  16318. pointCap.push(path[pathIndex]);
  16319. }
  16320. return pointCap;
  16321. };
  16322. switch (cap) {
  16323. case Mesh.NO_CAP:
  16324. break;
  16325. case Mesh.CAP_START:
  16326. circlePaths[0] = capPath(tessellation, 0);
  16327. circlePaths[1] = circlePaths[2].slice(0);
  16328. break;
  16329. case Mesh.CAP_END:
  16330. circlePaths[index] = circlePaths[index - 1].slice(0);
  16331. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16332. break;
  16333. case Mesh.CAP_ALL:
  16334. circlePaths[0] = capPath(tessellation, 0);
  16335. circlePaths[1] = circlePaths[2].slice(0);
  16336. circlePaths[index] = circlePaths[index - 1].slice(0);
  16337. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16338. break;
  16339. default:
  16340. break;
  16341. }
  16342. return circlePaths;
  16343. };
  16344. var path3D;
  16345. var pathArray;
  16346. if (instance) {
  16347. arc = arc || instance.arc;
  16348. path3D = (instance.path3D).update(path);
  16349. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16350. instance = Mesh.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16351. instance.path3D = path3D;
  16352. instance.pathArray = pathArray;
  16353. instance.arc = arc;
  16354. return instance;
  16355. }
  16356. // tube creation
  16357. path3D = new BABYLON.Path3D(path);
  16358. var newPathArray = new Array();
  16359. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16360. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, arc);
  16361. var tube = Mesh.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16362. tube.pathArray = pathArray;
  16363. tube.path3D = path3D;
  16364. tube.tessellation = tessellation;
  16365. tube.cap = cap;
  16366. tube.arc = arc;
  16367. return tube;
  16368. };
  16369. Mesh.CreateDecal = function (name, sourceMesh, positionOrOptions, normal, size, angle) {
  16370. if (angle === void 0) { angle = 0; }
  16371. var indices = sourceMesh.getIndices();
  16372. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16373. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16374. var position;
  16375. if (positionOrOptions instanceof BABYLON.Vector3) {
  16376. position = positionOrOptions;
  16377. }
  16378. else {
  16379. position = positionOrOptions.position || BABYLON.Vector3.Zero();
  16380. normal = positionOrOptions.normal || BABYLON.Vector3.Up();
  16381. size = positionOrOptions.size || new BABYLON.Vector3(1, 1, 1);
  16382. angle = positionOrOptions.angle;
  16383. }
  16384. // Getting correct rotation
  16385. if (!normal) {
  16386. var target = new BABYLON.Vector3(0, 0, 1);
  16387. var camera = sourceMesh.getScene().activeCamera;
  16388. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16389. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16390. }
  16391. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16392. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16393. var pitch = Math.atan2(normal.y, len);
  16394. // Matrix
  16395. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16396. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16397. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16398. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16399. var vertexData = new BABYLON.VertexData();
  16400. vertexData.indices = [];
  16401. vertexData.positions = [];
  16402. vertexData.normals = [];
  16403. vertexData.uvs = [];
  16404. var currentVertexDataIndex = 0;
  16405. var extractDecalVector3 = function (indexId) {
  16406. var vertexId = indices[indexId];
  16407. var result = new BABYLON.PositionNormalVertex();
  16408. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16409. // Send vector to decal local world
  16410. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16411. // Get normal
  16412. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16413. return result;
  16414. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16415. var clip = function (vertices, axis) {
  16416. if (vertices.length === 0) {
  16417. return vertices;
  16418. }
  16419. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16420. var clipVertices = function (v0, v1) {
  16421. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16422. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16423. };
  16424. var result = new Array();
  16425. for (var index = 0; index < vertices.length; index += 3) {
  16426. var v1Out;
  16427. var v2Out;
  16428. var v3Out;
  16429. var total = 0;
  16430. var nV1, nV2, nV3, nV4;
  16431. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16432. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16433. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16434. v1Out = d1 > 0;
  16435. v2Out = d2 > 0;
  16436. v3Out = d3 > 0;
  16437. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16438. switch (total) {
  16439. case 0:
  16440. result.push(vertices[index]);
  16441. result.push(vertices[index + 1]);
  16442. result.push(vertices[index + 2]);
  16443. break;
  16444. case 1:
  16445. if (v1Out) {
  16446. nV1 = vertices[index + 1];
  16447. nV2 = vertices[index + 2];
  16448. nV3 = clipVertices(vertices[index], nV1);
  16449. nV4 = clipVertices(vertices[index], nV2);
  16450. }
  16451. if (v2Out) {
  16452. nV1 = vertices[index];
  16453. nV2 = vertices[index + 2];
  16454. nV3 = clipVertices(vertices[index + 1], nV1);
  16455. nV4 = clipVertices(vertices[index + 1], nV2);
  16456. result.push(nV3);
  16457. result.push(nV2.clone());
  16458. result.push(nV1.clone());
  16459. result.push(nV2.clone());
  16460. result.push(nV3.clone());
  16461. result.push(nV4);
  16462. break;
  16463. }
  16464. if (v3Out) {
  16465. nV1 = vertices[index];
  16466. nV2 = vertices[index + 1];
  16467. nV3 = clipVertices(vertices[index + 2], nV1);
  16468. nV4 = clipVertices(vertices[index + 2], nV2);
  16469. }
  16470. result.push(nV1.clone());
  16471. result.push(nV2.clone());
  16472. result.push(nV3);
  16473. result.push(nV4);
  16474. result.push(nV3.clone());
  16475. result.push(nV2.clone());
  16476. break;
  16477. case 2:
  16478. if (!v1Out) {
  16479. nV1 = vertices[index].clone();
  16480. nV2 = clipVertices(nV1, vertices[index + 1]);
  16481. nV3 = clipVertices(nV1, vertices[index + 2]);
  16482. result.push(nV1);
  16483. result.push(nV2);
  16484. result.push(nV3);
  16485. }
  16486. if (!v2Out) {
  16487. nV1 = vertices[index + 1].clone();
  16488. nV2 = clipVertices(nV1, vertices[index + 2]);
  16489. nV3 = clipVertices(nV1, vertices[index]);
  16490. result.push(nV1);
  16491. result.push(nV2);
  16492. result.push(nV3);
  16493. }
  16494. if (!v3Out) {
  16495. nV1 = vertices[index + 2].clone();
  16496. nV2 = clipVertices(nV1, vertices[index]);
  16497. nV3 = clipVertices(nV1, vertices[index + 1]);
  16498. result.push(nV1);
  16499. result.push(nV2);
  16500. result.push(nV3);
  16501. }
  16502. break;
  16503. case 3:
  16504. break;
  16505. }
  16506. }
  16507. return result;
  16508. };
  16509. for (var index = 0; index < indices.length; index += 3) {
  16510. var faceVertices = new Array();
  16511. faceVertices.push(extractDecalVector3(index));
  16512. faceVertices.push(extractDecalVector3(index + 1));
  16513. faceVertices.push(extractDecalVector3(index + 2));
  16514. // Clip
  16515. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16516. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16517. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16518. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16519. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16520. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16521. if (faceVertices.length === 0) {
  16522. continue;
  16523. }
  16524. // Add UVs and get back to world
  16525. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16526. var vertex = faceVertices[vIndex];
  16527. vertexData.indices.push(currentVertexDataIndex);
  16528. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16529. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16530. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16531. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16532. currentVertexDataIndex++;
  16533. }
  16534. }
  16535. // Return mesh
  16536. var decal = new Mesh(name, sourceMesh.getScene());
  16537. vertexData.applyToMesh(decal);
  16538. decal.position = position.clone();
  16539. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16540. return decal;
  16541. };
  16542. // Skeletons
  16543. /**
  16544. * Update the vertex buffers by applying transformation from the bones
  16545. * @param {skeleton} skeleton to apply
  16546. */
  16547. Mesh.prototype.applySkeleton = function (skeleton) {
  16548. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16549. return this;
  16550. }
  16551. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16552. return this;
  16553. }
  16554. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16555. return this;
  16556. }
  16557. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16558. return this;
  16559. }
  16560. var source;
  16561. if (!this._sourcePositions) {
  16562. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16563. this._sourcePositions = new Float32Array(source);
  16564. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16565. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16566. }
  16567. }
  16568. if (!this._sourceNormals) {
  16569. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16570. this._sourceNormals = new Float32Array(source);
  16571. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16572. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16573. }
  16574. }
  16575. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16576. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16577. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16578. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16579. var skeletonMatrices = skeleton.getTransformMatrices();
  16580. var tempVector3 = BABYLON.Vector3.Zero();
  16581. var finalMatrix = new BABYLON.Matrix();
  16582. var tempMatrix = new BABYLON.Matrix();
  16583. for (var index = 0; index < positionsData.length; index += 3) {
  16584. var index4 = (index / 3) * 4;
  16585. var matricesWeight0 = matricesWeightsData[index4];
  16586. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16587. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16588. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16589. if (matricesWeight0 > 0) {
  16590. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16591. finalMatrix.addToSelf(tempMatrix);
  16592. }
  16593. if (matricesWeight1 > 0) {
  16594. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16595. finalMatrix.addToSelf(tempMatrix);
  16596. }
  16597. if (matricesWeight2 > 0) {
  16598. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16599. finalMatrix.addToSelf(tempMatrix);
  16600. }
  16601. if (matricesWeight3 > 0) {
  16602. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16603. finalMatrix.addToSelf(tempMatrix);
  16604. }
  16605. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16606. tempVector3.toArray(positionsData, index);
  16607. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16608. tempVector3.toArray(normalsData, index);
  16609. finalMatrix.reset();
  16610. }
  16611. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16612. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16613. return this;
  16614. };
  16615. // Tools
  16616. Mesh.MinMax = function (meshes) {
  16617. var minVector = null;
  16618. var maxVector = null;
  16619. for (var i in meshes) {
  16620. var mesh = meshes[i];
  16621. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16622. if (!minVector) {
  16623. minVector = boundingBox.minimumWorld;
  16624. maxVector = boundingBox.maximumWorld;
  16625. continue;
  16626. }
  16627. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16628. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16629. }
  16630. return {
  16631. min: minVector,
  16632. max: maxVector
  16633. };
  16634. };
  16635. Mesh.Center = function (meshesOrMinMaxVector) {
  16636. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16637. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16638. };
  16639. /**
  16640. * Merge the array of meshes into a single mesh for performance reasons.
  16641. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16642. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16643. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16644. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16645. */
  16646. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16647. if (disposeSource === void 0) { disposeSource = true; }
  16648. var index;
  16649. if (!allow32BitsIndices) {
  16650. var totalVertices = 0;
  16651. // Counting vertices
  16652. for (index = 0; index < meshes.length; index++) {
  16653. if (meshes[index]) {
  16654. totalVertices += meshes[index].getTotalVertices();
  16655. if (totalVertices > 65536) {
  16656. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16657. return null;
  16658. }
  16659. }
  16660. }
  16661. }
  16662. // Merge
  16663. var vertexData;
  16664. var otherVertexData;
  16665. var source;
  16666. for (index = 0; index < meshes.length; index++) {
  16667. if (meshes[index]) {
  16668. meshes[index].computeWorldMatrix(true);
  16669. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16670. otherVertexData.transform(meshes[index].getWorldMatrix());
  16671. if (vertexData) {
  16672. vertexData.merge(otherVertexData);
  16673. }
  16674. else {
  16675. vertexData = otherVertexData;
  16676. source = meshes[index];
  16677. }
  16678. }
  16679. }
  16680. if (!meshSubclass) {
  16681. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16682. }
  16683. vertexData.applyToMesh(meshSubclass);
  16684. // Setting properties
  16685. meshSubclass.material = source.material;
  16686. meshSubclass.checkCollisions = source.checkCollisions;
  16687. // Cleaning
  16688. if (disposeSource) {
  16689. for (index = 0; index < meshes.length; index++) {
  16690. if (meshes[index]) {
  16691. meshes[index].dispose();
  16692. }
  16693. }
  16694. }
  16695. return meshSubclass;
  16696. };
  16697. // Consts
  16698. Mesh._FRONTSIDE = 0;
  16699. Mesh._BACKSIDE = 1;
  16700. Mesh._DOUBLESIDE = 2;
  16701. Mesh._DEFAULTSIDE = 0;
  16702. Mesh._NO_CAP = 0;
  16703. Mesh._CAP_START = 1;
  16704. Mesh._CAP_END = 2;
  16705. Mesh._CAP_ALL = 3;
  16706. return Mesh;
  16707. })(BABYLON.AbstractMesh);
  16708. BABYLON.Mesh = Mesh;
  16709. })(BABYLON || (BABYLON = {}));
  16710. var BABYLON;
  16711. (function (BABYLON) {
  16712. var SubMesh = (function () {
  16713. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16714. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16715. this.materialIndex = materialIndex;
  16716. this.verticesStart = verticesStart;
  16717. this.verticesCount = verticesCount;
  16718. this.indexStart = indexStart;
  16719. this.indexCount = indexCount;
  16720. this._renderId = 0;
  16721. this._mesh = mesh;
  16722. this._renderingMesh = renderingMesh || mesh;
  16723. mesh.subMeshes.push(this);
  16724. this._trianglePlanes = [];
  16725. this._id = mesh.subMeshes.length - 1;
  16726. if (createBoundingBox) {
  16727. this.refreshBoundingInfo();
  16728. mesh.computeWorldMatrix(true);
  16729. }
  16730. }
  16731. SubMesh.prototype.getBoundingInfo = function () {
  16732. return this._boundingInfo;
  16733. };
  16734. SubMesh.prototype.getMesh = function () {
  16735. return this._mesh;
  16736. };
  16737. SubMesh.prototype.getRenderingMesh = function () {
  16738. return this._renderingMesh;
  16739. };
  16740. SubMesh.prototype.getMaterial = function () {
  16741. var rootMaterial = this._renderingMesh.material;
  16742. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16743. var multiMaterial = rootMaterial;
  16744. return multiMaterial.getSubMaterial(this.materialIndex);
  16745. }
  16746. if (!rootMaterial) {
  16747. return this._mesh.getScene().defaultMaterial;
  16748. }
  16749. return rootMaterial;
  16750. };
  16751. // Methods
  16752. SubMesh.prototype.refreshBoundingInfo = function () {
  16753. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16754. if (!data) {
  16755. this._boundingInfo = this._mesh._boundingInfo;
  16756. return;
  16757. }
  16758. var indices = this._renderingMesh.getIndices();
  16759. var extend;
  16760. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16761. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16762. }
  16763. else {
  16764. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16765. }
  16766. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16767. };
  16768. SubMesh.prototype._checkCollision = function (collider) {
  16769. return this._boundingInfo._checkCollision(collider);
  16770. };
  16771. SubMesh.prototype.updateBoundingInfo = function (world) {
  16772. if (!this._boundingInfo) {
  16773. this.refreshBoundingInfo();
  16774. }
  16775. this._boundingInfo._update(world);
  16776. };
  16777. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16778. return this._boundingInfo.isInFrustum(frustumPlanes);
  16779. };
  16780. SubMesh.prototype.render = function (enableAlphaMode) {
  16781. this._renderingMesh.render(this, enableAlphaMode);
  16782. };
  16783. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16784. if (!this._linesIndexBuffer) {
  16785. var linesIndices = [];
  16786. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16787. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16788. }
  16789. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16790. this.linesIndexCount = linesIndices.length;
  16791. }
  16792. return this._linesIndexBuffer;
  16793. };
  16794. SubMesh.prototype.canIntersects = function (ray) {
  16795. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16796. };
  16797. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16798. var intersectInfo = null;
  16799. // Triangles test
  16800. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16801. var p0 = positions[indices[index]];
  16802. var p1 = positions[indices[index + 1]];
  16803. var p2 = positions[indices[index + 2]];
  16804. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16805. if (currentIntersectInfo) {
  16806. if (currentIntersectInfo.distance < 0) {
  16807. continue;
  16808. }
  16809. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16810. intersectInfo = currentIntersectInfo;
  16811. intersectInfo.faceId = index / 3;
  16812. if (fastCheck) {
  16813. break;
  16814. }
  16815. }
  16816. }
  16817. }
  16818. return intersectInfo;
  16819. };
  16820. // Clone
  16821. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16822. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16823. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16824. return result;
  16825. };
  16826. // Dispose
  16827. SubMesh.prototype.dispose = function () {
  16828. if (this._linesIndexBuffer) {
  16829. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16830. this._linesIndexBuffer = null;
  16831. }
  16832. // Remove from mesh
  16833. var index = this._mesh.subMeshes.indexOf(this);
  16834. this._mesh.subMeshes.splice(index, 1);
  16835. };
  16836. // Statics
  16837. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16838. var minVertexIndex = Number.MAX_VALUE;
  16839. var maxVertexIndex = -Number.MAX_VALUE;
  16840. renderingMesh = renderingMesh || mesh;
  16841. var indices = renderingMesh.getIndices();
  16842. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16843. var vertexIndex = indices[index];
  16844. if (vertexIndex < minVertexIndex)
  16845. minVertexIndex = vertexIndex;
  16846. if (vertexIndex > maxVertexIndex)
  16847. maxVertexIndex = vertexIndex;
  16848. }
  16849. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16850. };
  16851. return SubMesh;
  16852. })();
  16853. BABYLON.SubMesh = SubMesh;
  16854. })(BABYLON || (BABYLON = {}));
  16855. var BABYLON;
  16856. (function (BABYLON) {
  16857. var BaseTexture = (function () {
  16858. function BaseTexture(scene) {
  16859. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16860. this.hasAlpha = false;
  16861. this.getAlphaFromRGB = false;
  16862. this.level = 1;
  16863. this.isCube = false;
  16864. this.isRenderTarget = false;
  16865. this.animations = new Array();
  16866. this.coordinatesIndex = 0;
  16867. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16868. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16869. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16870. this.anisotropicFilteringLevel = 4;
  16871. this._scene = scene;
  16872. this._scene.textures.push(this);
  16873. }
  16874. BaseTexture.prototype.getScene = function () {
  16875. return this._scene;
  16876. };
  16877. BaseTexture.prototype.getTextureMatrix = function () {
  16878. return null;
  16879. };
  16880. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16881. return null;
  16882. };
  16883. BaseTexture.prototype.getInternalTexture = function () {
  16884. return this._texture;
  16885. };
  16886. BaseTexture.prototype.isReady = function () {
  16887. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16888. return true;
  16889. }
  16890. if (this._texture) {
  16891. return this._texture.isReady;
  16892. }
  16893. return false;
  16894. };
  16895. BaseTexture.prototype.getSize = function () {
  16896. if (this._texture._width) {
  16897. return { width: this._texture._width, height: this._texture._height };
  16898. }
  16899. if (this._texture._size) {
  16900. return { width: this._texture._size, height: this._texture._size };
  16901. }
  16902. return { width: 0, height: 0 };
  16903. };
  16904. BaseTexture.prototype.getBaseSize = function () {
  16905. if (!this.isReady())
  16906. return { width: 0, height: 0 };
  16907. if (this._texture._size) {
  16908. return { width: this._texture._size, height: this._texture._size };
  16909. }
  16910. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16911. };
  16912. BaseTexture.prototype.scale = function (ratio) {
  16913. };
  16914. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16915. get: function () {
  16916. return false;
  16917. },
  16918. enumerable: true,
  16919. configurable: true
  16920. });
  16921. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16922. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16923. for (var index = 0; index < texturesCache.length; index++) {
  16924. var texturesCacheEntry = texturesCache[index];
  16925. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16926. texturesCache.splice(index, 1);
  16927. return;
  16928. }
  16929. }
  16930. };
  16931. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16932. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16933. for (var index = 0; index < texturesCache.length; index++) {
  16934. var texturesCacheEntry = texturesCache[index];
  16935. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16936. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16937. texturesCacheEntry.references++;
  16938. return texturesCacheEntry;
  16939. }
  16940. }
  16941. }
  16942. return null;
  16943. };
  16944. BaseTexture.prototype.delayLoad = function () {
  16945. };
  16946. BaseTexture.prototype.clone = function () {
  16947. return null;
  16948. };
  16949. BaseTexture.prototype.releaseInternalTexture = function () {
  16950. if (this._texture) {
  16951. this._scene.getEngine().releaseInternalTexture(this._texture);
  16952. delete this._texture;
  16953. }
  16954. };
  16955. BaseTexture.prototype.dispose = function () {
  16956. // Remove from scene
  16957. var index = this._scene.textures.indexOf(this);
  16958. if (index >= 0) {
  16959. this._scene.textures.splice(index, 1);
  16960. }
  16961. if (this._texture === undefined) {
  16962. return;
  16963. }
  16964. // Callback
  16965. if (this.onDispose) {
  16966. this.onDispose();
  16967. }
  16968. };
  16969. return BaseTexture;
  16970. })();
  16971. BABYLON.BaseTexture = BaseTexture;
  16972. })(BABYLON || (BABYLON = {}));
  16973. var BABYLON;
  16974. (function (BABYLON) {
  16975. var Texture = (function (_super) {
  16976. __extends(Texture, _super);
  16977. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16978. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16979. if (onLoad === void 0) { onLoad = null; }
  16980. if (onError === void 0) { onError = null; }
  16981. if (buffer === void 0) { buffer = null; }
  16982. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16983. _super.call(this, scene);
  16984. this.uOffset = 0;
  16985. this.vOffset = 0;
  16986. this.uScale = 1.0;
  16987. this.vScale = 1.0;
  16988. this.uAng = 0;
  16989. this.vAng = 0;
  16990. this.wAng = 0;
  16991. this.name = url;
  16992. this.url = url;
  16993. this._noMipmap = noMipmap;
  16994. this._invertY = invertY;
  16995. this._samplingMode = samplingMode;
  16996. this._buffer = buffer;
  16997. this._deleteBuffer = deleteBuffer;
  16998. if (!url) {
  16999. return;
  17000. }
  17001. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17002. if (!this._texture) {
  17003. if (!scene.useDelayedTextureLoading) {
  17004. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17005. if (deleteBuffer) {
  17006. delete this._buffer;
  17007. }
  17008. }
  17009. else {
  17010. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17011. }
  17012. }
  17013. else {
  17014. BABYLON.Tools.SetImmediate(function () {
  17015. if (onLoad) {
  17016. onLoad();
  17017. }
  17018. });
  17019. }
  17020. }
  17021. Texture.prototype.delayLoad = function () {
  17022. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17023. return;
  17024. }
  17025. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17026. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17027. if (!this._texture) {
  17028. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17029. if (this._deleteBuffer) {
  17030. delete this._buffer;
  17031. }
  17032. }
  17033. };
  17034. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17035. if (!this._texture) {
  17036. return;
  17037. }
  17038. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17039. };
  17040. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17041. x *= this.uScale;
  17042. y *= this.vScale;
  17043. x -= 0.5 * this.uScale;
  17044. y -= 0.5 * this.vScale;
  17045. z -= 0.5;
  17046. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17047. t.x += 0.5 * this.uScale + this.uOffset;
  17048. t.y += 0.5 * this.vScale + this.vOffset;
  17049. t.z += 0.5;
  17050. };
  17051. Texture.prototype.getTextureMatrix = function () {
  17052. if (this.uOffset === this._cachedUOffset &&
  17053. this.vOffset === this._cachedVOffset &&
  17054. this.uScale === this._cachedUScale &&
  17055. this.vScale === this._cachedVScale &&
  17056. this.uAng === this._cachedUAng &&
  17057. this.vAng === this._cachedVAng &&
  17058. this.wAng === this._cachedWAng) {
  17059. return this._cachedTextureMatrix;
  17060. }
  17061. this._cachedUOffset = this.uOffset;
  17062. this._cachedVOffset = this.vOffset;
  17063. this._cachedUScale = this.uScale;
  17064. this._cachedVScale = this.vScale;
  17065. this._cachedUAng = this.uAng;
  17066. this._cachedVAng = this.vAng;
  17067. this._cachedWAng = this.wAng;
  17068. if (!this._cachedTextureMatrix) {
  17069. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17070. this._rowGenerationMatrix = new BABYLON.Matrix();
  17071. this._t0 = BABYLON.Vector3.Zero();
  17072. this._t1 = BABYLON.Vector3.Zero();
  17073. this._t2 = BABYLON.Vector3.Zero();
  17074. }
  17075. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17076. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17077. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17078. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17079. this._t1.subtractInPlace(this._t0);
  17080. this._t2.subtractInPlace(this._t0);
  17081. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17082. this._cachedTextureMatrix.m[0] = this._t1.x;
  17083. this._cachedTextureMatrix.m[1] = this._t1.y;
  17084. this._cachedTextureMatrix.m[2] = this._t1.z;
  17085. this._cachedTextureMatrix.m[4] = this._t2.x;
  17086. this._cachedTextureMatrix.m[5] = this._t2.y;
  17087. this._cachedTextureMatrix.m[6] = this._t2.z;
  17088. this._cachedTextureMatrix.m[8] = this._t0.x;
  17089. this._cachedTextureMatrix.m[9] = this._t0.y;
  17090. this._cachedTextureMatrix.m[10] = this._t0.z;
  17091. return this._cachedTextureMatrix;
  17092. };
  17093. Texture.prototype.getReflectionTextureMatrix = function () {
  17094. if (this.uOffset === this._cachedUOffset &&
  17095. this.vOffset === this._cachedVOffset &&
  17096. this.uScale === this._cachedUScale &&
  17097. this.vScale === this._cachedVScale &&
  17098. this.coordinatesMode === this._cachedCoordinatesMode) {
  17099. return this._cachedTextureMatrix;
  17100. }
  17101. if (!this._cachedTextureMatrix) {
  17102. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17103. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17104. }
  17105. this._cachedCoordinatesMode = this.coordinatesMode;
  17106. switch (this.coordinatesMode) {
  17107. case Texture.SPHERICAL_MODE:
  17108. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17109. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  17110. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  17111. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  17112. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  17113. break;
  17114. case Texture.PLANAR_MODE:
  17115. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17116. this._cachedTextureMatrix[0] = this.uScale;
  17117. this._cachedTextureMatrix[5] = this.vScale;
  17118. this._cachedTextureMatrix[12] = this.uOffset;
  17119. this._cachedTextureMatrix[13] = this.vOffset;
  17120. break;
  17121. case Texture.PROJECTION_MODE:
  17122. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17123. this._projectionModeMatrix.m[0] = 0.5;
  17124. this._projectionModeMatrix.m[5] = -0.5;
  17125. this._projectionModeMatrix.m[10] = 0.0;
  17126. this._projectionModeMatrix.m[12] = 0.5;
  17127. this._projectionModeMatrix.m[13] = 0.5;
  17128. this._projectionModeMatrix.m[14] = 1.0;
  17129. this._projectionModeMatrix.m[15] = 1.0;
  17130. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17131. break;
  17132. default:
  17133. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17134. break;
  17135. }
  17136. return this._cachedTextureMatrix;
  17137. };
  17138. Texture.prototype.clone = function () {
  17139. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17140. // Base texture
  17141. newTexture.hasAlpha = this.hasAlpha;
  17142. newTexture.level = this.level;
  17143. newTexture.wrapU = this.wrapU;
  17144. newTexture.wrapV = this.wrapV;
  17145. newTexture.coordinatesIndex = this.coordinatesIndex;
  17146. newTexture.coordinatesMode = this.coordinatesMode;
  17147. // Texture
  17148. newTexture.uOffset = this.uOffset;
  17149. newTexture.vOffset = this.vOffset;
  17150. newTexture.uScale = this.uScale;
  17151. newTexture.vScale = this.vScale;
  17152. newTexture.uAng = this.uAng;
  17153. newTexture.vAng = this.vAng;
  17154. newTexture.wAng = this.wAng;
  17155. return newTexture;
  17156. };
  17157. // Statics
  17158. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17159. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17160. if (onLoad === void 0) { onLoad = null; }
  17161. if (onError === void 0) { onError = null; }
  17162. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17163. };
  17164. // Constants
  17165. Texture.NEAREST_SAMPLINGMODE = 1;
  17166. Texture.BILINEAR_SAMPLINGMODE = 2;
  17167. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17168. Texture.EXPLICIT_MODE = 0;
  17169. Texture.SPHERICAL_MODE = 1;
  17170. Texture.PLANAR_MODE = 2;
  17171. Texture.CUBIC_MODE = 3;
  17172. Texture.PROJECTION_MODE = 4;
  17173. Texture.SKYBOX_MODE = 5;
  17174. Texture.INVCUBIC_MODE = 6;
  17175. Texture.CLAMP_ADDRESSMODE = 0;
  17176. Texture.WRAP_ADDRESSMODE = 1;
  17177. Texture.MIRROR_ADDRESSMODE = 2;
  17178. return Texture;
  17179. })(BABYLON.BaseTexture);
  17180. BABYLON.Texture = Texture;
  17181. })(BABYLON || (BABYLON = {}));
  17182. var BABYLON;
  17183. (function (BABYLON) {
  17184. var CubeTexture = (function (_super) {
  17185. __extends(CubeTexture, _super);
  17186. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17187. _super.call(this, scene);
  17188. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17189. this.name = rootUrl;
  17190. this.url = rootUrl;
  17191. this._noMipmap = noMipmap;
  17192. this.hasAlpha = false;
  17193. if (!rootUrl) {
  17194. return;
  17195. }
  17196. this._texture = this._getFromCache(rootUrl, noMipmap);
  17197. if (!extensions) {
  17198. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17199. }
  17200. this._extensions = extensions;
  17201. if (!this._texture) {
  17202. if (!scene.useDelayedTextureLoading) {
  17203. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17204. }
  17205. else {
  17206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17207. }
  17208. }
  17209. this.isCube = true;
  17210. this._textureMatrix = BABYLON.Matrix.Identity();
  17211. }
  17212. CubeTexture.prototype.clone = function () {
  17213. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17214. // Base texture
  17215. newTexture.level = this.level;
  17216. newTexture.wrapU = this.wrapU;
  17217. newTexture.wrapV = this.wrapV;
  17218. newTexture.coordinatesIndex = this.coordinatesIndex;
  17219. newTexture.coordinatesMode = this.coordinatesMode;
  17220. return newTexture;
  17221. };
  17222. // Methods
  17223. CubeTexture.prototype.delayLoad = function () {
  17224. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17225. return;
  17226. }
  17227. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17228. this._texture = this._getFromCache(this.url, this._noMipmap);
  17229. if (!this._texture) {
  17230. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17231. }
  17232. };
  17233. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17234. return this._textureMatrix;
  17235. };
  17236. return CubeTexture;
  17237. })(BABYLON.BaseTexture);
  17238. BABYLON.CubeTexture = CubeTexture;
  17239. })(BABYLON || (BABYLON = {}));
  17240. var BABYLON;
  17241. (function (BABYLON) {
  17242. var RenderTargetTexture = (function (_super) {
  17243. __extends(RenderTargetTexture, _super);
  17244. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17245. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17246. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17247. if (isCube === void 0) { isCube = false; }
  17248. _super.call(this, null, scene, !generateMipMaps);
  17249. this.isCube = isCube;
  17250. this.renderList = new Array();
  17251. this.renderParticles = true;
  17252. this.renderSprites = false;
  17253. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17254. this._currentRefreshId = -1;
  17255. this._refreshRate = 1;
  17256. this.name = name;
  17257. this.isRenderTarget = true;
  17258. this._size = size;
  17259. this._generateMipMaps = generateMipMaps;
  17260. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17261. if (isCube) {
  17262. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17263. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17264. this._textureMatrix = BABYLON.Matrix.Identity();
  17265. }
  17266. else {
  17267. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17268. }
  17269. // Rendering groups
  17270. this._renderingManager = new BABYLON.RenderingManager(scene);
  17271. }
  17272. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONCE", {
  17273. get: function () {
  17274. return RenderTargetTexture._REFRESHRATE_RENDERONCE;
  17275. },
  17276. enumerable: true,
  17277. configurable: true
  17278. });
  17279. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYFRAME", {
  17280. get: function () {
  17281. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME;
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYTWOFRAME", {
  17287. get: function () {
  17288. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME;
  17289. },
  17290. enumerable: true,
  17291. configurable: true
  17292. });
  17293. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17294. this._currentRefreshId = -1;
  17295. };
  17296. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17297. get: function () {
  17298. return this._refreshRate;
  17299. },
  17300. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17301. set: function (value) {
  17302. this._refreshRate = value;
  17303. this.resetRefreshCounter();
  17304. },
  17305. enumerable: true,
  17306. configurable: true
  17307. });
  17308. RenderTargetTexture.prototype._shouldRender = function () {
  17309. if (this._currentRefreshId === -1) {
  17310. this._currentRefreshId = 1;
  17311. return true;
  17312. }
  17313. if (this.refreshRate === this._currentRefreshId) {
  17314. this._currentRefreshId = 1;
  17315. return true;
  17316. }
  17317. this._currentRefreshId++;
  17318. return false;
  17319. };
  17320. RenderTargetTexture.prototype.isReady = function () {
  17321. if (!this.getScene().renderTargetsEnabled) {
  17322. return false;
  17323. }
  17324. return _super.prototype.isReady.call(this);
  17325. };
  17326. RenderTargetTexture.prototype.getRenderSize = function () {
  17327. return this._size;
  17328. };
  17329. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17330. get: function () {
  17331. return true;
  17332. },
  17333. enumerable: true,
  17334. configurable: true
  17335. });
  17336. RenderTargetTexture.prototype.scale = function (ratio) {
  17337. var newSize = this._size * ratio;
  17338. this.resize(newSize, this._generateMipMaps);
  17339. };
  17340. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17341. if (this.isCube) {
  17342. return this._textureMatrix;
  17343. }
  17344. return _super.prototype.getReflectionTextureMatrix.call(this);
  17345. };
  17346. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17347. this.releaseInternalTexture();
  17348. if (this.isCube) {
  17349. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17350. }
  17351. else {
  17352. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17353. }
  17354. };
  17355. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17356. var scene = this.getScene();
  17357. if (this._waitingRenderList) {
  17358. this.renderList = [];
  17359. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17360. var id = this._waitingRenderList[index];
  17361. this.renderList.push(scene.getMeshByID(id));
  17362. }
  17363. delete this._waitingRenderList;
  17364. }
  17365. if (this.renderList && this.renderList.length === 0) {
  17366. return;
  17367. }
  17368. // Prepare renderingManager
  17369. this._renderingManager.reset();
  17370. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17371. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17372. var mesh = currentRenderList[meshIndex];
  17373. if (mesh) {
  17374. if (!mesh.isReady()) {
  17375. // Reset _currentRefreshId
  17376. this.resetRefreshCounter();
  17377. continue;
  17378. }
  17379. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17380. mesh._activate(scene.getRenderId());
  17381. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17382. var subMesh = mesh.subMeshes[subIndex];
  17383. scene._activeIndices += subMesh.indexCount;
  17384. this._renderingManager.dispatch(subMesh);
  17385. }
  17386. }
  17387. }
  17388. }
  17389. if (this.isCube) {
  17390. for (var face = 0; face < 6; face++) {
  17391. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17392. }
  17393. }
  17394. else {
  17395. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17396. }
  17397. if (this.onAfterUnbind) {
  17398. this.onAfterUnbind();
  17399. }
  17400. scene.resetCachedMaterial();
  17401. };
  17402. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17403. var scene = this.getScene();
  17404. var engine = scene.getEngine();
  17405. // Bind
  17406. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17407. if (this.isCube) {
  17408. engine.bindFramebuffer(this._texture, faceIndex);
  17409. }
  17410. else {
  17411. engine.bindFramebuffer(this._texture);
  17412. }
  17413. }
  17414. if (this.onBeforeRender) {
  17415. this.onBeforeRender(faceIndex);
  17416. }
  17417. // Clear
  17418. if (this.onClear) {
  17419. this.onClear(engine);
  17420. }
  17421. else {
  17422. engine.clear(scene.clearColor, true, true);
  17423. }
  17424. if (!this._doNotChangeAspectRatio) {
  17425. scene.updateTransformMatrix(true);
  17426. }
  17427. // Render
  17428. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17429. if (useCameraPostProcess) {
  17430. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17431. }
  17432. if (!this._doNotChangeAspectRatio) {
  17433. scene.updateTransformMatrix(true);
  17434. }
  17435. if (this.onAfterRender) {
  17436. this.onAfterRender(faceIndex);
  17437. }
  17438. // Dump ?
  17439. if (dumpForDebug) {
  17440. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17441. }
  17442. // Unbind
  17443. if (!this.isCube || faceIndex === 5) {
  17444. if (this.isCube) {
  17445. if (faceIndex === 5) {
  17446. engine.generateMipMapsForCubemap(this._texture);
  17447. }
  17448. }
  17449. engine.unBindFramebuffer(this._texture, true);
  17450. }
  17451. };
  17452. RenderTargetTexture.prototype.clone = function () {
  17453. var textureSize = this.getSize();
  17454. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17455. // Base texture
  17456. newTexture.hasAlpha = this.hasAlpha;
  17457. newTexture.level = this.level;
  17458. // RenderTarget Texture
  17459. newTexture.coordinatesMode = this.coordinatesMode;
  17460. newTexture.renderList = this.renderList.slice(0);
  17461. return newTexture;
  17462. };
  17463. RenderTargetTexture._REFRESHRATE_RENDERONCE = 0;
  17464. RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME = 1;
  17465. RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME = 2;
  17466. return RenderTargetTexture;
  17467. })(BABYLON.Texture);
  17468. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17469. })(BABYLON || (BABYLON = {}));
  17470. var BABYLON;
  17471. (function (BABYLON) {
  17472. var ProceduralTexture = (function (_super) {
  17473. __extends(ProceduralTexture, _super);
  17474. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17475. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17476. _super.call(this, null, scene, !generateMipMaps);
  17477. this.isEnabled = true;
  17478. this._currentRefreshId = -1;
  17479. this._refreshRate = 1;
  17480. this._vertexDeclaration = [2];
  17481. this._vertexStrideSize = 2 * 4;
  17482. this._uniforms = new Array();
  17483. this._samplers = new Array();
  17484. this._textures = new Array();
  17485. this._floats = new Array();
  17486. this._floatsArrays = {};
  17487. this._colors3 = new Array();
  17488. this._colors4 = new Array();
  17489. this._vectors2 = new Array();
  17490. this._vectors3 = new Array();
  17491. this._matrices = new Array();
  17492. this._fallbackTextureUsed = false;
  17493. scene._proceduralTextures.push(this);
  17494. this.name = name;
  17495. this.isRenderTarget = true;
  17496. this._size = size;
  17497. this._generateMipMaps = generateMipMaps;
  17498. this.setFragment(fragment);
  17499. this._fallbackTexture = fallbackTexture;
  17500. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17501. // VBO
  17502. var vertices = [];
  17503. vertices.push(1, 1);
  17504. vertices.push(-1, 1);
  17505. vertices.push(-1, -1);
  17506. vertices.push(1, -1);
  17507. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17508. // Indices
  17509. var indices = [];
  17510. indices.push(0);
  17511. indices.push(1);
  17512. indices.push(2);
  17513. indices.push(0);
  17514. indices.push(2);
  17515. indices.push(3);
  17516. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17517. }
  17518. ProceduralTexture.prototype.reset = function () {
  17519. if (this._effect === undefined) {
  17520. return;
  17521. }
  17522. var engine = this.getScene().getEngine();
  17523. engine._releaseEffect(this._effect);
  17524. };
  17525. ProceduralTexture.prototype.isReady = function () {
  17526. var _this = this;
  17527. var engine = this.getScene().getEngine();
  17528. var shaders;
  17529. if (!this._fragment) {
  17530. return false;
  17531. }
  17532. if (this._fallbackTextureUsed) {
  17533. return true;
  17534. }
  17535. if (this._fragment.fragmentElement !== undefined) {
  17536. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17537. }
  17538. else {
  17539. shaders = { vertex: "procedural", fragment: this._fragment };
  17540. }
  17541. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17542. _this.releaseInternalTexture();
  17543. if (_this._fallbackTexture) {
  17544. _this._texture = _this._fallbackTexture._texture;
  17545. _this._texture.references++;
  17546. }
  17547. _this._fallbackTextureUsed = true;
  17548. });
  17549. return this._effect.isReady();
  17550. };
  17551. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17552. this._currentRefreshId = -1;
  17553. };
  17554. ProceduralTexture.prototype.setFragment = function (fragment) {
  17555. this._fragment = fragment;
  17556. };
  17557. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17558. get: function () {
  17559. return this._refreshRate;
  17560. },
  17561. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17562. set: function (value) {
  17563. this._refreshRate = value;
  17564. this.resetRefreshCounter();
  17565. },
  17566. enumerable: true,
  17567. configurable: true
  17568. });
  17569. ProceduralTexture.prototype._shouldRender = function () {
  17570. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17571. return false;
  17572. }
  17573. if (this._fallbackTextureUsed) {
  17574. return false;
  17575. }
  17576. if (this._currentRefreshId === -1) {
  17577. this._currentRefreshId = 1;
  17578. return true;
  17579. }
  17580. if (this.refreshRate === this._currentRefreshId) {
  17581. this._currentRefreshId = 1;
  17582. return true;
  17583. }
  17584. this._currentRefreshId++;
  17585. return false;
  17586. };
  17587. ProceduralTexture.prototype.getRenderSize = function () {
  17588. return this._size;
  17589. };
  17590. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17591. if (this._fallbackTextureUsed) {
  17592. return;
  17593. }
  17594. this.releaseInternalTexture();
  17595. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17596. };
  17597. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17598. if (this._uniforms.indexOf(uniformName) === -1) {
  17599. this._uniforms.push(uniformName);
  17600. }
  17601. };
  17602. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17603. if (this._samplers.indexOf(name) === -1) {
  17604. this._samplers.push(name);
  17605. }
  17606. this._textures[name] = texture;
  17607. return this;
  17608. };
  17609. ProceduralTexture.prototype.setFloat = function (name, value) {
  17610. this._checkUniform(name);
  17611. this._floats[name] = value;
  17612. return this;
  17613. };
  17614. ProceduralTexture.prototype.setFloats = function (name, value) {
  17615. this._checkUniform(name);
  17616. this._floatsArrays[name] = value;
  17617. return this;
  17618. };
  17619. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17620. this._checkUniform(name);
  17621. this._colors3[name] = value;
  17622. return this;
  17623. };
  17624. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17625. this._checkUniform(name);
  17626. this._colors4[name] = value;
  17627. return this;
  17628. };
  17629. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17630. this._checkUniform(name);
  17631. this._vectors2[name] = value;
  17632. return this;
  17633. };
  17634. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17635. this._checkUniform(name);
  17636. this._vectors3[name] = value;
  17637. return this;
  17638. };
  17639. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17640. this._checkUniform(name);
  17641. this._matrices[name] = value;
  17642. return this;
  17643. };
  17644. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17645. var scene = this.getScene();
  17646. var engine = scene.getEngine();
  17647. engine.bindFramebuffer(this._texture);
  17648. // Clear
  17649. engine.clear(scene.clearColor, true, true);
  17650. // Render
  17651. engine.enableEffect(this._effect);
  17652. engine.setState(false);
  17653. // Texture
  17654. for (var name in this._textures) {
  17655. this._effect.setTexture(name, this._textures[name]);
  17656. }
  17657. // Float
  17658. for (name in this._floats) {
  17659. this._effect.setFloat(name, this._floats[name]);
  17660. }
  17661. // Floats
  17662. for (name in this._floatsArrays) {
  17663. this._effect.setArray(name, this._floatsArrays[name]);
  17664. }
  17665. // Color3
  17666. for (name in this._colors3) {
  17667. this._effect.setColor3(name, this._colors3[name]);
  17668. }
  17669. // Color4
  17670. for (name in this._colors4) {
  17671. var color = this._colors4[name];
  17672. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17673. }
  17674. // Vector2
  17675. for (name in this._vectors2) {
  17676. this._effect.setVector2(name, this._vectors2[name]);
  17677. }
  17678. // Vector3
  17679. for (name in this._vectors3) {
  17680. this._effect.setVector3(name, this._vectors3[name]);
  17681. }
  17682. // Matrix
  17683. for (name in this._matrices) {
  17684. this._effect.setMatrix(name, this._matrices[name]);
  17685. }
  17686. // VBOs
  17687. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17688. // Draw order
  17689. engine.draw(true, 0, 6);
  17690. // Unbind
  17691. engine.unBindFramebuffer(this._texture);
  17692. };
  17693. ProceduralTexture.prototype.clone = function () {
  17694. var textureSize = this.getSize();
  17695. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17696. // Base texture
  17697. newTexture.hasAlpha = this.hasAlpha;
  17698. newTexture.level = this.level;
  17699. // RenderTarget Texture
  17700. newTexture.coordinatesMode = this.coordinatesMode;
  17701. return newTexture;
  17702. };
  17703. ProceduralTexture.prototype.dispose = function () {
  17704. var index = this.getScene()._proceduralTextures.indexOf(this);
  17705. if (index >= 0) {
  17706. this.getScene()._proceduralTextures.splice(index, 1);
  17707. }
  17708. _super.prototype.dispose.call(this);
  17709. };
  17710. return ProceduralTexture;
  17711. })(BABYLON.Texture);
  17712. BABYLON.ProceduralTexture = ProceduralTexture;
  17713. })(BABYLON || (BABYLON = {}));
  17714. var BABYLON;
  17715. (function (BABYLON) {
  17716. var MirrorTexture = (function (_super) {
  17717. __extends(MirrorTexture, _super);
  17718. function MirrorTexture(name, size, scene, generateMipMaps) {
  17719. var _this = this;
  17720. _super.call(this, name, size, scene, generateMipMaps, true);
  17721. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17722. this._transformMatrix = BABYLON.Matrix.Zero();
  17723. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17724. this.onBeforeRender = function () {
  17725. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17726. _this._savedViewMatrix = scene.getViewMatrix();
  17727. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17728. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17729. scene.clipPlane = _this.mirrorPlane;
  17730. scene.getEngine().cullBackFaces = false;
  17731. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17732. };
  17733. this.onAfterRender = function () {
  17734. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17735. scene.getEngine().cullBackFaces = true;
  17736. scene._mirroredCameraPosition = null;
  17737. delete scene.clipPlane;
  17738. };
  17739. }
  17740. MirrorTexture.prototype.clone = function () {
  17741. var textureSize = this.getSize();
  17742. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17743. // Base texture
  17744. newTexture.hasAlpha = this.hasAlpha;
  17745. newTexture.level = this.level;
  17746. // Mirror Texture
  17747. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17748. newTexture.renderList = this.renderList.slice(0);
  17749. return newTexture;
  17750. };
  17751. return MirrorTexture;
  17752. })(BABYLON.RenderTargetTexture);
  17753. BABYLON.MirrorTexture = MirrorTexture;
  17754. })(BABYLON || (BABYLON = {}));
  17755. var BABYLON;
  17756. (function (BABYLON) {
  17757. var DynamicTexture = (function (_super) {
  17758. __extends(DynamicTexture, _super);
  17759. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17761. _super.call(this, null, scene, !generateMipMaps);
  17762. this.name = name;
  17763. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17764. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17765. this._generateMipMaps = generateMipMaps;
  17766. if (options.getContext) {
  17767. this._canvas = options;
  17768. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17769. }
  17770. else {
  17771. this._canvas = document.createElement("canvas");
  17772. if (options.width) {
  17773. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17774. }
  17775. else {
  17776. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17777. }
  17778. }
  17779. var textureSize = this.getSize();
  17780. this._canvas.width = textureSize.width;
  17781. this._canvas.height = textureSize.height;
  17782. this._context = this._canvas.getContext("2d");
  17783. }
  17784. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17785. get: function () {
  17786. return true;
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. DynamicTexture.prototype.scale = function (ratio) {
  17792. var textureSize = this.getSize();
  17793. textureSize.width *= ratio;
  17794. textureSize.height *= ratio;
  17795. this._canvas.width = textureSize.width;
  17796. this._canvas.height = textureSize.height;
  17797. this.releaseInternalTexture();
  17798. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17799. };
  17800. DynamicTexture.prototype.getContext = function () {
  17801. return this._context;
  17802. };
  17803. DynamicTexture.prototype.clear = function () {
  17804. var size = this.getSize();
  17805. this._context.fillRect(0, 0, size.width, size.height);
  17806. };
  17807. DynamicTexture.prototype.update = function (invertY) {
  17808. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17809. };
  17810. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17811. if (update === void 0) { update = true; }
  17812. var size = this.getSize();
  17813. if (clearColor) {
  17814. this._context.fillStyle = clearColor;
  17815. this._context.fillRect(0, 0, size.width, size.height);
  17816. }
  17817. this._context.font = font;
  17818. if (x === null) {
  17819. var textSize = this._context.measureText(text);
  17820. x = (size.width - textSize.width) / 2;
  17821. }
  17822. this._context.fillStyle = color;
  17823. this._context.fillText(text, x, y);
  17824. if (update) {
  17825. this.update(invertY);
  17826. }
  17827. };
  17828. DynamicTexture.prototype.clone = function () {
  17829. var textureSize = this.getSize();
  17830. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17831. // Base texture
  17832. newTexture.hasAlpha = this.hasAlpha;
  17833. newTexture.level = this.level;
  17834. // Dynamic Texture
  17835. newTexture.wrapU = this.wrapU;
  17836. newTexture.wrapV = this.wrapV;
  17837. return newTexture;
  17838. };
  17839. return DynamicTexture;
  17840. })(BABYLON.Texture);
  17841. BABYLON.DynamicTexture = DynamicTexture;
  17842. })(BABYLON || (BABYLON = {}));
  17843. var BABYLON;
  17844. (function (BABYLON) {
  17845. var VideoTexture = (function (_super) {
  17846. __extends(VideoTexture, _super);
  17847. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17848. var _this = this;
  17849. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17850. if (invertY === void 0) { invertY = false; }
  17851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17852. _super.call(this, null, scene, !generateMipMaps, invertY);
  17853. this._autoLaunch = true;
  17854. this.name = name;
  17855. this.video = document.createElement("video");
  17856. this.video.autoplay = false;
  17857. this.video.loop = true;
  17858. this.video.addEventListener("canplaythrough", function () {
  17859. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17860. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17861. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17862. }
  17863. else {
  17864. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17865. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17866. generateMipMaps = false;
  17867. }
  17868. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17869. _this._texture.isReady = true;
  17870. });
  17871. urls.forEach(function (url) {
  17872. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17873. var source = document.createElement("source");
  17874. source.src = url;
  17875. _this.video.appendChild(source);
  17876. });
  17877. this._lastUpdate = BABYLON.Tools.Now;
  17878. }
  17879. VideoTexture.prototype.update = function () {
  17880. if (this._autoLaunch) {
  17881. this._autoLaunch = false;
  17882. this.video.play();
  17883. }
  17884. var now = BABYLON.Tools.Now;
  17885. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17886. return false;
  17887. }
  17888. this._lastUpdate = now;
  17889. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17890. return true;
  17891. };
  17892. return VideoTexture;
  17893. })(BABYLON.Texture);
  17894. BABYLON.VideoTexture = VideoTexture;
  17895. })(BABYLON || (BABYLON = {}));
  17896. var BABYLON;
  17897. (function (BABYLON) {
  17898. var CustomProceduralTexture = (function (_super) {
  17899. __extends(CustomProceduralTexture, _super);
  17900. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17901. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17902. this._animate = true;
  17903. this._time = 0;
  17904. this._texturePath = texturePath;
  17905. //Try to load json
  17906. this.loadJson(texturePath);
  17907. this.refreshRate = 1;
  17908. }
  17909. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17910. var _this = this;
  17911. var that = this;
  17912. function noConfigFile() {
  17913. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17914. try {
  17915. that.setFragment(that._texturePath);
  17916. }
  17917. catch (ex) {
  17918. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17919. }
  17920. }
  17921. var configFileUrl = jsonUrl + "/config.json";
  17922. var xhr = new XMLHttpRequest();
  17923. xhr.open("GET", configFileUrl, true);
  17924. xhr.addEventListener("load", function () {
  17925. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17926. try {
  17927. _this._config = JSON.parse(xhr.response);
  17928. _this.updateShaderUniforms();
  17929. _this.updateTextures();
  17930. _this.setFragment(_this._texturePath + "/custom");
  17931. _this._animate = _this._config.animate;
  17932. _this.refreshRate = _this._config.refreshrate;
  17933. }
  17934. catch (ex) {
  17935. noConfigFile();
  17936. }
  17937. }
  17938. else {
  17939. noConfigFile();
  17940. }
  17941. }, false);
  17942. xhr.addEventListener("error", function () {
  17943. noConfigFile();
  17944. }, false);
  17945. try {
  17946. xhr.send();
  17947. }
  17948. catch (ex) {
  17949. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17950. }
  17951. };
  17952. CustomProceduralTexture.prototype.isReady = function () {
  17953. if (!_super.prototype.isReady.call(this)) {
  17954. return false;
  17955. }
  17956. for (var name in this._textures) {
  17957. var texture = this._textures[name];
  17958. if (!texture.isReady()) {
  17959. return false;
  17960. }
  17961. }
  17962. return true;
  17963. };
  17964. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17965. if (this._animate) {
  17966. this._time += this.getScene().getAnimationRatio() * 0.03;
  17967. this.updateShaderUniforms();
  17968. }
  17969. _super.prototype.render.call(this, useCameraPostProcess);
  17970. };
  17971. CustomProceduralTexture.prototype.updateTextures = function () {
  17972. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17973. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17974. }
  17975. };
  17976. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17977. if (this._config) {
  17978. for (var j = 0; j < this._config.uniforms.length; j++) {
  17979. var uniform = this._config.uniforms[j];
  17980. switch (uniform.type) {
  17981. case "float":
  17982. this.setFloat(uniform.name, uniform.value);
  17983. break;
  17984. case "color3":
  17985. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17986. break;
  17987. case "color4":
  17988. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17989. break;
  17990. case "vector2":
  17991. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17992. break;
  17993. case "vector3":
  17994. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17995. break;
  17996. }
  17997. }
  17998. }
  17999. this.setFloat("time", this._time);
  18000. };
  18001. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18002. get: function () {
  18003. return this._animate;
  18004. },
  18005. set: function (value) {
  18006. this._animate = value;
  18007. },
  18008. enumerable: true,
  18009. configurable: true
  18010. });
  18011. return CustomProceduralTexture;
  18012. })(BABYLON.ProceduralTexture);
  18013. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18014. })(BABYLON || (BABYLON = {}));
  18015. var BABYLON;
  18016. (function (BABYLON) {
  18017. var WoodProceduralTexture = (function (_super) {
  18018. __extends(WoodProceduralTexture, _super);
  18019. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18020. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  18021. this._ampScale = 100.0;
  18022. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  18023. this.updateShaderUniforms();
  18024. this.refreshRate = 0;
  18025. }
  18026. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  18027. this.setFloat("ampScale", this._ampScale);
  18028. this.setColor3("woodColor", this._woodColor);
  18029. };
  18030. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  18031. get: function () {
  18032. return this._ampScale;
  18033. },
  18034. set: function (value) {
  18035. this._ampScale = value;
  18036. this.updateShaderUniforms();
  18037. },
  18038. enumerable: true,
  18039. configurable: true
  18040. });
  18041. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  18042. get: function () {
  18043. return this._woodColor;
  18044. },
  18045. set: function (value) {
  18046. this._woodColor = value;
  18047. this.updateShaderUniforms();
  18048. },
  18049. enumerable: true,
  18050. configurable: true
  18051. });
  18052. return WoodProceduralTexture;
  18053. })(BABYLON.ProceduralTexture);
  18054. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  18055. var FireProceduralTexture = (function (_super) {
  18056. __extends(FireProceduralTexture, _super);
  18057. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18058. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  18059. this._time = 0.0;
  18060. this._speed = new BABYLON.Vector2(0.5, 0.3);
  18061. this._autoGenerateTime = true;
  18062. this._alphaThreshold = 0.5;
  18063. this._fireColors = FireProceduralTexture.RedFireColors;
  18064. this.updateShaderUniforms();
  18065. this.refreshRate = 1;
  18066. }
  18067. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  18068. this.setFloat("time", this._time);
  18069. this.setVector2("speed", this._speed);
  18070. this.setColor3("c1", this._fireColors[0]);
  18071. this.setColor3("c2", this._fireColors[1]);
  18072. this.setColor3("c3", this._fireColors[2]);
  18073. this.setColor3("c4", this._fireColors[3]);
  18074. this.setColor3("c5", this._fireColors[4]);
  18075. this.setColor3("c6", this._fireColors[5]);
  18076. this.setFloat("alphaThreshold", this._alphaThreshold);
  18077. };
  18078. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18079. if (this._autoGenerateTime) {
  18080. this._time += this.getScene().getAnimationRatio() * 0.03;
  18081. this.updateShaderUniforms();
  18082. }
  18083. _super.prototype.render.call(this, useCameraPostProcess);
  18084. };
  18085. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  18086. get: function () {
  18087. return [
  18088. new BABYLON.Color3(0.5, 0.0, 1.0),
  18089. new BABYLON.Color3(0.9, 0.0, 1.0),
  18090. new BABYLON.Color3(0.2, 0.0, 1.0),
  18091. new BABYLON.Color3(1.0, 0.9, 1.0),
  18092. new BABYLON.Color3(0.1, 0.1, 1.0),
  18093. new BABYLON.Color3(0.9, 0.9, 1.0)
  18094. ];
  18095. },
  18096. enumerable: true,
  18097. configurable: true
  18098. });
  18099. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  18100. get: function () {
  18101. return [
  18102. new BABYLON.Color3(0.5, 1.0, 0.0),
  18103. new BABYLON.Color3(0.5, 1.0, 0.0),
  18104. new BABYLON.Color3(0.3, 0.4, 0.0),
  18105. new BABYLON.Color3(0.5, 1.0, 0.0),
  18106. new BABYLON.Color3(0.2, 0.0, 0.0),
  18107. new BABYLON.Color3(0.5, 1.0, 0.0)
  18108. ];
  18109. },
  18110. enumerable: true,
  18111. configurable: true
  18112. });
  18113. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  18114. get: function () {
  18115. return [
  18116. new BABYLON.Color3(0.5, 0.0, 0.1),
  18117. new BABYLON.Color3(0.9, 0.0, 0.0),
  18118. new BABYLON.Color3(0.2, 0.0, 0.0),
  18119. new BABYLON.Color3(1.0, 0.9, 0.0),
  18120. new BABYLON.Color3(0.1, 0.1, 0.1),
  18121. new BABYLON.Color3(0.9, 0.9, 0.9)
  18122. ];
  18123. },
  18124. enumerable: true,
  18125. configurable: true
  18126. });
  18127. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  18128. get: function () {
  18129. return [
  18130. new BABYLON.Color3(0.1, 0.0, 0.5),
  18131. new BABYLON.Color3(0.0, 0.0, 0.5),
  18132. new BABYLON.Color3(0.1, 0.0, 0.2),
  18133. new BABYLON.Color3(0.0, 0.0, 1.0),
  18134. new BABYLON.Color3(0.1, 0.2, 0.3),
  18135. new BABYLON.Color3(0.0, 0.2, 0.9)
  18136. ];
  18137. },
  18138. enumerable: true,
  18139. configurable: true
  18140. });
  18141. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  18142. get: function () {
  18143. return this._fireColors;
  18144. },
  18145. set: function (value) {
  18146. this._fireColors = value;
  18147. this.updateShaderUniforms();
  18148. },
  18149. enumerable: true,
  18150. configurable: true
  18151. });
  18152. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  18153. get: function () {
  18154. return this._time;
  18155. },
  18156. set: function (value) {
  18157. this._time = value;
  18158. this.updateShaderUniforms();
  18159. },
  18160. enumerable: true,
  18161. configurable: true
  18162. });
  18163. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  18164. get: function () {
  18165. return this._speed;
  18166. },
  18167. set: function (value) {
  18168. this._speed = value;
  18169. this.updateShaderUniforms();
  18170. },
  18171. enumerable: true,
  18172. configurable: true
  18173. });
  18174. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  18175. get: function () {
  18176. return this._alphaThreshold;
  18177. },
  18178. set: function (value) {
  18179. this._alphaThreshold = value;
  18180. this.updateShaderUniforms();
  18181. },
  18182. enumerable: true,
  18183. configurable: true
  18184. });
  18185. return FireProceduralTexture;
  18186. })(BABYLON.ProceduralTexture);
  18187. BABYLON.FireProceduralTexture = FireProceduralTexture;
  18188. var CloudProceduralTexture = (function (_super) {
  18189. __extends(CloudProceduralTexture, _super);
  18190. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18191. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  18192. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  18193. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  18194. this.updateShaderUniforms();
  18195. this.refreshRate = 0;
  18196. }
  18197. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  18198. this.setColor4("skyColor", this._skyColor);
  18199. this.setColor4("cloudColor", this._cloudColor);
  18200. };
  18201. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  18202. get: function () {
  18203. return this._skyColor;
  18204. },
  18205. set: function (value) {
  18206. this._skyColor = value;
  18207. this.updateShaderUniforms();
  18208. },
  18209. enumerable: true,
  18210. configurable: true
  18211. });
  18212. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  18213. get: function () {
  18214. return this._cloudColor;
  18215. },
  18216. set: function (value) {
  18217. this._cloudColor = value;
  18218. this.updateShaderUniforms();
  18219. },
  18220. enumerable: true,
  18221. configurable: true
  18222. });
  18223. return CloudProceduralTexture;
  18224. })(BABYLON.ProceduralTexture);
  18225. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  18226. var GrassProceduralTexture = (function (_super) {
  18227. __extends(GrassProceduralTexture, _super);
  18228. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18229. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  18230. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  18231. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  18232. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  18233. this._groundColor = new BABYLON.Color3(1, 1, 1);
  18234. this._grassColors = [
  18235. new BABYLON.Color3(0.29, 0.38, 0.02),
  18236. new BABYLON.Color3(0.36, 0.49, 0.09),
  18237. new BABYLON.Color3(0.51, 0.6, 0.28)
  18238. ];
  18239. this.updateShaderUniforms();
  18240. this.refreshRate = 0;
  18241. }
  18242. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  18243. this.setColor3("herb1Color", this._grassColors[0]);
  18244. this.setColor3("herb2Color", this._grassColors[1]);
  18245. this.setColor3("herb3Color", this._grassColors[2]);
  18246. this.setColor3("groundColor", this._groundColor);
  18247. };
  18248. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  18249. get: function () {
  18250. return this._grassColors;
  18251. },
  18252. set: function (value) {
  18253. this._grassColors = value;
  18254. this.updateShaderUniforms();
  18255. },
  18256. enumerable: true,
  18257. configurable: true
  18258. });
  18259. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  18260. get: function () {
  18261. return this._groundColor;
  18262. },
  18263. set: function (value) {
  18264. this.groundColor = value;
  18265. this.updateShaderUniforms();
  18266. },
  18267. enumerable: true,
  18268. configurable: true
  18269. });
  18270. return GrassProceduralTexture;
  18271. })(BABYLON.ProceduralTexture);
  18272. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  18273. var RoadProceduralTexture = (function (_super) {
  18274. __extends(RoadProceduralTexture, _super);
  18275. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18276. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  18277. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  18278. this.updateShaderUniforms();
  18279. this.refreshRate = 0;
  18280. }
  18281. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  18282. this.setColor3("roadColor", this._roadColor);
  18283. };
  18284. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  18285. get: function () {
  18286. return this._roadColor;
  18287. },
  18288. set: function (value) {
  18289. this._roadColor = value;
  18290. this.updateShaderUniforms();
  18291. },
  18292. enumerable: true,
  18293. configurable: true
  18294. });
  18295. return RoadProceduralTexture;
  18296. })(BABYLON.ProceduralTexture);
  18297. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  18298. var BrickProceduralTexture = (function (_super) {
  18299. __extends(BrickProceduralTexture, _super);
  18300. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18301. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  18302. this._numberOfBricksHeight = 15;
  18303. this._numberOfBricksWidth = 5;
  18304. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18305. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18306. this.updateShaderUniforms();
  18307. this.refreshRate = 0;
  18308. }
  18309. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  18310. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  18311. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  18312. this.setColor3("brickColor", this._brickColor);
  18313. this.setColor3("jointColor", this._jointColor);
  18314. };
  18315. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  18316. get: function () {
  18317. return this._numberOfBricksHeight;
  18318. },
  18319. set: function (value) {
  18320. this._numberOfBricksHeight = value;
  18321. this.updateShaderUniforms();
  18322. },
  18323. enumerable: true,
  18324. configurable: true
  18325. });
  18326. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  18327. get: function () {
  18328. return this._numberOfBricksWidth;
  18329. },
  18330. set: function (value) {
  18331. this._numberOfBricksWidth = value;
  18332. this.updateShaderUniforms();
  18333. },
  18334. enumerable: true,
  18335. configurable: true
  18336. });
  18337. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  18338. get: function () {
  18339. return this._jointColor;
  18340. },
  18341. set: function (value) {
  18342. this._jointColor = value;
  18343. this.updateShaderUniforms();
  18344. },
  18345. enumerable: true,
  18346. configurable: true
  18347. });
  18348. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  18349. get: function () {
  18350. return this._brickColor;
  18351. },
  18352. set: function (value) {
  18353. this._brickColor = value;
  18354. this.updateShaderUniforms();
  18355. },
  18356. enumerable: true,
  18357. configurable: true
  18358. });
  18359. return BrickProceduralTexture;
  18360. })(BABYLON.ProceduralTexture);
  18361. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  18362. var MarbleProceduralTexture = (function (_super) {
  18363. __extends(MarbleProceduralTexture, _super);
  18364. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18365. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  18366. this._numberOfTilesHeight = 3;
  18367. this._numberOfTilesWidth = 3;
  18368. this._amplitude = 9.0;
  18369. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18370. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18371. this.updateShaderUniforms();
  18372. this.refreshRate = 0;
  18373. }
  18374. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  18375. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  18376. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  18377. this.setFloat("amplitude", this._amplitude);
  18378. this.setColor3("marbleColor", this._marbleColor);
  18379. this.setColor3("jointColor", this._jointColor);
  18380. };
  18381. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  18382. get: function () {
  18383. return this._numberOfTilesHeight;
  18384. },
  18385. set: function (value) {
  18386. this._numberOfTilesHeight = value;
  18387. this.updateShaderUniforms();
  18388. },
  18389. enumerable: true,
  18390. configurable: true
  18391. });
  18392. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  18393. get: function () {
  18394. return this._numberOfTilesWidth;
  18395. },
  18396. set: function (value) {
  18397. this._numberOfTilesWidth = value;
  18398. this.updateShaderUniforms();
  18399. },
  18400. enumerable: true,
  18401. configurable: true
  18402. });
  18403. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  18404. get: function () {
  18405. return this._jointColor;
  18406. },
  18407. set: function (value) {
  18408. this._jointColor = value;
  18409. this.updateShaderUniforms();
  18410. },
  18411. enumerable: true,
  18412. configurable: true
  18413. });
  18414. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  18415. get: function () {
  18416. return this._marbleColor;
  18417. },
  18418. set: function (value) {
  18419. this._marbleColor = value;
  18420. this.updateShaderUniforms();
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. return MarbleProceduralTexture;
  18426. })(BABYLON.ProceduralTexture);
  18427. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18428. })(BABYLON || (BABYLON = {}));
  18429. var BABYLON;
  18430. (function (BABYLON) {
  18431. var EffectFallbacks = (function () {
  18432. function EffectFallbacks() {
  18433. this._defines = {};
  18434. this._currentRank = 32;
  18435. this._maxRank = -1;
  18436. }
  18437. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18438. if (!this._defines[rank]) {
  18439. if (rank < this._currentRank) {
  18440. this._currentRank = rank;
  18441. }
  18442. if (rank > this._maxRank) {
  18443. this._maxRank = rank;
  18444. }
  18445. this._defines[rank] = new Array();
  18446. }
  18447. this._defines[rank].push(define);
  18448. };
  18449. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18450. get: function () {
  18451. return this._currentRank <= this._maxRank;
  18452. },
  18453. enumerable: true,
  18454. configurable: true
  18455. });
  18456. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18457. var currentFallbacks = this._defines[this._currentRank];
  18458. for (var index = 0; index < currentFallbacks.length; index++) {
  18459. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18460. }
  18461. this._currentRank++;
  18462. return currentDefines;
  18463. };
  18464. return EffectFallbacks;
  18465. })();
  18466. BABYLON.EffectFallbacks = EffectFallbacks;
  18467. var Effect = (function () {
  18468. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18469. var _this = this;
  18470. this._isReady = false;
  18471. this._compilationError = "";
  18472. this._valueCache = [];
  18473. this._engine = engine;
  18474. this.name = baseName;
  18475. this.defines = defines;
  18476. this._uniformsNames = uniformsNames.concat(samplers);
  18477. this._samplers = samplers;
  18478. this._attributesNames = attributesNames;
  18479. this.onError = onError;
  18480. this.onCompiled = onCompiled;
  18481. var vertexSource;
  18482. var fragmentSource;
  18483. if (baseName.vertexElement) {
  18484. vertexSource = document.getElementById(baseName.vertexElement);
  18485. if (!vertexSource) {
  18486. vertexSource = baseName.vertexElement;
  18487. }
  18488. }
  18489. else {
  18490. vertexSource = baseName.vertex || baseName;
  18491. }
  18492. if (baseName.fragmentElement) {
  18493. fragmentSource = document.getElementById(baseName.fragmentElement);
  18494. if (!fragmentSource) {
  18495. fragmentSource = baseName.fragmentElement;
  18496. }
  18497. }
  18498. else {
  18499. fragmentSource = baseName.fragment || baseName;
  18500. }
  18501. this._loadVertexShader(vertexSource, function (vertexCode) {
  18502. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18503. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18504. });
  18505. });
  18506. }
  18507. // Properties
  18508. Effect.prototype.isReady = function () {
  18509. return this._isReady;
  18510. };
  18511. Effect.prototype.getProgram = function () {
  18512. return this._program;
  18513. };
  18514. Effect.prototype.getAttributesNames = function () {
  18515. return this._attributesNames;
  18516. };
  18517. Effect.prototype.getAttributeLocation = function (index) {
  18518. return this._attributes[index];
  18519. };
  18520. Effect.prototype.getAttributeLocationByName = function (name) {
  18521. var index = this._attributesNames.indexOf(name);
  18522. return this._attributes[index];
  18523. };
  18524. Effect.prototype.getAttributesCount = function () {
  18525. return this._attributes.length;
  18526. };
  18527. Effect.prototype.getUniformIndex = function (uniformName) {
  18528. return this._uniformsNames.indexOf(uniformName);
  18529. };
  18530. Effect.prototype.getUniform = function (uniformName) {
  18531. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18532. };
  18533. Effect.prototype.getSamplers = function () {
  18534. return this._samplers;
  18535. };
  18536. Effect.prototype.getCompilationError = function () {
  18537. return this._compilationError;
  18538. };
  18539. // Methods
  18540. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18541. // DOM element ?
  18542. if (vertex instanceof HTMLElement) {
  18543. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18544. callback(vertexCode);
  18545. return;
  18546. }
  18547. // Is in local store ?
  18548. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18549. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18550. return;
  18551. }
  18552. var vertexShaderUrl;
  18553. if (vertex[0] === "." || vertex[0] === "/") {
  18554. vertexShaderUrl = vertex;
  18555. }
  18556. else {
  18557. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18558. }
  18559. // Vertex shader
  18560. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18561. };
  18562. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18563. // DOM element ?
  18564. if (fragment instanceof HTMLElement) {
  18565. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18566. callback(fragmentCode);
  18567. return;
  18568. }
  18569. // Is in local store ?
  18570. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18571. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18572. return;
  18573. }
  18574. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18575. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18576. return;
  18577. }
  18578. var fragmentShaderUrl;
  18579. if (fragment[0] === "." || fragment[0] === "/") {
  18580. fragmentShaderUrl = fragment;
  18581. }
  18582. else {
  18583. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18584. }
  18585. // Fragment shader
  18586. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18587. };
  18588. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18589. try {
  18590. var engine = this._engine;
  18591. if (!engine.getCaps().highPrecisionShaderSupported) {
  18592. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18593. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18594. }
  18595. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18596. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18597. this._attributes = engine.getAttributes(this._program, attributesNames);
  18598. for (var index = 0; index < this._samplers.length; index++) {
  18599. var sampler = this.getUniform(this._samplers[index]);
  18600. if (sampler == null) {
  18601. this._samplers.splice(index, 1);
  18602. index--;
  18603. }
  18604. }
  18605. engine.bindSamplers(this);
  18606. this._isReady = true;
  18607. if (this.onCompiled) {
  18608. this.onCompiled(this);
  18609. }
  18610. }
  18611. catch (e) {
  18612. // Is it a problem with precision?
  18613. if (e.message.indexOf("highp") !== -1) {
  18614. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18615. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18616. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18617. return;
  18618. }
  18619. // Let's go through fallbacks then
  18620. if (fallbacks && fallbacks.isMoreFallbacks) {
  18621. defines = fallbacks.reduce(defines);
  18622. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18623. }
  18624. else {
  18625. BABYLON.Tools.Error("Unable to compile effect: ");
  18626. if (this.name.vertexElement) {
  18627. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18628. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18629. }
  18630. else if (this.name.vertex) {
  18631. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18632. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18633. }
  18634. else {
  18635. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18636. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18637. }
  18638. BABYLON.Tools.Error("Defines: " + defines);
  18639. BABYLON.Tools.Error("Error: " + e.message);
  18640. this._compilationError = e.message;
  18641. if (this.onError) {
  18642. this.onError(this, this._compilationError);
  18643. }
  18644. }
  18645. }
  18646. };
  18647. Effect.prototype._bindTexture = function (channel, texture) {
  18648. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18649. };
  18650. Effect.prototype.setTexture = function (channel, texture) {
  18651. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18652. };
  18653. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18654. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18655. };
  18656. //public _cacheMatrix(uniformName, matrix) {
  18657. // if (!this._valueCache[uniformName]) {
  18658. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18659. // }
  18660. // for (var index = 0; index < 16; index++) {
  18661. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18662. // }
  18663. //};
  18664. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18665. if (!this._valueCache[uniformName]) {
  18666. this._valueCache[uniformName] = [x, y];
  18667. return;
  18668. }
  18669. this._valueCache[uniformName][0] = x;
  18670. this._valueCache[uniformName][1] = y;
  18671. };
  18672. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18673. if (!this._valueCache[uniformName]) {
  18674. this._valueCache[uniformName] = [x, y, z];
  18675. return;
  18676. }
  18677. this._valueCache[uniformName][0] = x;
  18678. this._valueCache[uniformName][1] = y;
  18679. this._valueCache[uniformName][2] = z;
  18680. };
  18681. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18682. if (!this._valueCache[uniformName]) {
  18683. this._valueCache[uniformName] = [x, y, z, w];
  18684. return;
  18685. }
  18686. this._valueCache[uniformName][0] = x;
  18687. this._valueCache[uniformName][1] = y;
  18688. this._valueCache[uniformName][2] = z;
  18689. this._valueCache[uniformName][3] = w;
  18690. };
  18691. Effect.prototype.setArray = function (uniformName, array) {
  18692. this._engine.setArray(this.getUniform(uniformName), array);
  18693. return this;
  18694. };
  18695. Effect.prototype.setArray2 = function (uniformName, array) {
  18696. this._engine.setArray2(this.getUniform(uniformName), array);
  18697. return this;
  18698. };
  18699. Effect.prototype.setArray3 = function (uniformName, array) {
  18700. this._engine.setArray3(this.getUniform(uniformName), array);
  18701. return this;
  18702. };
  18703. Effect.prototype.setArray4 = function (uniformName, array) {
  18704. this._engine.setArray4(this.getUniform(uniformName), array);
  18705. return this;
  18706. };
  18707. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18708. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18709. return this;
  18710. };
  18711. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18712. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18713. // return;
  18714. //this._cacheMatrix(uniformName, matrix);
  18715. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18716. return this;
  18717. };
  18718. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18719. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18720. return this;
  18721. };
  18722. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18723. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18724. return this;
  18725. };
  18726. Effect.prototype.setFloat = function (uniformName, value) {
  18727. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18728. return this;
  18729. this._valueCache[uniformName] = value;
  18730. this._engine.setFloat(this.getUniform(uniformName), value);
  18731. return this;
  18732. };
  18733. Effect.prototype.setBool = function (uniformName, bool) {
  18734. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18735. return this;
  18736. this._valueCache[uniformName] = bool;
  18737. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18738. return this;
  18739. };
  18740. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18741. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18742. return this;
  18743. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18744. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18745. return this;
  18746. };
  18747. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18748. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18749. return this;
  18750. this._cacheFloat2(uniformName, x, y);
  18751. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18752. return this;
  18753. };
  18754. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18755. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18756. return this;
  18757. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18758. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18759. return this;
  18760. };
  18761. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18762. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18763. return this;
  18764. this._cacheFloat3(uniformName, x, y, z);
  18765. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18766. return this;
  18767. };
  18768. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18769. 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)
  18770. return this;
  18771. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18772. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18773. return this;
  18774. };
  18775. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18776. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18777. return this;
  18778. this._cacheFloat4(uniformName, x, y, z, w);
  18779. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18780. return this;
  18781. };
  18782. Effect.prototype.setColor3 = function (uniformName, color3) {
  18783. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18784. return this;
  18785. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18786. this._engine.setColor3(this.getUniform(uniformName), color3);
  18787. return this;
  18788. };
  18789. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18790. 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)
  18791. return this;
  18792. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18793. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18794. return this;
  18795. };
  18796. // Statics
  18797. Effect.ShadersStore = {};
  18798. return Effect;
  18799. })();
  18800. BABYLON.Effect = Effect;
  18801. })(BABYLON || (BABYLON = {}));
  18802. var BABYLON;
  18803. (function (BABYLON) {
  18804. var Material = (function () {
  18805. function Material(name, scene, doNotAdd) {
  18806. this.name = name;
  18807. this.checkReadyOnEveryCall = true;
  18808. this.checkReadyOnlyOnce = false;
  18809. this.state = "";
  18810. this.alpha = 1.0;
  18811. this.backFaceCulling = true;
  18812. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18813. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18814. this.disableDepthWrite = false;
  18815. this.fogEnabled = true;
  18816. this._wasPreviouslyReady = false;
  18817. this._fillMode = Material.TriangleFillMode;
  18818. this.pointSize = 1.0;
  18819. this.zOffset = 0;
  18820. this.id = name;
  18821. this._scene = scene;
  18822. if (!doNotAdd) {
  18823. scene.materials.push(this);
  18824. }
  18825. }
  18826. Object.defineProperty(Material, "TriangleFillMode", {
  18827. get: function () {
  18828. return Material._TriangleFillMode;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. Object.defineProperty(Material, "WireFrameFillMode", {
  18834. get: function () {
  18835. return Material._WireFrameFillMode;
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. Object.defineProperty(Material, "PointFillMode", {
  18841. get: function () {
  18842. return Material._PointFillMode;
  18843. },
  18844. enumerable: true,
  18845. configurable: true
  18846. });
  18847. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18848. get: function () {
  18849. return Material._ClockWiseSideOrientation;
  18850. },
  18851. enumerable: true,
  18852. configurable: true
  18853. });
  18854. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18855. get: function () {
  18856. return Material._CounterClockWiseSideOrientation;
  18857. },
  18858. enumerable: true,
  18859. configurable: true
  18860. });
  18861. Object.defineProperty(Material.prototype, "wireframe", {
  18862. get: function () {
  18863. return this._fillMode === Material.WireFrameFillMode;
  18864. },
  18865. set: function (value) {
  18866. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18867. },
  18868. enumerable: true,
  18869. configurable: true
  18870. });
  18871. Object.defineProperty(Material.prototype, "pointsCloud", {
  18872. get: function () {
  18873. return this._fillMode === Material.PointFillMode;
  18874. },
  18875. set: function (value) {
  18876. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18877. },
  18878. enumerable: true,
  18879. configurable: true
  18880. });
  18881. Object.defineProperty(Material.prototype, "fillMode", {
  18882. get: function () {
  18883. return this._fillMode;
  18884. },
  18885. set: function (value) {
  18886. this._fillMode = value;
  18887. },
  18888. enumerable: true,
  18889. configurable: true
  18890. });
  18891. Material.prototype.isReady = function (mesh, useInstances) {
  18892. return true;
  18893. };
  18894. Material.prototype.getEffect = function () {
  18895. return this._effect;
  18896. };
  18897. Material.prototype.getScene = function () {
  18898. return this._scene;
  18899. };
  18900. Material.prototype.needAlphaBlending = function () {
  18901. return (this.alpha < 1.0);
  18902. };
  18903. Material.prototype.needAlphaTesting = function () {
  18904. return false;
  18905. };
  18906. Material.prototype.getAlphaTestTexture = function () {
  18907. return null;
  18908. };
  18909. Material.prototype.trackCreation = function (onCompiled, onError) {
  18910. };
  18911. Material.prototype._preBind = function () {
  18912. var engine = this._scene.getEngine();
  18913. engine.enableEffect(this._effect);
  18914. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18915. };
  18916. Material.prototype.bind = function (world, mesh) {
  18917. this._scene._cachedMaterial = this;
  18918. if (this.onBind) {
  18919. this.onBind(this, mesh);
  18920. }
  18921. if (this.disableDepthWrite) {
  18922. var engine = this._scene.getEngine();
  18923. this._cachedDepthWriteState = engine.getDepthWrite();
  18924. engine.setDepthWrite(false);
  18925. }
  18926. };
  18927. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18928. };
  18929. Material.prototype.unbind = function () {
  18930. if (this.disableDepthWrite) {
  18931. var engine = this._scene.getEngine();
  18932. engine.setDepthWrite(this._cachedDepthWriteState);
  18933. }
  18934. };
  18935. Material.prototype.clone = function (name) {
  18936. return null;
  18937. };
  18938. Material.prototype.getBindedMeshes = function () {
  18939. var result = new Array();
  18940. for (var index = 0; index < this._scene.meshes.length; index++) {
  18941. var mesh = this._scene.meshes[index];
  18942. if (mesh.material === this) {
  18943. result.push(mesh);
  18944. }
  18945. }
  18946. return result;
  18947. };
  18948. Material.prototype.dispose = function (forceDisposeEffect) {
  18949. // Remove from scene
  18950. var index = this._scene.materials.indexOf(this);
  18951. if (index >= 0) {
  18952. this._scene.materials.splice(index, 1);
  18953. }
  18954. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18955. if (forceDisposeEffect && this._effect) {
  18956. this._scene.getEngine()._releaseEffect(this._effect);
  18957. this._effect = null;
  18958. }
  18959. // Remove from meshes
  18960. for (index = 0; index < this._scene.meshes.length; index++) {
  18961. var mesh = this._scene.meshes[index];
  18962. if (mesh.material === this) {
  18963. mesh.material = null;
  18964. }
  18965. }
  18966. // Callback
  18967. if (this.onDispose) {
  18968. this.onDispose();
  18969. }
  18970. };
  18971. Material.prototype.copyTo = function (other) {
  18972. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18973. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18974. other.alpha = this.alpha;
  18975. other.fillMode = this.fillMode;
  18976. other.backFaceCulling = this.backFaceCulling;
  18977. other.wireframe = this.wireframe;
  18978. other.fogEnabled = this.fogEnabled;
  18979. other.wireframe = this.wireframe;
  18980. other.zOffset = this.zOffset;
  18981. other.alphaMode = this.alphaMode;
  18982. other.sideOrientation = this.sideOrientation;
  18983. other.disableDepthWrite = this.disableDepthWrite;
  18984. other.pointSize = this.pointSize;
  18985. other.pointsCloud = this.pointsCloud;
  18986. };
  18987. Material._TriangleFillMode = 0;
  18988. Material._WireFrameFillMode = 1;
  18989. Material._PointFillMode = 2;
  18990. Material._ClockWiseSideOrientation = 0;
  18991. Material._CounterClockWiseSideOrientation = 1;
  18992. return Material;
  18993. })();
  18994. BABYLON.Material = Material;
  18995. })(BABYLON || (BABYLON = {}));
  18996. var BABYLON;
  18997. (function (BABYLON) {
  18998. var maxSimultaneousLights = 4;
  18999. var FresnelParameters = (function () {
  19000. function FresnelParameters() {
  19001. this.isEnabled = true;
  19002. this.leftColor = BABYLON.Color3.White();
  19003. this.rightColor = BABYLON.Color3.Black();
  19004. this.bias = 0;
  19005. this.power = 1;
  19006. }
  19007. FresnelParameters.prototype.clone = function () {
  19008. var newFresnelParameters = new FresnelParameters();
  19009. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19010. return new FresnelParameters;
  19011. };
  19012. return FresnelParameters;
  19013. })();
  19014. BABYLON.FresnelParameters = FresnelParameters;
  19015. var StandardMaterialDefines = (function () {
  19016. function StandardMaterialDefines() {
  19017. this.DIFFUSE = false;
  19018. this.AMBIENT = false;
  19019. this.OPACITY = false;
  19020. this.OPACITYRGB = false;
  19021. this.REFLECTION = false;
  19022. this.EMISSIVE = false;
  19023. this.SPECULAR = false;
  19024. this.BUMP = false;
  19025. this.SPECULAROVERALPHA = false;
  19026. this.CLIPPLANE = false;
  19027. this.ALPHATEST = false;
  19028. this.ALPHAFROMDIFFUSE = false;
  19029. this.POINTSIZE = false;
  19030. this.FOG = false;
  19031. this.LIGHT0 = false;
  19032. this.LIGHT1 = false;
  19033. this.LIGHT2 = false;
  19034. this.LIGHT3 = false;
  19035. this.SPOTLIGHT0 = false;
  19036. this.SPOTLIGHT1 = false;
  19037. this.SPOTLIGHT2 = false;
  19038. this.SPOTLIGHT3 = false;
  19039. this.HEMILIGHT0 = false;
  19040. this.HEMILIGHT1 = false;
  19041. this.HEMILIGHT2 = false;
  19042. this.HEMILIGHT3 = false;
  19043. this.POINTDIRLIGHT0 = false;
  19044. this.POINTDIRLIGHT1 = false;
  19045. this.POINTDIRLIGHT2 = false;
  19046. this.POINTDIRLIGHT3 = false;
  19047. this.SPECULARTERM = false;
  19048. this.SHADOW0 = false;
  19049. this.SHADOW1 = false;
  19050. this.SHADOW2 = false;
  19051. this.SHADOW3 = false;
  19052. this.SHADOWS = false;
  19053. this.SHADOWVSM0 = false;
  19054. this.SHADOWVSM1 = false;
  19055. this.SHADOWVSM2 = false;
  19056. this.SHADOWVSM3 = false;
  19057. this.SHADOWPCF0 = false;
  19058. this.SHADOWPCF1 = false;
  19059. this.SHADOWPCF2 = false;
  19060. this.SHADOWPCF3 = false;
  19061. this.DIFFUSEFRESNEL = false;
  19062. this.OPACITYFRESNEL = false;
  19063. this.REFLECTIONFRESNEL = false;
  19064. this.EMISSIVEFRESNEL = false;
  19065. this.FRESNEL = false;
  19066. this.NORMAL = false;
  19067. this.UV1 = false;
  19068. this.UV2 = false;
  19069. this.VERTEXCOLOR = false;
  19070. this.VERTEXALPHA = false;
  19071. this.BONES = false;
  19072. this.BONES4 = false;
  19073. this.BonesPerMesh = 0;
  19074. this.INSTANCES = false;
  19075. this.GLOSSINESS = false;
  19076. this.ROUGHNESS = false;
  19077. this.EMISSIVEASILLUMINATION = false;
  19078. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19079. this.LIGHTMAP = false;
  19080. this.INVERTCUBICMAP = false;
  19081. this._keys = Object.keys(this);
  19082. }
  19083. StandardMaterialDefines.prototype.isEqual = function (other) {
  19084. for (var index = 0; index < this._keys.length; index++) {
  19085. var prop = this._keys[index];
  19086. if (this[prop] !== other[prop]) {
  19087. return false;
  19088. }
  19089. }
  19090. return true;
  19091. };
  19092. StandardMaterialDefines.prototype.cloneTo = function (other) {
  19093. for (var index = 0; index < this._keys.length; index++) {
  19094. var prop = this._keys[index];
  19095. other[prop] = this[prop];
  19096. }
  19097. };
  19098. StandardMaterialDefines.prototype.reset = function () {
  19099. for (var index = 0; index < this._keys.length; index++) {
  19100. var prop = this._keys[index];
  19101. if (prop === "BonesPerMesh") {
  19102. this[prop] = 0;
  19103. continue;
  19104. }
  19105. this[prop] = false;
  19106. }
  19107. };
  19108. StandardMaterialDefines.prototype.toString = function () {
  19109. var result = "";
  19110. for (var index = 0; index < this._keys.length; index++) {
  19111. var prop = this._keys[index];
  19112. if (prop === "BonesPerMesh" && this[prop] > 0) {
  19113. result += "#define BonesPerMesh " + this[prop] + "\n";
  19114. continue;
  19115. }
  19116. if (this[prop]) {
  19117. result += "#define " + prop + "\n";
  19118. }
  19119. }
  19120. return result;
  19121. };
  19122. return StandardMaterialDefines;
  19123. })();
  19124. var StandardMaterial = (function (_super) {
  19125. __extends(StandardMaterial, _super);
  19126. function StandardMaterial(name, scene) {
  19127. var _this = this;
  19128. _super.call(this, name, scene);
  19129. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19130. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19131. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19132. this.specularPower = 64;
  19133. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19134. this.useAlphaFromDiffuseTexture = false;
  19135. this.useEmissiveAsIllumination = false;
  19136. this.useReflectionFresnelFromSpecular = false;
  19137. this.useSpecularOverAlpha = true;
  19138. this.roughness = 0;
  19139. this.lightmapThreshold = 0;
  19140. this.useGlossinessFromSpecularMapAlpha = false;
  19141. this._renderTargets = new BABYLON.SmartArray(16);
  19142. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19143. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19144. this._scaledDiffuse = new BABYLON.Color3();
  19145. this._scaledSpecular = new BABYLON.Color3();
  19146. this._defines = new StandardMaterialDefines();
  19147. this._cachedDefines = new StandardMaterialDefines();
  19148. this._cachedDefines.BonesPerMesh = -1;
  19149. this.getRenderTargetTextures = function () {
  19150. _this._renderTargets.reset();
  19151. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19152. _this._renderTargets.push(_this.reflectionTexture);
  19153. }
  19154. return _this._renderTargets;
  19155. };
  19156. }
  19157. StandardMaterial.prototype.needAlphaBlending = function () {
  19158. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19159. };
  19160. StandardMaterial.prototype.needAlphaTesting = function () {
  19161. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19162. };
  19163. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19164. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19165. };
  19166. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19167. return this.diffuseTexture;
  19168. };
  19169. // Methods
  19170. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19171. if (this.checkReadyOnlyOnce) {
  19172. if (this._wasPreviouslyReady) {
  19173. return true;
  19174. }
  19175. }
  19176. var scene = this.getScene();
  19177. if (!this.checkReadyOnEveryCall) {
  19178. if (this._renderId === scene.getRenderId()) {
  19179. return true;
  19180. }
  19181. }
  19182. var engine = scene.getEngine();
  19183. var needNormals = false;
  19184. var needUVs = false;
  19185. this._defines.reset();
  19186. // Textures
  19187. if (scene.texturesEnabled) {
  19188. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19189. if (!this.diffuseTexture.isReady()) {
  19190. return false;
  19191. }
  19192. else {
  19193. needUVs = true;
  19194. this._defines.DIFFUSE = true;
  19195. }
  19196. }
  19197. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19198. if (!this.ambientTexture.isReady()) {
  19199. return false;
  19200. }
  19201. else {
  19202. needUVs = true;
  19203. this._defines.AMBIENT = true;
  19204. }
  19205. }
  19206. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19207. if (!this.opacityTexture.isReady()) {
  19208. return false;
  19209. }
  19210. else {
  19211. needUVs = true;
  19212. this._defines.OPACITY = true;
  19213. if (this.opacityTexture.getAlphaFromRGB) {
  19214. this._defines.OPACITYRGB = true;
  19215. }
  19216. }
  19217. }
  19218. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19219. if (!this.reflectionTexture.isReady()) {
  19220. return false;
  19221. }
  19222. else {
  19223. needNormals = true;
  19224. needUVs = true;
  19225. this._defines.REFLECTION = true;
  19226. if (this.roughness > 0) {
  19227. this._defines.ROUGHNESS = true;
  19228. }
  19229. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19230. this._defines.INVERTCUBICMAP = true;
  19231. }
  19232. }
  19233. }
  19234. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19235. if (!this.emissiveTexture.isReady()) {
  19236. return false;
  19237. }
  19238. else {
  19239. needUVs = true;
  19240. this._defines.EMISSIVE = true;
  19241. }
  19242. }
  19243. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19244. if (!this.lightmapTexture.isReady()) {
  19245. return false;
  19246. }
  19247. else {
  19248. needUVs = true;
  19249. this._defines.LIGHTMAP = true;
  19250. }
  19251. }
  19252. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19253. if (!this.specularTexture.isReady()) {
  19254. return false;
  19255. }
  19256. else {
  19257. needUVs = true;
  19258. this._defines.SPECULAR = true;
  19259. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19260. }
  19261. }
  19262. }
  19263. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19264. if (!this.bumpTexture.isReady()) {
  19265. return false;
  19266. }
  19267. else {
  19268. needUVs = true;
  19269. this._defines.BUMP = true;
  19270. }
  19271. }
  19272. // Effect
  19273. if (scene.clipPlane) {
  19274. this._defines.CLIPPLANE = true;
  19275. }
  19276. if (engine.getAlphaTesting()) {
  19277. this._defines.ALPHATEST = true;
  19278. }
  19279. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19280. this._defines.ALPHAFROMDIFFUSE = true;
  19281. }
  19282. if (this.useEmissiveAsIllumination) {
  19283. this._defines.EMISSIVEASILLUMINATION = true;
  19284. }
  19285. if (this.useReflectionFresnelFromSpecular) {
  19286. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19287. }
  19288. // Point size
  19289. if (this.pointsCloud || scene.forcePointsCloud) {
  19290. this._defines.POINTSIZE = true;
  19291. }
  19292. // Fog
  19293. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19294. this._defines.FOG = true;
  19295. }
  19296. var lightIndex = 0;
  19297. if (scene.lightsEnabled) {
  19298. for (var index = 0; index < scene.lights.length; index++) {
  19299. var light = scene.lights[index];
  19300. if (!light.isEnabled()) {
  19301. continue;
  19302. }
  19303. // Excluded check
  19304. if (light._excludedMeshesIds.length > 0) {
  19305. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19306. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19307. if (excludedMesh) {
  19308. light.excludedMeshes.push(excludedMesh);
  19309. }
  19310. }
  19311. light._excludedMeshesIds = [];
  19312. }
  19313. // Included check
  19314. if (light._includedOnlyMeshesIds.length > 0) {
  19315. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19316. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19317. if (includedOnlyMesh) {
  19318. light.includedOnlyMeshes.push(includedOnlyMesh);
  19319. }
  19320. }
  19321. light._includedOnlyMeshesIds = [];
  19322. }
  19323. if (!light.canAffectMesh(mesh)) {
  19324. continue;
  19325. }
  19326. needNormals = true;
  19327. this._defines["LIGHT" + lightIndex] = true;
  19328. var type;
  19329. if (light instanceof BABYLON.SpotLight) {
  19330. type = "SPOTLIGHT" + lightIndex;
  19331. }
  19332. else if (light instanceof BABYLON.HemisphericLight) {
  19333. type = "HEMILIGHT" + lightIndex;
  19334. }
  19335. else {
  19336. type = "POINTDIRLIGHT" + lightIndex;
  19337. }
  19338. this._defines[type] = true;
  19339. // Specular
  19340. if (!light.specular.equalsFloats(0, 0, 0)) {
  19341. this._defines.SPECULARTERM = true;
  19342. }
  19343. // Shadows
  19344. if (scene.shadowsEnabled) {
  19345. var shadowGenerator = light.getShadowGenerator();
  19346. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19347. this._defines["SHADOW" + lightIndex] = true;
  19348. this._defines.SHADOWS = true;
  19349. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19350. this._defines["SHADOWVSM" + lightIndex] = true;
  19351. }
  19352. if (shadowGenerator.usePoissonSampling) {
  19353. this._defines["SHADOWPCF" + lightIndex] = true;
  19354. }
  19355. }
  19356. }
  19357. lightIndex++;
  19358. if (lightIndex === maxSimultaneousLights)
  19359. break;
  19360. }
  19361. }
  19362. if (StandardMaterial.FresnelEnabled) {
  19363. // Fresnel
  19364. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19365. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19366. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19367. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19368. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19369. this._defines.DIFFUSEFRESNEL = true;
  19370. }
  19371. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19372. this._defines.OPACITYFRESNEL = true;
  19373. }
  19374. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19375. this._defines.REFLECTIONFRESNEL = true;
  19376. }
  19377. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19378. this._defines.EMISSIVEFRESNEL = true;
  19379. }
  19380. needNormals = true;
  19381. this._defines.FRESNEL = true;
  19382. }
  19383. }
  19384. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19385. this._defines.SPECULAROVERALPHA = true;
  19386. }
  19387. // Attribs
  19388. if (mesh) {
  19389. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19390. this._defines.NORMAL = true;
  19391. }
  19392. if (needUVs) {
  19393. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19394. this._defines.UV1 = true;
  19395. }
  19396. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19397. this._defines.UV2 = true;
  19398. }
  19399. }
  19400. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19401. this._defines.VERTEXCOLOR = true;
  19402. if (mesh.hasVertexAlpha) {
  19403. this._defines.VERTEXALPHA = true;
  19404. }
  19405. }
  19406. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19407. this._defines.BONES = true;
  19408. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19409. this._defines.BONES4 = true;
  19410. }
  19411. // Instances
  19412. if (useInstances) {
  19413. this._defines.INSTANCES = true;
  19414. }
  19415. }
  19416. // Get correct effect
  19417. if (!this._defines.isEqual(this._cachedDefines)) {
  19418. this._defines.cloneTo(this._cachedDefines);
  19419. scene.resetCachedMaterial();
  19420. // Fallbacks
  19421. var fallbacks = new BABYLON.EffectFallbacks();
  19422. if (this._defines.REFLECTION) {
  19423. fallbacks.addFallback(0, "REFLECTION");
  19424. }
  19425. if (this._defines.SPECULAR) {
  19426. fallbacks.addFallback(0, "SPECULAR");
  19427. }
  19428. if (this._defines.BUMP) {
  19429. fallbacks.addFallback(0, "BUMP");
  19430. }
  19431. if (this._defines.SPECULAROVERALPHA) {
  19432. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19433. }
  19434. if (this._defines.FOG) {
  19435. fallbacks.addFallback(1, "FOG");
  19436. }
  19437. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19438. if (!this._defines["LIGHT" + lightIndex]) {
  19439. continue;
  19440. }
  19441. if (lightIndex > 0) {
  19442. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19443. }
  19444. if (this._defines["SHADOW" + lightIndex]) {
  19445. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19446. }
  19447. if (this._defines["SHADOWPCF" + lightIndex]) {
  19448. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19449. }
  19450. if (this._defines["SHADOWVSM" + lightIndex]) {
  19451. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19452. }
  19453. }
  19454. if (this._defines.SPECULARTERM) {
  19455. fallbacks.addFallback(0, "SPECULARTERM");
  19456. }
  19457. if (this._defines.DIFFUSEFRESNEL) {
  19458. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19459. }
  19460. if (this._defines.OPACITYFRESNEL) {
  19461. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19462. }
  19463. if (this._defines.REFLECTIONFRESNEL) {
  19464. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19465. }
  19466. if (this._defines.EMISSIVEFRESNEL) {
  19467. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19468. }
  19469. if (this._defines.FRESNEL) {
  19470. fallbacks.addFallback(4, "FRESNEL");
  19471. }
  19472. if (this._defines.BONES4) {
  19473. fallbacks.addFallback(0, "BONES4");
  19474. }
  19475. //Attributes
  19476. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19477. if (this._defines.NORMAL) {
  19478. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19479. }
  19480. if (this._defines.UV1) {
  19481. attribs.push(BABYLON.VertexBuffer.UVKind);
  19482. }
  19483. if (this._defines.UV2) {
  19484. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19485. }
  19486. if (this._defines.VERTEXCOLOR) {
  19487. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19488. }
  19489. if (this._defines.BONES) {
  19490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19492. }
  19493. if (this._defines.INSTANCES) {
  19494. attribs.push("world0");
  19495. attribs.push("world1");
  19496. attribs.push("world2");
  19497. attribs.push("world3");
  19498. }
  19499. // Legacy browser patch
  19500. var shaderName = "default";
  19501. if (!scene.getEngine().getCaps().standardDerivatives) {
  19502. shaderName = "legacydefault";
  19503. }
  19504. var join = this._defines.toString();
  19505. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19506. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19507. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19508. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19509. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19510. "vFogInfos", "vFogColor", "pointSize",
  19511. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19512. "mBones",
  19513. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19514. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19515. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19516. "roughness"
  19517. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19518. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19519. ], join, fallbacks, this.onCompiled, this.onError);
  19520. }
  19521. if (!this._effect.isReady()) {
  19522. return false;
  19523. }
  19524. this._renderId = scene.getRenderId();
  19525. this._wasPreviouslyReady = true;
  19526. return true;
  19527. };
  19528. StandardMaterial.prototype.unbind = function () {
  19529. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19530. this._effect.setTexture("reflection2DSampler", null);
  19531. }
  19532. _super.prototype.unbind.call(this);
  19533. };
  19534. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19535. this._effect.setMatrix("world", world);
  19536. };
  19537. StandardMaterial.prototype.bind = function (world, mesh) {
  19538. var scene = this.getScene();
  19539. // Matrices
  19540. this.bindOnlyWorldMatrix(world);
  19541. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19542. // Bones
  19543. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19544. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19545. }
  19546. if (scene.getCachedMaterial() !== this) {
  19547. if (StandardMaterial.FresnelEnabled) {
  19548. // Fresnel
  19549. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19550. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19551. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19552. }
  19553. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19554. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19555. }
  19556. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19557. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19558. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19559. }
  19560. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19561. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19562. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19563. }
  19564. }
  19565. // Textures
  19566. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19567. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19568. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19569. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19570. }
  19571. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19572. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19573. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19574. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19575. }
  19576. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19577. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19578. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19579. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19580. }
  19581. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19582. if (this.reflectionTexture.isCube) {
  19583. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19584. if (this._defines.ROUGHNESS) {
  19585. this._effect.setFloat("roughness", this.roughness);
  19586. }
  19587. }
  19588. else {
  19589. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19590. }
  19591. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19592. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE ? BABYLON.Texture.CUBIC_MODE : this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19593. }
  19594. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19595. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19596. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19597. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19598. }
  19599. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19600. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19601. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  19602. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19603. }
  19604. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19605. this._effect.setTexture("specularSampler", this.specularTexture);
  19606. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19607. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19608. }
  19609. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19610. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19611. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19612. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19613. }
  19614. // Clip plane
  19615. if (scene.clipPlane) {
  19616. var clipPlane = scene.clipPlane;
  19617. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19618. }
  19619. // Point size
  19620. if (this.pointsCloud) {
  19621. this._effect.setFloat("pointSize", this.pointSize);
  19622. }
  19623. // Colors
  19624. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19625. // Scaling down color according to emissive
  19626. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19627. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19628. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19629. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19630. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19631. if (this._defines.SPECULARTERM) {
  19632. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19633. }
  19634. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19635. }
  19636. // Scaling down color according to emissive
  19637. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19638. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19639. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19640. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19641. if (scene.lightsEnabled) {
  19642. var lightIndex = 0;
  19643. for (var index = 0; index < scene.lights.length; index++) {
  19644. var light = scene.lights[index];
  19645. if (!light.isEnabled()) {
  19646. continue;
  19647. }
  19648. if (!light.canAffectMesh(mesh)) {
  19649. continue;
  19650. }
  19651. if (light instanceof BABYLON.PointLight) {
  19652. // Point Light
  19653. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19654. }
  19655. else if (light instanceof BABYLON.DirectionalLight) {
  19656. // Directional Light
  19657. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19658. }
  19659. else if (light instanceof BABYLON.SpotLight) {
  19660. // Spot Light
  19661. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19662. }
  19663. else if (light instanceof BABYLON.HemisphericLight) {
  19664. // Hemispheric Light
  19665. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19666. }
  19667. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19668. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19669. if (this._defines.SPECULARTERM) {
  19670. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19671. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19672. }
  19673. // Shadows
  19674. if (scene.shadowsEnabled) {
  19675. var shadowGenerator = light.getShadowGenerator();
  19676. if (mesh.receiveShadows && shadowGenerator) {
  19677. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19678. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19679. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19680. }
  19681. }
  19682. lightIndex++;
  19683. if (lightIndex === maxSimultaneousLights)
  19684. break;
  19685. }
  19686. }
  19687. // View
  19688. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19689. this._effect.setMatrix("view", scene.getViewMatrix());
  19690. }
  19691. // Fog
  19692. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19693. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19694. this._effect.setColor3("vFogColor", scene.fogColor);
  19695. }
  19696. _super.prototype.bind.call(this, world, mesh);
  19697. };
  19698. StandardMaterial.prototype.getAnimatables = function () {
  19699. var results = [];
  19700. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19701. results.push(this.diffuseTexture);
  19702. }
  19703. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19704. results.push(this.ambientTexture);
  19705. }
  19706. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19707. results.push(this.opacityTexture);
  19708. }
  19709. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19710. results.push(this.reflectionTexture);
  19711. }
  19712. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19713. results.push(this.emissiveTexture);
  19714. }
  19715. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19716. results.push(this.specularTexture);
  19717. }
  19718. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19719. results.push(this.bumpTexture);
  19720. }
  19721. return results;
  19722. };
  19723. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19724. if (this.diffuseTexture) {
  19725. this.diffuseTexture.dispose();
  19726. }
  19727. if (this.ambientTexture) {
  19728. this.ambientTexture.dispose();
  19729. }
  19730. if (this.opacityTexture) {
  19731. this.opacityTexture.dispose();
  19732. }
  19733. if (this.reflectionTexture) {
  19734. this.reflectionTexture.dispose();
  19735. }
  19736. if (this.emissiveTexture) {
  19737. this.emissiveTexture.dispose();
  19738. }
  19739. if (this.specularTexture) {
  19740. this.specularTexture.dispose();
  19741. }
  19742. if (this.bumpTexture) {
  19743. this.bumpTexture.dispose();
  19744. }
  19745. _super.prototype.dispose.call(this, forceDisposeEffect);
  19746. };
  19747. StandardMaterial.prototype.clone = function (name) {
  19748. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19749. // Base material
  19750. this.copyTo(newStandardMaterial);
  19751. // Standard material
  19752. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19753. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19754. }
  19755. if (this.ambientTexture && this.ambientTexture.clone) {
  19756. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19757. }
  19758. if (this.opacityTexture && this.opacityTexture.clone) {
  19759. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19760. }
  19761. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19762. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19763. }
  19764. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19765. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19766. }
  19767. if (this.specularTexture && this.specularTexture.clone) {
  19768. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19769. }
  19770. if (this.bumpTexture && this.bumpTexture.clone) {
  19771. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19772. }
  19773. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19774. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19775. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19776. newStandardMaterial.lightmapThreshold = this.lightmapThreshold;
  19777. }
  19778. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19779. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19780. newStandardMaterial.specularColor = this.specularColor.clone();
  19781. newStandardMaterial.specularPower = this.specularPower;
  19782. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19783. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19784. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19785. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19786. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19787. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19788. newStandardMaterial.roughness = this.roughness;
  19789. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19790. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19791. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19792. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19793. return newStandardMaterial;
  19794. };
  19795. // Statics
  19796. // Flags used to enable or disable a type of texture for all Standard Materials
  19797. StandardMaterial.DiffuseTextureEnabled = true;
  19798. StandardMaterial.AmbientTextureEnabled = true;
  19799. StandardMaterial.OpacityTextureEnabled = true;
  19800. StandardMaterial.ReflectionTextureEnabled = true;
  19801. StandardMaterial.EmissiveTextureEnabled = true;
  19802. StandardMaterial.SpecularTextureEnabled = true;
  19803. StandardMaterial.BumpTextureEnabled = true;
  19804. StandardMaterial.FresnelEnabled = true;
  19805. StandardMaterial.LightmapEnabled = true;
  19806. return StandardMaterial;
  19807. })(BABYLON.Material);
  19808. BABYLON.StandardMaterial = StandardMaterial;
  19809. })(BABYLON || (BABYLON = {}));
  19810. var BABYLON;
  19811. (function (BABYLON) {
  19812. var MultiMaterial = (function (_super) {
  19813. __extends(MultiMaterial, _super);
  19814. function MultiMaterial(name, scene) {
  19815. _super.call(this, name, scene, true);
  19816. this.subMaterials = new Array();
  19817. scene.multiMaterials.push(this);
  19818. }
  19819. // Properties
  19820. MultiMaterial.prototype.getSubMaterial = function (index) {
  19821. if (index < 0 || index >= this.subMaterials.length) {
  19822. return this.getScene().defaultMaterial;
  19823. }
  19824. return this.subMaterials[index];
  19825. };
  19826. // Methods
  19827. MultiMaterial.prototype.isReady = function (mesh) {
  19828. for (var index = 0; index < this.subMaterials.length; index++) {
  19829. var subMaterial = this.subMaterials[index];
  19830. if (subMaterial) {
  19831. if (!this.subMaterials[index].isReady(mesh)) {
  19832. return false;
  19833. }
  19834. }
  19835. }
  19836. return true;
  19837. };
  19838. MultiMaterial.prototype.clone = function (name) {
  19839. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19840. for (var index = 0; index < this.subMaterials.length; index++) {
  19841. var subMaterial = this.subMaterials[index];
  19842. newMultiMaterial.subMaterials.push(subMaterial);
  19843. }
  19844. return newMultiMaterial;
  19845. };
  19846. return MultiMaterial;
  19847. })(BABYLON.Material);
  19848. BABYLON.MultiMaterial = MultiMaterial;
  19849. })(BABYLON || (BABYLON = {}));
  19850. var BABYLON;
  19851. (function (BABYLON) {
  19852. var SceneLoader = (function () {
  19853. function SceneLoader() {
  19854. }
  19855. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19856. get: function () {
  19857. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19858. },
  19859. set: function (value) {
  19860. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19866. get: function () {
  19867. return SceneLoader._ShowLoadingScreen;
  19868. },
  19869. set: function (value) {
  19870. SceneLoader._ShowLoadingScreen = value;
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19876. var dotPosition = sceneFilename.lastIndexOf(".");
  19877. var queryStringPosition = sceneFilename.indexOf("?");
  19878. if (queryStringPosition === -1) {
  19879. queryStringPosition = sceneFilename.length;
  19880. }
  19881. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19882. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19883. var plugin = this._registeredPlugins[index];
  19884. if (plugin.extensions.indexOf(extension) !== -1) {
  19885. return plugin;
  19886. }
  19887. }
  19888. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19889. };
  19890. // Public functions
  19891. SceneLoader.RegisterPlugin = function (plugin) {
  19892. plugin.extensions = plugin.extensions.toLowerCase();
  19893. SceneLoader._registeredPlugins.push(plugin);
  19894. };
  19895. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19896. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19897. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19898. return;
  19899. }
  19900. var loadingToken = {};
  19901. scene._addPendingData(loadingToken);
  19902. var manifestChecked = function (success) {
  19903. scene.database = database;
  19904. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19905. var importMeshFromData = function (data) {
  19906. var meshes = [];
  19907. var particleSystems = [];
  19908. var skeletons = [];
  19909. try {
  19910. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19911. if (onerror) {
  19912. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19913. }
  19914. scene._removePendingData(loadingToken);
  19915. return;
  19916. }
  19917. }
  19918. catch (e) {
  19919. if (onerror) {
  19920. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19921. }
  19922. scene._removePendingData(loadingToken);
  19923. return;
  19924. }
  19925. if (onsuccess) {
  19926. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19927. onsuccess(meshes, particleSystems, skeletons);
  19928. scene._removePendingData(loadingToken);
  19929. }
  19930. };
  19931. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19932. // Direct load
  19933. importMeshFromData(sceneFilename.substr(5));
  19934. return;
  19935. }
  19936. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19937. importMeshFromData(data);
  19938. }, progressCallBack, database);
  19939. };
  19940. if (scene.getEngine().enableOfflineSupport) {
  19941. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19942. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19943. }
  19944. else {
  19945. manifestChecked(true);
  19946. }
  19947. };
  19948. /**
  19949. * Load a scene
  19950. * @param rootUrl a string that defines the root url for scene and resources
  19951. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19952. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19953. */
  19954. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19955. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19956. };
  19957. /**
  19958. * Append a scene
  19959. * @param rootUrl a string that defines the root url for scene and resources
  19960. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19961. * @param scene is the instance of BABYLON.Scene to append to
  19962. */
  19963. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19964. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19965. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19966. return;
  19967. }
  19968. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19969. var database;
  19970. var loadingToken = {};
  19971. scene._addPendingData(loadingToken);
  19972. if (SceneLoader.ShowLoadingScreen) {
  19973. scene.getEngine().displayLoadingUI();
  19974. }
  19975. var loadSceneFromData = function (data) {
  19976. scene.database = database;
  19977. if (!plugin.load(scene, data, rootUrl)) {
  19978. if (onerror) {
  19979. onerror(scene);
  19980. }
  19981. scene._removePendingData(loadingToken);
  19982. scene.getEngine().hideLoadingUI();
  19983. return;
  19984. }
  19985. if (onsuccess) {
  19986. onsuccess(scene);
  19987. }
  19988. scene._removePendingData(loadingToken);
  19989. if (SceneLoader.ShowLoadingScreen) {
  19990. scene.executeWhenReady(function () {
  19991. scene.getEngine().hideLoadingUI();
  19992. });
  19993. }
  19994. };
  19995. var manifestChecked = function (success) {
  19996. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19997. };
  19998. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19999. // Direct load
  20000. loadSceneFromData(sceneFilename.substr(5));
  20001. return;
  20002. }
  20003. if (rootUrl.indexOf("file:") === -1) {
  20004. if (scene.getEngine().enableOfflineSupport) {
  20005. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20006. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20007. }
  20008. else {
  20009. manifestChecked(true);
  20010. }
  20011. }
  20012. else {
  20013. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20014. }
  20015. };
  20016. // Flags
  20017. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20018. SceneLoader._ShowLoadingScreen = true;
  20019. // Members
  20020. SceneLoader._registeredPlugins = new Array();
  20021. return SceneLoader;
  20022. })();
  20023. BABYLON.SceneLoader = SceneLoader;
  20024. ;
  20025. })(BABYLON || (BABYLON = {}));
  20026. var BABYLON;
  20027. (function (BABYLON) {
  20028. var Internals;
  20029. (function (Internals) {
  20030. var checkColors4 = function (colors, count) {
  20031. // Check if color3 was used
  20032. if (colors.length === count * 3) {
  20033. var colors4 = [];
  20034. for (var index = 0; index < colors.length; index += 3) {
  20035. var newIndex = (index / 3) * 4;
  20036. colors4[newIndex] = colors[index];
  20037. colors4[newIndex + 1] = colors[index + 1];
  20038. colors4[newIndex + 2] = colors[index + 2];
  20039. colors4[newIndex + 3] = 1.0;
  20040. }
  20041. return colors4;
  20042. }
  20043. return colors;
  20044. };
  20045. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  20046. var texture = null;
  20047. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  20048. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20049. texture.name = parsedTexture.name;
  20050. texture.hasAlpha = parsedTexture.hasAlpha;
  20051. texture.level = parsedTexture.level;
  20052. texture.coordinatesMode = parsedTexture.coordinatesMode;
  20053. }
  20054. return texture;
  20055. };
  20056. var loadTexture = function (rootUrl, parsedTexture, scene) {
  20057. if (parsedTexture.isCube) {
  20058. return loadCubeTexture(rootUrl, parsedTexture, scene);
  20059. }
  20060. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20061. return null;
  20062. }
  20063. var texture;
  20064. if (parsedTexture.mirrorPlane) {
  20065. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20066. texture._waitingRenderList = parsedTexture.renderList;
  20067. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20068. }
  20069. else if (parsedTexture.isRenderTarget) {
  20070. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20071. texture._waitingRenderList = parsedTexture.renderList;
  20072. }
  20073. else {
  20074. if (parsedTexture.base64String) {
  20075. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20076. }
  20077. else {
  20078. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  20079. }
  20080. }
  20081. texture.name = parsedTexture.name;
  20082. texture.hasAlpha = parsedTexture.hasAlpha;
  20083. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  20084. texture.level = parsedTexture.level;
  20085. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  20086. texture.coordinatesMode = parsedTexture.coordinatesMode;
  20087. texture.uOffset = parsedTexture.uOffset;
  20088. texture.vOffset = parsedTexture.vOffset;
  20089. texture.uScale = parsedTexture.uScale;
  20090. texture.vScale = parsedTexture.vScale;
  20091. texture.uAng = parsedTexture.uAng;
  20092. texture.vAng = parsedTexture.vAng;
  20093. texture.wAng = parsedTexture.wAng;
  20094. texture.wrapU = parsedTexture.wrapU;
  20095. texture.wrapV = parsedTexture.wrapV;
  20096. // Animations
  20097. if (parsedTexture.animations) {
  20098. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20099. var parsedAnimation = parsedTexture.animations[animationIndex];
  20100. texture.animations.push(parseAnimation(parsedAnimation));
  20101. }
  20102. }
  20103. return texture;
  20104. };
  20105. var parseSkeleton = function (parsedSkeleton, scene) {
  20106. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  20107. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  20108. var parsedBone = parsedSkeleton.bones[index];
  20109. var parentBone = null;
  20110. if (parsedBone.parentBoneIndex > -1) {
  20111. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  20112. }
  20113. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  20114. if (parsedBone.animation) {
  20115. bone.animations.push(parseAnimation(parsedBone.animation));
  20116. }
  20117. }
  20118. return skeleton;
  20119. };
  20120. var parseFresnelParameters = function (parsedFresnelParameters) {
  20121. var fresnelParameters = new BABYLON.FresnelParameters();
  20122. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  20123. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  20124. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  20125. fresnelParameters.bias = parsedFresnelParameters.bias;
  20126. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  20127. return fresnelParameters;
  20128. };
  20129. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  20130. var material;
  20131. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  20132. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  20133. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  20134. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  20135. material.specularPower = parsedMaterial.specularPower;
  20136. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  20137. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  20138. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  20139. material.alpha = parsedMaterial.alpha;
  20140. material.id = parsedMaterial.id;
  20141. if (parsedMaterial.disableDepthWrite) {
  20142. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  20143. }
  20144. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  20145. material.backFaceCulling = parsedMaterial.backFaceCulling;
  20146. material.wireframe = parsedMaterial.wireframe;
  20147. if (parsedMaterial.diffuseTexture) {
  20148. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  20149. }
  20150. if (parsedMaterial.diffuseFresnelParameters) {
  20151. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  20152. }
  20153. if (parsedMaterial.ambientTexture) {
  20154. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  20155. }
  20156. if (parsedMaterial.opacityTexture) {
  20157. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  20158. }
  20159. if (parsedMaterial.opacityFresnelParameters) {
  20160. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  20161. }
  20162. if (parsedMaterial.reflectionTexture) {
  20163. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  20164. }
  20165. if (parsedMaterial.reflectionFresnelParameters) {
  20166. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  20167. }
  20168. if (parsedMaterial.emissiveTexture) {
  20169. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  20170. }
  20171. if (parsedMaterial.lightmapTexture) {
  20172. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  20173. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  20174. }
  20175. if (parsedMaterial.emissiveFresnelParameters) {
  20176. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  20177. }
  20178. if (parsedMaterial.specularTexture) {
  20179. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  20180. }
  20181. if (parsedMaterial.bumpTexture) {
  20182. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  20183. }
  20184. if (parsedMaterial.checkReadyOnlyOnce) {
  20185. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  20186. }
  20187. return material;
  20188. };
  20189. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20190. for (var index = 0; index < parsedData.materials.length; index++) {
  20191. var parsedMaterial = parsedData.materials[index];
  20192. if (parsedMaterial.id === id) {
  20193. return parseMaterial(parsedMaterial, scene, rootUrl);
  20194. }
  20195. }
  20196. return null;
  20197. };
  20198. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  20199. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  20200. multiMaterial.id = parsedMultiMaterial.id;
  20201. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  20202. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20203. var subMatId = parsedMultiMaterial.materials[matIndex];
  20204. if (subMatId) {
  20205. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  20206. }
  20207. else {
  20208. multiMaterial.subMaterials.push(null);
  20209. }
  20210. }
  20211. return multiMaterial;
  20212. };
  20213. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  20214. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  20215. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  20216. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  20217. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  20218. var parsedFlare = parsedLensFlareSystem.flares[index];
  20219. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  20220. }
  20221. return lensFlareSystem;
  20222. };
  20223. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  20224. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  20225. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  20226. if (parsedParticleSystem.textureName) {
  20227. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  20228. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  20229. }
  20230. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  20231. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  20232. particleSystem.minSize = parsedParticleSystem.minSize;
  20233. particleSystem.maxSize = parsedParticleSystem.maxSize;
  20234. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  20235. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  20236. particleSystem.emitter = emitter;
  20237. particleSystem.emitRate = parsedParticleSystem.emitRate;
  20238. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  20239. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  20240. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  20241. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  20242. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  20243. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  20244. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  20245. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  20246. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  20247. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  20248. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  20249. particleSystem.blendMode = parsedParticleSystem.blendMode;
  20250. particleSystem.start();
  20251. return particleSystem;
  20252. };
  20253. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  20254. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  20255. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  20256. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  20257. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  20258. shadowGenerator.getShadowMap().renderList.push(mesh);
  20259. }
  20260. if (parsedShadowGenerator.usePoissonSampling) {
  20261. shadowGenerator.usePoissonSampling = true;
  20262. }
  20263. else if (parsedShadowGenerator.useVarianceShadowMap) {
  20264. shadowGenerator.useVarianceShadowMap = true;
  20265. }
  20266. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  20267. shadowGenerator.useBlurVarianceShadowMap = true;
  20268. if (parsedShadowGenerator.blurScale) {
  20269. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  20270. }
  20271. if (parsedShadowGenerator.blurBoxOffset) {
  20272. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  20273. }
  20274. }
  20275. if (parsedShadowGenerator.bias !== undefined) {
  20276. shadowGenerator.bias = parsedShadowGenerator.bias;
  20277. }
  20278. return shadowGenerator;
  20279. };
  20280. var parseAnimation = function (parsedAnimation) {
  20281. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  20282. var dataType = parsedAnimation.dataType;
  20283. var keys = [];
  20284. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  20285. var key = parsedAnimation.keys[index];
  20286. var data;
  20287. switch (dataType) {
  20288. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  20289. data = key.values[0];
  20290. break;
  20291. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  20292. data = BABYLON.Quaternion.FromArray(key.values);
  20293. break;
  20294. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  20295. data = BABYLON.Matrix.FromArray(key.values);
  20296. break;
  20297. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  20298. default:
  20299. data = BABYLON.Vector3.FromArray(key.values);
  20300. break;
  20301. }
  20302. keys.push({
  20303. frame: key.frame,
  20304. value: data
  20305. });
  20306. }
  20307. animation.setKeys(keys);
  20308. return animation;
  20309. };
  20310. var parseLight = function (parsedLight, scene) {
  20311. var light;
  20312. switch (parsedLight.type) {
  20313. case 0:
  20314. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  20315. break;
  20316. case 1:
  20317. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20318. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  20319. break;
  20320. case 2:
  20321. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  20322. break;
  20323. case 3:
  20324. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20325. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  20326. break;
  20327. }
  20328. light.id = parsedLight.id;
  20329. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  20330. if (parsedLight.intensity !== undefined) {
  20331. light.intensity = parsedLight.intensity;
  20332. }
  20333. if (parsedLight.range) {
  20334. light.range = parsedLight.range;
  20335. }
  20336. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  20337. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  20338. if (parsedLight.excludedMeshesIds) {
  20339. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20340. }
  20341. // Parent
  20342. if (parsedLight.parentId) {
  20343. light._waitingParentId = parsedLight.parentId;
  20344. }
  20345. if (parsedLight.includedOnlyMeshesIds) {
  20346. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20347. }
  20348. // Animations
  20349. if (parsedLight.animations) {
  20350. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20351. var parsedAnimation = parsedLight.animations[animationIndex];
  20352. light.animations.push(parseAnimation(parsedAnimation));
  20353. }
  20354. }
  20355. if (parsedLight.autoAnimate) {
  20356. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  20357. }
  20358. };
  20359. var parseCamera = function (parsedCamera, scene) {
  20360. var camera;
  20361. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20362. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20363. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20364. var alpha = parsedCamera.alpha;
  20365. var beta = parsedCamera.beta;
  20366. var radius = parsedCamera.radius;
  20367. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20368. var interaxial_distance = parsedCamera.interaxial_distance;
  20369. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  20370. }
  20371. else {
  20372. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20373. }
  20374. }
  20375. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20376. interaxial_distance = parsedCamera.interaxial_distance;
  20377. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  20378. }
  20379. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20380. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20381. }
  20382. else if (parsedCamera.type === "FollowCamera") {
  20383. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20384. camera.heightOffset = parsedCamera.heightOffset;
  20385. camera.radius = parsedCamera.radius;
  20386. camera.rotationOffset = parsedCamera.rotationOffset;
  20387. if (lockedTargetMesh)
  20388. camera.target = lockedTargetMesh;
  20389. }
  20390. else if (parsedCamera.type === "GamepadCamera") {
  20391. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20392. }
  20393. else if (parsedCamera.type === "TouchCamera") {
  20394. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20395. }
  20396. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20397. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20398. }
  20399. else if (parsedCamera.type === "WebVRFreeCamera") {
  20400. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  20401. }
  20402. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  20403. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  20404. }
  20405. else {
  20406. // Free Camera is the default value
  20407. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20408. }
  20409. // apply 3d rig, when found
  20410. if (parsedCamera.cameraRigMode) {
  20411. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20412. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20413. }
  20414. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20415. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20416. camera.lockedTarget = lockedTargetMesh;
  20417. }
  20418. camera.id = parsedCamera.id;
  20419. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20420. // Parent
  20421. if (parsedCamera.parentId) {
  20422. camera._waitingParentId = parsedCamera.parentId;
  20423. }
  20424. // Target
  20425. if (parsedCamera.target) {
  20426. if (camera.setTarget) {
  20427. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20428. }
  20429. else {
  20430. //For ArcRotate
  20431. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20432. }
  20433. }
  20434. else {
  20435. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20436. }
  20437. camera.fov = parsedCamera.fov;
  20438. camera.minZ = parsedCamera.minZ;
  20439. camera.maxZ = parsedCamera.maxZ;
  20440. camera.speed = parsedCamera.speed;
  20441. camera.inertia = parsedCamera.inertia;
  20442. camera.checkCollisions = parsedCamera.checkCollisions;
  20443. camera.applyGravity = parsedCamera.applyGravity;
  20444. if (parsedCamera.ellipsoid) {
  20445. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20446. }
  20447. // Animations
  20448. if (parsedCamera.animations) {
  20449. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20450. var parsedAnimation = parsedCamera.animations[animationIndex];
  20451. camera.animations.push(parseAnimation(parsedAnimation));
  20452. }
  20453. }
  20454. if (parsedCamera.autoAnimate) {
  20455. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20456. }
  20457. // Layer Mask
  20458. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20459. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20460. }
  20461. else {
  20462. camera.layerMask = 0x0FFFFFFF;
  20463. }
  20464. return camera;
  20465. };
  20466. var parseGeometry = function (parsedGeometry, scene) {
  20467. var id = parsedGeometry.id;
  20468. return scene.getGeometryByID(id);
  20469. };
  20470. var parseBox = function (parsedBox, scene) {
  20471. if (parseGeometry(parsedBox, scene)) {
  20472. return null; // null since geometry could be something else than a box...
  20473. }
  20474. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20475. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20476. scene.pushGeometry(box, true);
  20477. return box;
  20478. };
  20479. var parseSphere = function (parsedSphere, scene) {
  20480. if (parseGeometry(parsedSphere, scene)) {
  20481. return null; // null since geometry could be something else than a sphere...
  20482. }
  20483. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20484. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20485. scene.pushGeometry(sphere, true);
  20486. return sphere;
  20487. };
  20488. var parseCylinder = function (parsedCylinder, scene) {
  20489. if (parseGeometry(parsedCylinder, scene)) {
  20490. return null; // null since geometry could be something else than a cylinder...
  20491. }
  20492. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20493. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20494. scene.pushGeometry(cylinder, true);
  20495. return cylinder;
  20496. };
  20497. var parseTorus = function (parsedTorus, scene) {
  20498. if (parseGeometry(parsedTorus, scene)) {
  20499. return null; // null since geometry could be something else than a torus...
  20500. }
  20501. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20502. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20503. scene.pushGeometry(torus, true);
  20504. return torus;
  20505. };
  20506. var parseGround = function (parsedGround, scene) {
  20507. if (parseGeometry(parsedGround, scene)) {
  20508. return null; // null since geometry could be something else than a ground...
  20509. }
  20510. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20511. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20512. scene.pushGeometry(ground, true);
  20513. return ground;
  20514. };
  20515. var parsePlane = function (parsedPlane, scene) {
  20516. if (parseGeometry(parsedPlane, scene)) {
  20517. return null; // null since geometry could be something else than a plane...
  20518. }
  20519. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20520. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20521. scene.pushGeometry(plane, true);
  20522. return plane;
  20523. };
  20524. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20525. if (parseGeometry(parsedTorusKnot, scene)) {
  20526. return null; // null since geometry could be something else than a torusKnot...
  20527. }
  20528. 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);
  20529. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20530. scene.pushGeometry(torusKnot, true);
  20531. return torusKnot;
  20532. };
  20533. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20534. if (parseGeometry(parsedVertexData, scene)) {
  20535. return null; // null since geometry could be a primitive
  20536. }
  20537. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20538. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20539. if (parsedVertexData.delayLoadingFile) {
  20540. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20541. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20542. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20543. geometry._delayInfo = [];
  20544. if (parsedVertexData.hasUVs) {
  20545. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20546. }
  20547. if (parsedVertexData.hasUVs2) {
  20548. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20549. }
  20550. if (parsedVertexData.hasUVs3) {
  20551. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20552. }
  20553. if (parsedVertexData.hasUVs4) {
  20554. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20555. }
  20556. if (parsedVertexData.hasUVs5) {
  20557. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20558. }
  20559. if (parsedVertexData.hasUVs6) {
  20560. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20561. }
  20562. if (parsedVertexData.hasColors) {
  20563. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20564. }
  20565. if (parsedVertexData.hasMatricesIndices) {
  20566. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20567. }
  20568. if (parsedVertexData.hasMatricesWeights) {
  20569. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20570. }
  20571. geometry._delayLoadingFunction = importVertexData;
  20572. }
  20573. else {
  20574. importVertexData(parsedVertexData, geometry);
  20575. }
  20576. scene.pushGeometry(geometry, true);
  20577. return geometry;
  20578. };
  20579. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20580. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20581. mesh.id = parsedMesh.id;
  20582. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20583. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20584. if (parsedMesh.rotationQuaternion) {
  20585. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20586. }
  20587. else if (parsedMesh.rotation) {
  20588. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20589. }
  20590. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20591. if (parsedMesh.localMatrix) {
  20592. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20593. }
  20594. else if (parsedMesh.pivotMatrix) {
  20595. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20596. }
  20597. mesh.setEnabled(parsedMesh.isEnabled);
  20598. mesh.isVisible = parsedMesh.isVisible;
  20599. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20600. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20601. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20602. if (parsedMesh.applyFog !== undefined) {
  20603. mesh.applyFog = parsedMesh.applyFog;
  20604. }
  20605. if (parsedMesh.pickable !== undefined) {
  20606. mesh.isPickable = parsedMesh.pickable;
  20607. }
  20608. if (parsedMesh.alphaIndex !== undefined) {
  20609. mesh.alphaIndex = parsedMesh.alphaIndex;
  20610. }
  20611. mesh.receiveShadows = parsedMesh.receiveShadows;
  20612. mesh.billboardMode = parsedMesh.billboardMode;
  20613. if (parsedMesh.visibility !== undefined) {
  20614. mesh.visibility = parsedMesh.visibility;
  20615. }
  20616. mesh.checkCollisions = parsedMesh.checkCollisions;
  20617. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20618. // freezeWorldMatrix
  20619. if (parsedMesh.freezeWorldMatrix) {
  20620. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20621. }
  20622. // Parent
  20623. if (parsedMesh.parentId) {
  20624. mesh._waitingParentId = parsedMesh.parentId;
  20625. }
  20626. // Actions
  20627. if (parsedMesh.actions !== undefined) {
  20628. mesh._waitingActions = parsedMesh.actions;
  20629. }
  20630. // Geometry
  20631. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20632. if (parsedMesh.delayLoadingFile) {
  20633. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20634. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20635. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20636. if (parsedMesh._binaryInfo) {
  20637. mesh._binaryInfo = parsedMesh._binaryInfo;
  20638. }
  20639. mesh._delayInfo = [];
  20640. if (parsedMesh.hasUVs) {
  20641. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20642. }
  20643. if (parsedMesh.hasUVs2) {
  20644. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20645. }
  20646. if (parsedMesh.hasUVs3) {
  20647. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20648. }
  20649. if (parsedMesh.hasUVs4) {
  20650. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20651. }
  20652. if (parsedMesh.hasUVs5) {
  20653. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20654. }
  20655. if (parsedMesh.hasUVs6) {
  20656. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20657. }
  20658. if (parsedMesh.hasColors) {
  20659. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20660. }
  20661. if (parsedMesh.hasMatricesIndices) {
  20662. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20663. }
  20664. if (parsedMesh.hasMatricesWeights) {
  20665. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20666. }
  20667. mesh._delayLoadingFunction = importGeometry;
  20668. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20669. mesh._checkDelayState();
  20670. }
  20671. }
  20672. else {
  20673. importGeometry(parsedMesh, mesh);
  20674. }
  20675. // Material
  20676. if (parsedMesh.materialId) {
  20677. mesh.setMaterialByID(parsedMesh.materialId);
  20678. }
  20679. else {
  20680. mesh.material = null;
  20681. }
  20682. // Skeleton
  20683. if (parsedMesh.skeletonId > -1) {
  20684. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20685. }
  20686. // Physics
  20687. if (parsedMesh.physicsImpostor) {
  20688. if (!scene.isPhysicsEnabled()) {
  20689. scene.enablePhysics();
  20690. }
  20691. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20692. }
  20693. // Animations
  20694. if (parsedMesh.animations) {
  20695. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20696. var parsedAnimation = parsedMesh.animations[animationIndex];
  20697. mesh.animations.push(parseAnimation(parsedAnimation));
  20698. }
  20699. }
  20700. if (parsedMesh.autoAnimate) {
  20701. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20702. }
  20703. // Layer Mask
  20704. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20705. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20706. }
  20707. else {
  20708. mesh.layerMask = 0x0FFFFFFF;
  20709. }
  20710. // Instances
  20711. if (parsedMesh.instances) {
  20712. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20713. var parsedInstance = parsedMesh.instances[index];
  20714. var instance = mesh.createInstance(parsedInstance.name);
  20715. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20716. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20717. if (parsedInstance.rotationQuaternion) {
  20718. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20719. }
  20720. else if (parsedInstance.rotation) {
  20721. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20722. }
  20723. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20724. instance.checkCollisions = mesh.checkCollisions;
  20725. if (parsedMesh.animations) {
  20726. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20727. parsedAnimation = parsedMesh.animations[animationIndex];
  20728. instance.animations.push(parseAnimation(parsedAnimation));
  20729. }
  20730. }
  20731. }
  20732. }
  20733. return mesh;
  20734. };
  20735. var parseActions = function (parsedActions, object, scene) {
  20736. var actionManager = new BABYLON.ActionManager(scene);
  20737. if (object === null)
  20738. scene.actionManager = actionManager;
  20739. else
  20740. object.actionManager = actionManager;
  20741. // instanciate a new object
  20742. var instanciate = function (name, params) {
  20743. var newInstance = Object.create(BABYLON[name].prototype);
  20744. newInstance.constructor.apply(newInstance, params);
  20745. return newInstance;
  20746. };
  20747. var parseParameter = function (name, value, target, propertyPath) {
  20748. if (propertyPath === null) {
  20749. // String, boolean or float
  20750. var floatValue = parseFloat(value);
  20751. if (value === "true" || value === "false")
  20752. return value === "true";
  20753. else
  20754. return isNaN(floatValue) ? value : floatValue;
  20755. }
  20756. var effectiveTarget = propertyPath.split(".");
  20757. var values = value.split(",");
  20758. // Get effective Target
  20759. for (var i = 0; i < effectiveTarget.length; i++) {
  20760. target = target[effectiveTarget[i]];
  20761. }
  20762. // Return appropriate value with its type
  20763. if (typeof (target) === "boolean")
  20764. return values[0] === "true";
  20765. if (typeof (target) === "string")
  20766. return values[0];
  20767. // Parameters with multiple values such as Vector3 etc.
  20768. var split = new Array();
  20769. for (var i = 0; i < values.length; i++)
  20770. split.push(parseFloat(values[i]));
  20771. if (target instanceof BABYLON.Vector3)
  20772. return BABYLON.Vector3.FromArray(split);
  20773. if (target instanceof BABYLON.Vector4)
  20774. return BABYLON.Vector4.FromArray(split);
  20775. if (target instanceof BABYLON.Color3)
  20776. return BABYLON.Color3.FromArray(split);
  20777. if (target instanceof BABYLON.Color4)
  20778. return BABYLON.Color4.FromArray(split);
  20779. return parseFloat(values[0]);
  20780. };
  20781. // traverse graph per trigger
  20782. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20783. if (combineArray === void 0) { combineArray = null; }
  20784. if (parsedAction.detached)
  20785. return;
  20786. var parameters = new Array();
  20787. var target = null;
  20788. var propertyPath = null;
  20789. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20790. // Parameters
  20791. if (parsedAction.type === 2)
  20792. parameters.push(actionManager);
  20793. else
  20794. parameters.push(trigger);
  20795. if (combine) {
  20796. var actions = new Array();
  20797. for (var j = 0; j < parsedAction.combine.length; j++) {
  20798. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20799. }
  20800. parameters.push(actions);
  20801. }
  20802. else {
  20803. for (var i = 0; i < parsedAction.properties.length; i++) {
  20804. var value = parsedAction.properties[i].value;
  20805. var name = parsedAction.properties[i].name;
  20806. var targetType = parsedAction.properties[i].targetType;
  20807. if (name === "target")
  20808. if (targetType !== null && targetType === "SceneProperties")
  20809. value = target = scene;
  20810. else
  20811. value = target = scene.getNodeByName(value);
  20812. else if (name === "parent")
  20813. value = scene.getNodeByName(value);
  20814. else if (name === "sound")
  20815. value = scene.getSoundByName(value);
  20816. else if (name !== "propertyPath") {
  20817. if (parsedAction.type === 2 && name === "operator")
  20818. value = BABYLON.ValueCondition[value];
  20819. else
  20820. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20821. }
  20822. else {
  20823. propertyPath = value;
  20824. }
  20825. parameters.push(value);
  20826. }
  20827. }
  20828. if (combineArray === null) {
  20829. parameters.push(condition);
  20830. }
  20831. else {
  20832. parameters.push(null);
  20833. }
  20834. // If interpolate value action
  20835. if (parsedAction.name === "InterpolateValueAction") {
  20836. var param = parameters[parameters.length - 2];
  20837. parameters[parameters.length - 1] = param;
  20838. parameters[parameters.length - 2] = condition;
  20839. }
  20840. // Action or condition(s) and not CombineAction
  20841. var newAction = instanciate(parsedAction.name, parameters);
  20842. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20843. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20844. if (action)
  20845. action.then(nothing);
  20846. else
  20847. actionManager.registerAction(nothing);
  20848. action = nothing;
  20849. }
  20850. if (combineArray === null) {
  20851. if (newAction instanceof BABYLON.Condition) {
  20852. condition = newAction;
  20853. newAction = action;
  20854. }
  20855. else {
  20856. condition = null;
  20857. if (action)
  20858. action.then(newAction);
  20859. else
  20860. actionManager.registerAction(newAction);
  20861. }
  20862. }
  20863. else {
  20864. combineArray.push(newAction);
  20865. }
  20866. for (var i = 0; i < parsedAction.children.length; i++)
  20867. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20868. };
  20869. // triggers
  20870. for (var i = 0; i < parsedActions.children.length; i++) {
  20871. var triggerParams;
  20872. var trigger = parsedActions.children[i];
  20873. if (trigger.properties.length > 0) {
  20874. var param = trigger.properties[0].value;
  20875. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20876. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20877. }
  20878. else
  20879. triggerParams = BABYLON.ActionManager[trigger.name];
  20880. for (var j = 0; j < trigger.children.length; j++) {
  20881. if (!trigger.detached)
  20882. traverse(trigger.children[j], triggerParams, null, null);
  20883. }
  20884. }
  20885. };
  20886. var parseSound = function (parsedSound, scene, rootUrl) {
  20887. var soundName = parsedSound.name;
  20888. var soundUrl = rootUrl + soundName;
  20889. var options = {
  20890. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20891. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20892. rolloffFactor: parsedSound.rolloffFactor,
  20893. refDistance: parsedSound.refDistance,
  20894. distanceModel: parsedSound.distanceModel,
  20895. playbackRate: parsedSound.playbackRate
  20896. };
  20897. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20898. scene._addPendingData(newSound);
  20899. if (parsedSound.position) {
  20900. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20901. newSound.setPosition(soundPosition);
  20902. }
  20903. if (parsedSound.isDirectional) {
  20904. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20905. if (parsedSound.localDirectionToMesh) {
  20906. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20907. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20908. }
  20909. }
  20910. if (parsedSound.connectedMeshId) {
  20911. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20912. if (connectedMesh) {
  20913. newSound.attachToMesh(connectedMesh);
  20914. }
  20915. }
  20916. };
  20917. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20918. names = (names instanceof Array) ? names : [names];
  20919. for (var i in names) {
  20920. if (mesh.name === names[i]) {
  20921. hierarchyIds.push(mesh.id);
  20922. return true;
  20923. }
  20924. }
  20925. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20926. hierarchyIds.push(mesh.id);
  20927. return true;
  20928. }
  20929. return false;
  20930. };
  20931. var importVertexData = function (parsedVertexData, geometry) {
  20932. var vertexData = new BABYLON.VertexData();
  20933. // positions
  20934. var positions = parsedVertexData.positions;
  20935. if (positions) {
  20936. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20937. }
  20938. // normals
  20939. var normals = parsedVertexData.normals;
  20940. if (normals) {
  20941. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20942. }
  20943. // uvs
  20944. var uvs = parsedVertexData.uvs;
  20945. if (uvs) {
  20946. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20947. }
  20948. // uv2s
  20949. var uv2s = parsedVertexData.uv2s;
  20950. if (uv2s) {
  20951. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20952. }
  20953. // uv3s
  20954. var uv3s = parsedVertexData.uv3s;
  20955. if (uv3s) {
  20956. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20957. }
  20958. // uv4s
  20959. var uv4s = parsedVertexData.uv4s;
  20960. if (uv4s) {
  20961. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20962. }
  20963. // uv5s
  20964. var uv5s = parsedVertexData.uv5s;
  20965. if (uv5s) {
  20966. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20967. }
  20968. // uv6s
  20969. var uv6s = parsedVertexData.uv6s;
  20970. if (uv6s) {
  20971. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20972. }
  20973. // colors
  20974. var colors = parsedVertexData.colors;
  20975. if (colors) {
  20976. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20977. }
  20978. // matricesIndices
  20979. var matricesIndices = parsedVertexData.matricesIndices;
  20980. if (matricesIndices) {
  20981. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20982. }
  20983. // matricesWeights
  20984. var matricesWeights = parsedVertexData.matricesWeights;
  20985. if (matricesWeights) {
  20986. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20987. }
  20988. // indices
  20989. var indices = parsedVertexData.indices;
  20990. if (indices) {
  20991. vertexData.indices = indices;
  20992. }
  20993. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20994. };
  20995. var importGeometry = function (parsedGeometry, mesh) {
  20996. var scene = mesh.getScene();
  20997. // Geometry
  20998. var geometryId = parsedGeometry.geometryId;
  20999. if (geometryId) {
  21000. var geometry = scene.getGeometryByID(geometryId);
  21001. if (geometry) {
  21002. geometry.applyToMesh(mesh);
  21003. }
  21004. }
  21005. else if (parsedGeometry instanceof ArrayBuffer) {
  21006. var binaryInfo = mesh._binaryInfo;
  21007. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  21008. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  21009. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  21010. }
  21011. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  21012. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  21013. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  21014. }
  21015. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  21016. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  21017. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  21018. }
  21019. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  21020. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  21021. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  21022. }
  21023. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  21024. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  21025. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  21026. }
  21027. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  21028. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  21029. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  21030. }
  21031. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  21032. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  21033. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  21034. }
  21035. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  21036. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  21037. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  21038. }
  21039. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  21040. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  21041. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  21042. }
  21043. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  21044. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  21045. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  21046. }
  21047. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  21048. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  21049. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  21050. }
  21051. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  21052. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  21053. mesh.setIndices(indicesData);
  21054. }
  21055. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  21056. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  21057. mesh.subMeshes = [];
  21058. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  21059. var materialIndex = subMeshesData[(i * 5) + 0];
  21060. var verticesStart = subMeshesData[(i * 5) + 1];
  21061. var verticesCount = subMeshesData[(i * 5) + 2];
  21062. var indexStart = subMeshesData[(i * 5) + 3];
  21063. var indexCount = subMeshesData[(i * 5) + 4];
  21064. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  21065. }
  21066. }
  21067. }
  21068. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  21069. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  21070. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  21071. if (parsedGeometry.uvs) {
  21072. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  21073. }
  21074. if (parsedGeometry.uvs2) {
  21075. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  21076. }
  21077. if (parsedGeometry.uvs3) {
  21078. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  21079. }
  21080. if (parsedGeometry.uvs4) {
  21081. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  21082. }
  21083. if (parsedGeometry.uvs5) {
  21084. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  21085. }
  21086. if (parsedGeometry.uvs6) {
  21087. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  21088. }
  21089. if (parsedGeometry.colors) {
  21090. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  21091. }
  21092. if (parsedGeometry.matricesIndices) {
  21093. if (!parsedGeometry.matricesIndices._isExpanded) {
  21094. var floatIndices = [];
  21095. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  21096. var matricesIndex = parsedGeometry.matricesIndices[i];
  21097. floatIndices.push(matricesIndex & 0x000000FF);
  21098. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  21099. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  21100. floatIndices.push(matricesIndex >> 24);
  21101. }
  21102. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  21103. }
  21104. else {
  21105. delete parsedGeometry.matricesIndices._isExpanded;
  21106. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  21107. }
  21108. }
  21109. if (parsedGeometry.matricesWeights) {
  21110. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  21111. }
  21112. mesh.setIndices(parsedGeometry.indices);
  21113. }
  21114. // SubMeshes
  21115. if (parsedGeometry.subMeshes) {
  21116. mesh.subMeshes = [];
  21117. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  21118. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  21119. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  21120. }
  21121. }
  21122. // Flat shading
  21123. if (mesh._shouldGenerateFlatShading) {
  21124. mesh.convertToFlatShadedMesh();
  21125. delete mesh._shouldGenerateFlatShading;
  21126. }
  21127. // Update
  21128. mesh.computeWorldMatrix(true);
  21129. // Octree
  21130. if (scene._selectionOctree) {
  21131. scene._selectionOctree.addMesh(mesh);
  21132. }
  21133. };
  21134. BABYLON.SceneLoader.RegisterPlugin({
  21135. extensions: ".babylon",
  21136. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21137. var parsedData = JSON.parse(data);
  21138. var loadedSkeletonsIds = [];
  21139. var loadedMaterialsIds = [];
  21140. var hierarchyIds = [];
  21141. for (var index = 0; index < parsedData.meshes.length; index++) {
  21142. var parsedMesh = parsedData.meshes[index];
  21143. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21144. if (meshesNames instanceof Array) {
  21145. // Remove found mesh name from list.
  21146. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21147. }
  21148. //Geometry?
  21149. if (parsedMesh.geometryId) {
  21150. //does the file contain geometries?
  21151. if (parsedData.geometries) {
  21152. //find the correct geometry and add it to the scene
  21153. var found = false;
  21154. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21155. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21156. return;
  21157. }
  21158. else {
  21159. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21160. if (parsedGeometryData.id == parsedMesh.geometryId) {
  21161. switch (geometryType) {
  21162. case "boxes":
  21163. parseBox(parsedGeometryData, scene);
  21164. break;
  21165. case "spheres":
  21166. parseSphere(parsedGeometryData, scene);
  21167. break;
  21168. case "cylinders":
  21169. parseCylinder(parsedGeometryData, scene);
  21170. break;
  21171. case "toruses":
  21172. parseTorus(parsedGeometryData, scene);
  21173. break;
  21174. case "grounds":
  21175. parseGround(parsedGeometryData, scene);
  21176. break;
  21177. case "planes":
  21178. parsePlane(parsedGeometryData, scene);
  21179. break;
  21180. case "torusKnots":
  21181. parseTorusKnot(parsedGeometryData, scene);
  21182. break;
  21183. case "vertexData":
  21184. parseVertexData(parsedGeometryData, scene, rootUrl);
  21185. break;
  21186. }
  21187. found = true;
  21188. }
  21189. });
  21190. }
  21191. });
  21192. if (!found) {
  21193. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21194. }
  21195. }
  21196. }
  21197. // Material ?
  21198. if (parsedMesh.materialId) {
  21199. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21200. if (!materialFound && parsedData.multiMaterials) {
  21201. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  21202. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21203. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  21204. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21205. var subMatId = parsedMultiMaterial.materials[matIndex];
  21206. loadedMaterialsIds.push(subMatId);
  21207. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21208. }
  21209. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21210. parseMultiMaterial(parsedMultiMaterial, scene);
  21211. materialFound = true;
  21212. break;
  21213. }
  21214. }
  21215. }
  21216. if (!materialFound) {
  21217. loadedMaterialsIds.push(parsedMesh.materialId);
  21218. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21219. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21220. }
  21221. }
  21222. }
  21223. // Skeleton ?
  21224. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21225. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21226. if (!skeletonAlreadyLoaded) {
  21227. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  21228. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21229. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21230. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  21231. loadedSkeletonsIds.push(parsedSkeleton.id);
  21232. }
  21233. }
  21234. }
  21235. }
  21236. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  21237. meshes.push(mesh);
  21238. }
  21239. }
  21240. // Connecting parents
  21241. for (index = 0; index < scene.meshes.length; index++) {
  21242. var currentMesh = scene.meshes[index];
  21243. if (currentMesh._waitingParentId) {
  21244. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21245. currentMesh._waitingParentId = undefined;
  21246. }
  21247. }
  21248. // freeze world matrix application
  21249. for (index = 0; index < scene.meshes.length; index++) {
  21250. var currentMesh = scene.meshes[index];
  21251. if (currentMesh._waitingFreezeWorldMatrix) {
  21252. currentMesh.freezeWorldMatrix();
  21253. currentMesh._waitingFreezeWorldMatrix = undefined;
  21254. }
  21255. }
  21256. // Particles
  21257. if (parsedData.particleSystems) {
  21258. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21259. var parsedParticleSystem = parsedData.particleSystems[index];
  21260. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21261. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  21262. }
  21263. }
  21264. }
  21265. return true;
  21266. },
  21267. load: function (scene, data, rootUrl) {
  21268. var parsedData = JSON.parse(data);
  21269. // Scene
  21270. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21271. scene.autoClear = parsedData.autoClear;
  21272. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21273. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21274. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21275. // Fog
  21276. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21277. scene.fogMode = parsedData.fogMode;
  21278. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21279. scene.fogStart = parsedData.fogStart;
  21280. scene.fogEnd = parsedData.fogEnd;
  21281. scene.fogDensity = parsedData.fogDensity;
  21282. }
  21283. // Lights
  21284. for (var index = 0; index < parsedData.lights.length; index++) {
  21285. var parsedLight = parsedData.lights[index];
  21286. parseLight(parsedLight, scene);
  21287. }
  21288. // Materials
  21289. if (parsedData.materials) {
  21290. for (index = 0; index < parsedData.materials.length; index++) {
  21291. var parsedMaterial = parsedData.materials[index];
  21292. parseMaterial(parsedMaterial, scene, rootUrl);
  21293. }
  21294. }
  21295. if (parsedData.multiMaterials) {
  21296. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  21297. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21298. parseMultiMaterial(parsedMultiMaterial, scene);
  21299. }
  21300. }
  21301. // Skeletons
  21302. if (parsedData.skeletons) {
  21303. for (index = 0; index < parsedData.skeletons.length; index++) {
  21304. var parsedSkeleton = parsedData.skeletons[index];
  21305. parseSkeleton(parsedSkeleton, scene);
  21306. }
  21307. }
  21308. // Geometries
  21309. var geometries = parsedData.geometries;
  21310. if (geometries) {
  21311. // Boxes
  21312. var boxes = geometries.boxes;
  21313. if (boxes) {
  21314. for (index = 0; index < boxes.length; index++) {
  21315. var parsedBox = boxes[index];
  21316. parseBox(parsedBox, scene);
  21317. }
  21318. }
  21319. // Spheres
  21320. var spheres = geometries.spheres;
  21321. if (spheres) {
  21322. for (index = 0; index < spheres.length; index++) {
  21323. var parsedSphere = spheres[index];
  21324. parseSphere(parsedSphere, scene);
  21325. }
  21326. }
  21327. // Cylinders
  21328. var cylinders = geometries.cylinders;
  21329. if (cylinders) {
  21330. for (index = 0; index < cylinders.length; index++) {
  21331. var parsedCylinder = cylinders[index];
  21332. parseCylinder(parsedCylinder, scene);
  21333. }
  21334. }
  21335. // Toruses
  21336. var toruses = geometries.toruses;
  21337. if (toruses) {
  21338. for (index = 0; index < toruses.length; index++) {
  21339. var parsedTorus = toruses[index];
  21340. parseTorus(parsedTorus, scene);
  21341. }
  21342. }
  21343. // Grounds
  21344. var grounds = geometries.grounds;
  21345. if (grounds) {
  21346. for (index = 0; index < grounds.length; index++) {
  21347. var parsedGround = grounds[index];
  21348. parseGround(parsedGround, scene);
  21349. }
  21350. }
  21351. // Planes
  21352. var planes = geometries.planes;
  21353. if (planes) {
  21354. for (index = 0; index < planes.length; index++) {
  21355. var parsedPlane = planes[index];
  21356. parsePlane(parsedPlane, scene);
  21357. }
  21358. }
  21359. // TorusKnots
  21360. var torusKnots = geometries.torusKnots;
  21361. if (torusKnots) {
  21362. for (index = 0; index < torusKnots.length; index++) {
  21363. var parsedTorusKnot = torusKnots[index];
  21364. parseTorusKnot(parsedTorusKnot, scene);
  21365. }
  21366. }
  21367. // VertexData
  21368. var vertexData = geometries.vertexData;
  21369. if (vertexData) {
  21370. for (index = 0; index < vertexData.length; index++) {
  21371. var parsedVertexData = vertexData[index];
  21372. parseVertexData(parsedVertexData, scene, rootUrl);
  21373. }
  21374. }
  21375. }
  21376. // Meshes
  21377. for (index = 0; index < parsedData.meshes.length; index++) {
  21378. var parsedMesh = parsedData.meshes[index];
  21379. parseMesh(parsedMesh, scene, rootUrl);
  21380. }
  21381. // Cameras
  21382. for (index = 0; index < parsedData.cameras.length; index++) {
  21383. var parsedCamera = parsedData.cameras[index];
  21384. parseCamera(parsedCamera, scene);
  21385. }
  21386. if (parsedData.activeCameraID) {
  21387. scene.setActiveCameraByID(parsedData.activeCameraID);
  21388. }
  21389. // Browsing all the graph to connect the dots
  21390. for (index = 0; index < scene.cameras.length; index++) {
  21391. var camera = scene.cameras[index];
  21392. if (camera._waitingParentId) {
  21393. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21394. camera._waitingParentId = undefined;
  21395. }
  21396. }
  21397. for (index = 0; index < scene.lights.length; index++) {
  21398. var light = scene.lights[index];
  21399. if (light._waitingParentId) {
  21400. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21401. light._waitingParentId = undefined;
  21402. }
  21403. }
  21404. // Sounds
  21405. if (parsedData.sounds) {
  21406. for (index = 0; index < parsedData.sounds.length; index++) {
  21407. var parsedSound = parsedData.sounds[index];
  21408. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21409. parseSound(parsedSound, scene, rootUrl);
  21410. }
  21411. else {
  21412. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21413. }
  21414. }
  21415. }
  21416. // Connect parents & children and parse actions
  21417. for (index = 0; index < scene.meshes.length; index++) {
  21418. var mesh = scene.meshes[index];
  21419. if (mesh._waitingParentId) {
  21420. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21421. mesh._waitingParentId = undefined;
  21422. }
  21423. if (mesh._waitingActions) {
  21424. parseActions(mesh._waitingActions, mesh, scene);
  21425. mesh._waitingActions = undefined;
  21426. }
  21427. }
  21428. // freeze world matrix application
  21429. for (index = 0; index < scene.meshes.length; index++) {
  21430. var currentMesh = scene.meshes[index];
  21431. if (currentMesh._waitingFreezeWorldMatrix) {
  21432. currentMesh.freezeWorldMatrix();
  21433. currentMesh._waitingFreezeWorldMatrix = undefined;
  21434. }
  21435. }
  21436. // Particles Systems
  21437. if (parsedData.particleSystems) {
  21438. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21439. var parsedParticleSystem = parsedData.particleSystems[index];
  21440. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  21441. }
  21442. }
  21443. // Lens flares
  21444. if (parsedData.lensFlareSystems) {
  21445. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  21446. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21447. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  21448. }
  21449. }
  21450. // Shadows
  21451. if (parsedData.shadowGenerators) {
  21452. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  21453. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21454. parseShadowGenerator(parsedShadowGenerator, scene);
  21455. }
  21456. }
  21457. // Actions (scene)
  21458. if (parsedData.actions) {
  21459. parseActions(parsedData.actions, null, scene);
  21460. }
  21461. // Finish
  21462. return true;
  21463. }
  21464. });
  21465. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21466. })(BABYLON || (BABYLON = {}));
  21467. var BABYLON;
  21468. (function (BABYLON) {
  21469. var SpriteManager = (function () {
  21470. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21472. this.name = name;
  21473. this.cellSize = cellSize;
  21474. this.sprites = new Array();
  21475. this.renderingGroupId = 0;
  21476. this.layerMask = 0x0FFFFFFF;
  21477. this.fogEnabled = true;
  21478. this._vertexDeclaration = [4, 4, 4, 4];
  21479. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21480. this._capacity = capacity;
  21481. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21482. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21483. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21484. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21485. this._scene = scene;
  21486. this._scene.spriteManagers.push(this);
  21487. // VBO
  21488. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21489. var indices = [];
  21490. var index = 0;
  21491. for (var count = 0; count < capacity; count++) {
  21492. indices.push(index);
  21493. indices.push(index + 1);
  21494. indices.push(index + 2);
  21495. indices.push(index);
  21496. indices.push(index + 2);
  21497. indices.push(index + 3);
  21498. index += 4;
  21499. }
  21500. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21501. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21502. // Effects
  21503. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21504. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21505. }
  21506. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21507. var arrayOffset = index * 16;
  21508. if (offsetX === 0)
  21509. offsetX = this._epsilon;
  21510. else if (offsetX === 1)
  21511. offsetX = 1 - this._epsilon;
  21512. if (offsetY === 0)
  21513. offsetY = this._epsilon;
  21514. else if (offsetY === 1)
  21515. offsetY = 1 - this._epsilon;
  21516. this._vertices[arrayOffset] = sprite.position.x;
  21517. this._vertices[arrayOffset + 1] = sprite.position.y;
  21518. this._vertices[arrayOffset + 2] = sprite.position.z;
  21519. this._vertices[arrayOffset + 3] = sprite.angle;
  21520. this._vertices[arrayOffset + 4] = sprite.width;
  21521. this._vertices[arrayOffset + 5] = sprite.height;
  21522. this._vertices[arrayOffset + 6] = offsetX;
  21523. this._vertices[arrayOffset + 7] = offsetY;
  21524. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21525. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21526. var offset = (sprite.cellIndex / rowSize) >> 0;
  21527. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21528. this._vertices[arrayOffset + 11] = offset;
  21529. // Color
  21530. this._vertices[arrayOffset + 12] = sprite.color.r;
  21531. this._vertices[arrayOffset + 13] = sprite.color.g;
  21532. this._vertices[arrayOffset + 14] = sprite.color.b;
  21533. this._vertices[arrayOffset + 15] = sprite.color.a;
  21534. };
  21535. SpriteManager.prototype.render = function () {
  21536. // Check
  21537. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21538. return;
  21539. var engine = this._scene.getEngine();
  21540. var baseSize = this._spriteTexture.getBaseSize();
  21541. // Sprites
  21542. var deltaTime = engine.getDeltaTime();
  21543. var max = Math.min(this._capacity, this.sprites.length);
  21544. var rowSize = baseSize.width / this.cellSize;
  21545. var offset = 0;
  21546. for (var index = 0; index < max; index++) {
  21547. var sprite = this.sprites[index];
  21548. if (!sprite) {
  21549. continue;
  21550. }
  21551. sprite._animate(deltaTime);
  21552. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21553. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21554. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21555. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21556. }
  21557. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21558. // Render
  21559. var effect = this._effectBase;
  21560. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21561. effect = this._effectFog;
  21562. }
  21563. engine.enableEffect(effect);
  21564. var viewMatrix = this._scene.getViewMatrix();
  21565. effect.setTexture("diffuseSampler", this._spriteTexture);
  21566. effect.setMatrix("view", viewMatrix);
  21567. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21568. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21569. // Fog
  21570. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21571. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21572. effect.setColor3("vFogColor", this._scene.fogColor);
  21573. }
  21574. // VBOs
  21575. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21576. // Draw order
  21577. engine.setDepthFunctionToLessOrEqual();
  21578. effect.setBool("alphaTest", true);
  21579. engine.setColorWrite(false);
  21580. engine.draw(true, 0, max * 6);
  21581. engine.setColorWrite(true);
  21582. effect.setBool("alphaTest", false);
  21583. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21584. engine.draw(true, 0, max * 6);
  21585. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21586. };
  21587. SpriteManager.prototype.dispose = function () {
  21588. if (this._vertexBuffer) {
  21589. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21590. this._vertexBuffer = null;
  21591. }
  21592. if (this._indexBuffer) {
  21593. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21594. this._indexBuffer = null;
  21595. }
  21596. if (this._spriteTexture) {
  21597. this._spriteTexture.dispose();
  21598. this._spriteTexture = null;
  21599. }
  21600. // Remove from scene
  21601. var index = this._scene.spriteManagers.indexOf(this);
  21602. this._scene.spriteManagers.splice(index, 1);
  21603. // Callback
  21604. if (this.onDispose) {
  21605. this.onDispose();
  21606. }
  21607. };
  21608. return SpriteManager;
  21609. })();
  21610. BABYLON.SpriteManager = SpriteManager;
  21611. })(BABYLON || (BABYLON = {}));
  21612. var BABYLON;
  21613. (function (BABYLON) {
  21614. var Sprite = (function () {
  21615. function Sprite(name, manager) {
  21616. this.name = name;
  21617. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21618. this.width = 1.0;
  21619. this.height = 1.0;
  21620. this.angle = 0;
  21621. this.cellIndex = 0;
  21622. this.invertU = 0;
  21623. this.invertV = 0;
  21624. this.animations = new Array();
  21625. this._animationStarted = false;
  21626. this._loopAnimation = false;
  21627. this._fromIndex = 0;
  21628. this._toIndex = 0;
  21629. this._delay = 0;
  21630. this._direction = 1;
  21631. this._frameCount = 0;
  21632. this._time = 0;
  21633. this._manager = manager;
  21634. this._manager.sprites.push(this);
  21635. this.position = BABYLON.Vector3.Zero();
  21636. }
  21637. Object.defineProperty(Sprite.prototype, "size", {
  21638. get: function () {
  21639. return this.width;
  21640. },
  21641. set: function (value) {
  21642. this.width = value;
  21643. this.height = value;
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21649. this._fromIndex = from;
  21650. this._toIndex = to;
  21651. this._loopAnimation = loop;
  21652. this._delay = delay;
  21653. this._animationStarted = true;
  21654. this._direction = from < to ? 1 : -1;
  21655. this.cellIndex = from;
  21656. this._time = 0;
  21657. };
  21658. Sprite.prototype.stopAnimation = function () {
  21659. this._animationStarted = false;
  21660. };
  21661. Sprite.prototype._animate = function (deltaTime) {
  21662. if (!this._animationStarted)
  21663. return;
  21664. this._time += deltaTime;
  21665. if (this._time > this._delay) {
  21666. this._time = this._time % this._delay;
  21667. this.cellIndex += this._direction;
  21668. if (this.cellIndex == this._toIndex) {
  21669. if (this._loopAnimation) {
  21670. this.cellIndex = this._fromIndex;
  21671. }
  21672. else {
  21673. this._animationStarted = false;
  21674. if (this.disposeWhenFinishedAnimating) {
  21675. this.dispose();
  21676. }
  21677. }
  21678. }
  21679. }
  21680. };
  21681. Sprite.prototype.dispose = function () {
  21682. for (var i = 0; i < this._manager.sprites.length; i++) {
  21683. if (this._manager.sprites[i] == this) {
  21684. this._manager.sprites.splice(i, 1);
  21685. }
  21686. }
  21687. };
  21688. return Sprite;
  21689. })();
  21690. BABYLON.Sprite = Sprite;
  21691. })(BABYLON || (BABYLON = {}));
  21692. var BABYLON;
  21693. (function (BABYLON) {
  21694. var Layer = (function () {
  21695. function Layer(name, imgUrl, scene, isBackground, color) {
  21696. this.name = name;
  21697. this._vertexDeclaration = [2];
  21698. this._vertexStrideSize = 2 * 4;
  21699. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21700. this.isBackground = isBackground === undefined ? true : isBackground;
  21701. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21702. this._scene = scene;
  21703. this._scene.layers.push(this);
  21704. // VBO
  21705. var vertices = [];
  21706. vertices.push(1, 1);
  21707. vertices.push(-1, 1);
  21708. vertices.push(-1, -1);
  21709. vertices.push(1, -1);
  21710. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21711. // Indices
  21712. var indices = [];
  21713. indices.push(0);
  21714. indices.push(1);
  21715. indices.push(2);
  21716. indices.push(0);
  21717. indices.push(2);
  21718. indices.push(3);
  21719. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21720. // Effects
  21721. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21722. }
  21723. Layer.prototype.render = function () {
  21724. // Check
  21725. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21726. return;
  21727. var engine = this._scene.getEngine();
  21728. // Render
  21729. engine.enableEffect(this._effect);
  21730. engine.setState(false);
  21731. // Texture
  21732. this._effect.setTexture("textureSampler", this.texture);
  21733. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21734. // Color
  21735. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21736. // VBOs
  21737. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21738. // Draw order
  21739. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21740. engine.draw(true, 0, 6);
  21741. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21742. };
  21743. Layer.prototype.dispose = function () {
  21744. if (this._vertexBuffer) {
  21745. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21746. this._vertexBuffer = null;
  21747. }
  21748. if (this._indexBuffer) {
  21749. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21750. this._indexBuffer = null;
  21751. }
  21752. if (this.texture) {
  21753. this.texture.dispose();
  21754. this.texture = null;
  21755. }
  21756. // Remove from scene
  21757. var index = this._scene.layers.indexOf(this);
  21758. this._scene.layers.splice(index, 1);
  21759. // Callback
  21760. if (this.onDispose) {
  21761. this.onDispose();
  21762. }
  21763. };
  21764. return Layer;
  21765. })();
  21766. BABYLON.Layer = Layer;
  21767. })(BABYLON || (BABYLON = {}));
  21768. var BABYLON;
  21769. (function (BABYLON) {
  21770. var Particle = (function () {
  21771. function Particle() {
  21772. this.position = BABYLON.Vector3.Zero();
  21773. this.direction = BABYLON.Vector3.Zero();
  21774. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21775. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21776. this.lifeTime = 1.0;
  21777. this.age = 0;
  21778. this.size = 0;
  21779. this.angle = 0;
  21780. this.angularSpeed = 0;
  21781. }
  21782. Particle.prototype.copyTo = function (other) {
  21783. other.position.copyFrom(this.position);
  21784. other.direction.copyFrom(this.direction);
  21785. other.color.copyFrom(this.color);
  21786. other.colorStep.copyFrom(this.colorStep);
  21787. other.lifeTime = this.lifeTime;
  21788. other.age = this.age;
  21789. other.size = this.size;
  21790. other.angle = this.angle;
  21791. other.angularSpeed = this.angularSpeed;
  21792. };
  21793. return Particle;
  21794. })();
  21795. BABYLON.Particle = Particle;
  21796. })(BABYLON || (BABYLON = {}));
  21797. var BABYLON;
  21798. (function (BABYLON) {
  21799. var randomNumber = function (min, max) {
  21800. if (min === max) {
  21801. return (min);
  21802. }
  21803. var random = Math.random();
  21804. return ((random * (max - min)) + min);
  21805. };
  21806. var ParticleSystem = (function () {
  21807. function ParticleSystem(name, capacity, scene, customEffect) {
  21808. var _this = this;
  21809. this.name = name;
  21810. this.renderingGroupId = 0;
  21811. this.emitter = null;
  21812. this.emitRate = 10;
  21813. this.manualEmitCount = -1;
  21814. this.updateSpeed = 0.01;
  21815. this.targetStopDuration = 0;
  21816. this.disposeOnStop = false;
  21817. this.minEmitPower = 1;
  21818. this.maxEmitPower = 1;
  21819. this.minLifeTime = 1;
  21820. this.maxLifeTime = 1;
  21821. this.minSize = 1;
  21822. this.maxSize = 1;
  21823. this.minAngularSpeed = 0;
  21824. this.maxAngularSpeed = 0;
  21825. this.layerMask = 0x0FFFFFFF;
  21826. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21827. this.forceDepthWrite = false;
  21828. this.gravity = BABYLON.Vector3.Zero();
  21829. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21830. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21831. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21832. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21833. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21834. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21835. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21836. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21837. this.particles = new Array();
  21838. this._vertexDeclaration = [3, 4, 4];
  21839. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21840. this._stockParticles = new Array();
  21841. this._newPartsExcess = 0;
  21842. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21843. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21844. this._scaledDirection = BABYLON.Vector3.Zero();
  21845. this._scaledGravity = BABYLON.Vector3.Zero();
  21846. this._currentRenderId = -1;
  21847. this._started = false;
  21848. this._stopped = false;
  21849. this._actualFrame = 0;
  21850. this.id = name;
  21851. this._capacity = capacity;
  21852. this._scene = scene;
  21853. this._customEffect = customEffect;
  21854. scene.particleSystems.push(this);
  21855. // VBO
  21856. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21857. var indices = [];
  21858. var index = 0;
  21859. for (var count = 0; count < capacity; count++) {
  21860. indices.push(index);
  21861. indices.push(index + 1);
  21862. indices.push(index + 2);
  21863. indices.push(index);
  21864. indices.push(index + 2);
  21865. indices.push(index + 3);
  21866. index += 4;
  21867. }
  21868. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21869. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21870. // Default behaviors
  21871. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21872. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21873. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21874. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21875. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21876. };
  21877. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21878. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21879. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21880. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21881. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21882. };
  21883. this.updateFunction = function (particles) {
  21884. for (var index = 0; index < particles.length; index++) {
  21885. var particle = particles[index];
  21886. particle.age += _this._scaledUpdateSpeed;
  21887. if (particle.age >= particle.lifeTime) {
  21888. _this.recycleParticle(particle);
  21889. index--;
  21890. continue;
  21891. }
  21892. else {
  21893. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21894. particle.color.addInPlace(_this._scaledColorStep);
  21895. if (particle.color.a < 0)
  21896. particle.color.a = 0;
  21897. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21898. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21899. particle.position.addInPlace(_this._scaledDirection);
  21900. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21901. particle.direction.addInPlace(_this._scaledGravity);
  21902. }
  21903. }
  21904. };
  21905. }
  21906. ParticleSystem.prototype.recycleParticle = function (particle) {
  21907. var lastParticle = this.particles.pop();
  21908. if (lastParticle !== particle) {
  21909. lastParticle.copyTo(particle);
  21910. this._stockParticles.push(lastParticle);
  21911. }
  21912. };
  21913. ParticleSystem.prototype.getCapacity = function () {
  21914. return this._capacity;
  21915. };
  21916. ParticleSystem.prototype.isAlive = function () {
  21917. return this._alive;
  21918. };
  21919. ParticleSystem.prototype.isStarted = function () {
  21920. return this._started;
  21921. };
  21922. ParticleSystem.prototype.start = function () {
  21923. this._started = true;
  21924. this._stopped = false;
  21925. this._actualFrame = 0;
  21926. };
  21927. ParticleSystem.prototype.stop = function () {
  21928. this._stopped = true;
  21929. };
  21930. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21931. var offset = index * 11;
  21932. this._vertices[offset] = particle.position.x;
  21933. this._vertices[offset + 1] = particle.position.y;
  21934. this._vertices[offset + 2] = particle.position.z;
  21935. this._vertices[offset + 3] = particle.color.r;
  21936. this._vertices[offset + 4] = particle.color.g;
  21937. this._vertices[offset + 5] = particle.color.b;
  21938. this._vertices[offset + 6] = particle.color.a;
  21939. this._vertices[offset + 7] = particle.angle;
  21940. this._vertices[offset + 8] = particle.size;
  21941. this._vertices[offset + 9] = offsetX;
  21942. this._vertices[offset + 10] = offsetY;
  21943. };
  21944. ParticleSystem.prototype._update = function (newParticles) {
  21945. // Update current
  21946. this._alive = this.particles.length > 0;
  21947. this.updateFunction(this.particles);
  21948. // Add new ones
  21949. var worldMatrix;
  21950. if (this.emitter.position) {
  21951. worldMatrix = this.emitter.getWorldMatrix();
  21952. }
  21953. else {
  21954. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21955. }
  21956. for (var index = 0; index < newParticles; index++) {
  21957. if (this.particles.length === this._capacity) {
  21958. break;
  21959. }
  21960. if (this._stockParticles.length !== 0) {
  21961. var particle = this._stockParticles.pop();
  21962. particle.age = 0;
  21963. }
  21964. else {
  21965. particle = new BABYLON.Particle();
  21966. }
  21967. this.particles.push(particle);
  21968. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21969. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21970. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21971. particle.size = randomNumber(this.minSize, this.maxSize);
  21972. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21973. this.startPositionFunction(worldMatrix, particle.position);
  21974. var step = randomNumber(0, 1.0);
  21975. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21976. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21977. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21978. }
  21979. };
  21980. ParticleSystem.prototype._getEffect = function () {
  21981. if (this._customEffect) {
  21982. return this._customEffect;
  21983. }
  21984. ;
  21985. var defines = [];
  21986. if (this._scene.clipPlane) {
  21987. defines.push("#define CLIPPLANE");
  21988. }
  21989. // Effect
  21990. var join = defines.join("\n");
  21991. if (this._cachedDefines !== join) {
  21992. this._cachedDefines = join;
  21993. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21994. }
  21995. return this._effect;
  21996. };
  21997. ParticleSystem.prototype.animate = function () {
  21998. if (!this._started)
  21999. return;
  22000. var effect = this._getEffect();
  22001. // Check
  22002. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22003. return;
  22004. if (this._currentRenderId === this._scene.getRenderId()) {
  22005. return;
  22006. }
  22007. this._currentRenderId = this._scene.getRenderId();
  22008. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22009. // determine the number of particles we need to create
  22010. var emitCout;
  22011. if (this.manualEmitCount > -1) {
  22012. emitCout = this.manualEmitCount;
  22013. this.manualEmitCount = 0;
  22014. }
  22015. else {
  22016. emitCout = this.emitRate;
  22017. }
  22018. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  22019. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  22020. if (this._newPartsExcess > 1.0) {
  22021. newParticles += this._newPartsExcess >> 0;
  22022. this._newPartsExcess -= this._newPartsExcess >> 0;
  22023. }
  22024. this._alive = false;
  22025. if (!this._stopped) {
  22026. this._actualFrame += this._scaledUpdateSpeed;
  22027. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22028. this.stop();
  22029. }
  22030. else {
  22031. newParticles = 0;
  22032. }
  22033. this._update(newParticles);
  22034. // Stopped?
  22035. if (this._stopped) {
  22036. if (!this._alive) {
  22037. this._started = false;
  22038. if (this.disposeOnStop) {
  22039. this._scene._toBeDisposed.push(this);
  22040. }
  22041. }
  22042. }
  22043. // Update VBO
  22044. var offset = 0;
  22045. for (var index = 0; index < this.particles.length; index++) {
  22046. var particle = this.particles[index];
  22047. this._appendParticleVertex(offset++, particle, 0, 0);
  22048. this._appendParticleVertex(offset++, particle, 1, 0);
  22049. this._appendParticleVertex(offset++, particle, 1, 1);
  22050. this._appendParticleVertex(offset++, particle, 0, 1);
  22051. }
  22052. var engine = this._scene.getEngine();
  22053. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22054. };
  22055. ParticleSystem.prototype.render = function () {
  22056. var effect = this._getEffect();
  22057. // Check
  22058. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22059. return 0;
  22060. var engine = this._scene.getEngine();
  22061. // Render
  22062. engine.enableEffect(effect);
  22063. engine.setState(false);
  22064. var viewMatrix = this._scene.getViewMatrix();
  22065. effect.setTexture("diffuseSampler", this.particleTexture);
  22066. effect.setMatrix("view", viewMatrix);
  22067. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22068. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22069. if (this._scene.clipPlane) {
  22070. var clipPlane = this._scene.clipPlane;
  22071. var invView = viewMatrix.clone();
  22072. invView.invert();
  22073. effect.setMatrix("invView", invView);
  22074. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22075. }
  22076. // VBOs
  22077. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22078. // Draw order
  22079. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22080. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22081. }
  22082. else {
  22083. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22084. }
  22085. if (this.forceDepthWrite) {
  22086. engine.setDepthWrite(true);
  22087. }
  22088. engine.draw(true, 0, this.particles.length * 6);
  22089. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22090. return this.particles.length;
  22091. };
  22092. ParticleSystem.prototype.dispose = function () {
  22093. if (this._vertexBuffer) {
  22094. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22095. this._vertexBuffer = null;
  22096. }
  22097. if (this._indexBuffer) {
  22098. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22099. this._indexBuffer = null;
  22100. }
  22101. if (this.particleTexture) {
  22102. this.particleTexture.dispose();
  22103. this.particleTexture = null;
  22104. }
  22105. // Remove from scene
  22106. var index = this._scene.particleSystems.indexOf(this);
  22107. this._scene.particleSystems.splice(index, 1);
  22108. // Callback
  22109. if (this.onDispose) {
  22110. this.onDispose();
  22111. }
  22112. };
  22113. // Clone
  22114. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22115. var result = new ParticleSystem(name, this._capacity, this._scene);
  22116. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22117. if (newEmitter === undefined) {
  22118. newEmitter = this.emitter;
  22119. }
  22120. result.emitter = newEmitter;
  22121. if (this.particleTexture) {
  22122. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22123. }
  22124. result.start();
  22125. return result;
  22126. };
  22127. // Statics
  22128. ParticleSystem.BLENDMODE_ONEONE = 0;
  22129. ParticleSystem.BLENDMODE_STANDARD = 1;
  22130. return ParticleSystem;
  22131. })();
  22132. BABYLON.ParticleSystem = ParticleSystem;
  22133. })(BABYLON || (BABYLON = {}));
  22134. var BABYLON;
  22135. (function (BABYLON) {
  22136. var Animation = (function () {
  22137. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22138. this.name = name;
  22139. this.targetProperty = targetProperty;
  22140. this.framePerSecond = framePerSecond;
  22141. this.dataType = dataType;
  22142. this.loopMode = loopMode;
  22143. this._offsetsCache = {};
  22144. this._highLimitsCache = {};
  22145. this._stopped = false;
  22146. this.allowMatricesInterpolation = false;
  22147. this.targetPropertyPath = targetProperty.split(".");
  22148. this.dataType = dataType;
  22149. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22150. }
  22151. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22152. var dataType = undefined;
  22153. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22154. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22155. }
  22156. else if (from instanceof BABYLON.Quaternion) {
  22157. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22158. }
  22159. else if (from instanceof BABYLON.Vector3) {
  22160. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22161. }
  22162. else if (from instanceof BABYLON.Vector2) {
  22163. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22164. }
  22165. else if (from instanceof BABYLON.Color3) {
  22166. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22167. }
  22168. if (dataType == undefined) {
  22169. return null;
  22170. }
  22171. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22172. var keys = [];
  22173. keys.push({ frame: 0, value: from });
  22174. keys.push({ frame: totalFrame, value: to });
  22175. animation.setKeys(keys);
  22176. if (easingFunction !== undefined) {
  22177. animation.setEasingFunction(easingFunction);
  22178. }
  22179. mesh.animations.push(animation);
  22180. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22181. };
  22182. // Methods
  22183. Animation.prototype.reset = function () {
  22184. this._offsetsCache = {};
  22185. this._highLimitsCache = {};
  22186. this.currentFrame = 0;
  22187. };
  22188. Animation.prototype.isStopped = function () {
  22189. return this._stopped;
  22190. };
  22191. Animation.prototype.getKeys = function () {
  22192. return this._keys;
  22193. };
  22194. Animation.prototype.getEasingFunction = function () {
  22195. return this._easingFunction;
  22196. };
  22197. Animation.prototype.setEasingFunction = function (easingFunction) {
  22198. this._easingFunction = easingFunction;
  22199. };
  22200. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22201. return startValue + (endValue - startValue) * gradient;
  22202. };
  22203. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22204. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22205. };
  22206. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22207. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22208. };
  22209. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22210. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22211. };
  22212. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22213. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22214. };
  22215. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22216. var startScale = new BABYLON.Vector3(0, 0, 0);
  22217. var startRotation = new BABYLON.Quaternion();
  22218. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  22219. startValue.decompose(startScale, startRotation, startTranslation);
  22220. var endScale = new BABYLON.Vector3(0, 0, 0);
  22221. var endRotation = new BABYLON.Quaternion();
  22222. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  22223. endValue.decompose(endScale, endRotation, endTranslation);
  22224. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  22225. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  22226. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  22227. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  22228. return result;
  22229. };
  22230. Animation.prototype.clone = function () {
  22231. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22232. clone.setKeys(this._keys);
  22233. return clone;
  22234. };
  22235. Animation.prototype.setKeys = function (values) {
  22236. this._keys = values.slice(0);
  22237. this._offsetsCache = {};
  22238. this._highLimitsCache = {};
  22239. };
  22240. Animation.prototype._getKeyValue = function (value) {
  22241. if (typeof value === "function") {
  22242. return value();
  22243. }
  22244. return value;
  22245. };
  22246. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22247. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22248. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22249. }
  22250. this.currentFrame = currentFrame;
  22251. // Try to get a hash to find the right key
  22252. 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));
  22253. if (this._keys[startKey].frame >= currentFrame) {
  22254. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22255. startKey--;
  22256. }
  22257. }
  22258. for (var key = startKey; key < this._keys.length; key++) {
  22259. if (this._keys[key + 1].frame >= currentFrame) {
  22260. var startValue = this._getKeyValue(this._keys[key].value);
  22261. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22262. // gradient : percent of currentFrame between the frame inf and the frame sup
  22263. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22264. // check for easingFunction and correction of gradient
  22265. if (this._easingFunction != null) {
  22266. gradient = this._easingFunction.ease(gradient);
  22267. }
  22268. switch (this.dataType) {
  22269. // Float
  22270. case Animation.ANIMATIONTYPE_FLOAT:
  22271. switch (loopMode) {
  22272. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22273. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22274. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22275. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22276. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22277. }
  22278. break;
  22279. // Quaternion
  22280. case Animation.ANIMATIONTYPE_QUATERNION:
  22281. var quaternion = null;
  22282. switch (loopMode) {
  22283. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22284. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22285. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22286. break;
  22287. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22288. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22289. break;
  22290. }
  22291. return quaternion;
  22292. // Vector3
  22293. case Animation.ANIMATIONTYPE_VECTOR3:
  22294. switch (loopMode) {
  22295. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22296. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22297. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22298. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22299. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22300. }
  22301. // Vector2
  22302. case Animation.ANIMATIONTYPE_VECTOR2:
  22303. switch (loopMode) {
  22304. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22305. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22306. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22307. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22308. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22309. }
  22310. // Color3
  22311. case Animation.ANIMATIONTYPE_COLOR3:
  22312. switch (loopMode) {
  22313. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22314. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22315. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22316. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22317. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22318. }
  22319. // Matrix
  22320. case Animation.ANIMATIONTYPE_MATRIX:
  22321. switch (loopMode) {
  22322. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22323. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22324. if (this.allowMatricesInterpolation) {
  22325. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22326. }
  22327. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22328. return startValue;
  22329. }
  22330. default:
  22331. break;
  22332. }
  22333. break;
  22334. }
  22335. }
  22336. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22337. };
  22338. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22339. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22340. this._stopped = true;
  22341. return false;
  22342. }
  22343. var returnValue = true;
  22344. // Adding a start key at frame 0 if missing
  22345. if (this._keys[0].frame !== 0) {
  22346. var newKey = { frame: 0, value: this._keys[0].value };
  22347. this._keys.splice(0, 0, newKey);
  22348. }
  22349. // Check limits
  22350. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22351. from = this._keys[0].frame;
  22352. }
  22353. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22354. to = this._keys[this._keys.length - 1].frame;
  22355. }
  22356. // Compute ratio
  22357. var range = to - from;
  22358. var offsetValue;
  22359. // ratio represents the frame delta between from and to
  22360. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22361. var highLimitValue = 0;
  22362. if (ratio > range && !loop) {
  22363. returnValue = false;
  22364. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22365. }
  22366. else {
  22367. // Get max value if required
  22368. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22369. var keyOffset = to.toString() + from.toString();
  22370. if (!this._offsetsCache[keyOffset]) {
  22371. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22372. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22373. switch (this.dataType) {
  22374. // Float
  22375. case Animation.ANIMATIONTYPE_FLOAT:
  22376. this._offsetsCache[keyOffset] = toValue - fromValue;
  22377. break;
  22378. // Quaternion
  22379. case Animation.ANIMATIONTYPE_QUATERNION:
  22380. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22381. break;
  22382. // Vector3
  22383. case Animation.ANIMATIONTYPE_VECTOR3:
  22384. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22385. // Vector2
  22386. case Animation.ANIMATIONTYPE_VECTOR2:
  22387. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22388. // Color3
  22389. case Animation.ANIMATIONTYPE_COLOR3:
  22390. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22391. default:
  22392. break;
  22393. }
  22394. this._highLimitsCache[keyOffset] = toValue;
  22395. }
  22396. highLimitValue = this._highLimitsCache[keyOffset];
  22397. offsetValue = this._offsetsCache[keyOffset];
  22398. }
  22399. }
  22400. if (offsetValue === undefined) {
  22401. switch (this.dataType) {
  22402. // Float
  22403. case Animation.ANIMATIONTYPE_FLOAT:
  22404. offsetValue = 0;
  22405. break;
  22406. // Quaternion
  22407. case Animation.ANIMATIONTYPE_QUATERNION:
  22408. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22409. break;
  22410. // Vector3
  22411. case Animation.ANIMATIONTYPE_VECTOR3:
  22412. offsetValue = BABYLON.Vector3.Zero();
  22413. break;
  22414. // Vector2
  22415. case Animation.ANIMATIONTYPE_VECTOR2:
  22416. offsetValue = BABYLON.Vector2.Zero();
  22417. break;
  22418. // Color3
  22419. case Animation.ANIMATIONTYPE_COLOR3:
  22420. offsetValue = BABYLON.Color3.Black();
  22421. }
  22422. }
  22423. // Compute value
  22424. var repeatCount = (ratio / range) >> 0;
  22425. var currentFrame = returnValue ? from + ratio % range : to;
  22426. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22427. // Set value
  22428. if (this.targetPropertyPath.length > 1) {
  22429. var property = this._target[this.targetPropertyPath[0]];
  22430. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22431. property = property[this.targetPropertyPath[index]];
  22432. }
  22433. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22434. }
  22435. else {
  22436. this._target[this.targetPropertyPath[0]] = currentValue;
  22437. }
  22438. if (this._target.markAsDirty) {
  22439. this._target.markAsDirty(this.targetProperty);
  22440. }
  22441. if (!returnValue) {
  22442. this._stopped = true;
  22443. }
  22444. return returnValue;
  22445. };
  22446. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22447. get: function () {
  22448. return Animation._ANIMATIONTYPE_FLOAT;
  22449. },
  22450. enumerable: true,
  22451. configurable: true
  22452. });
  22453. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22454. get: function () {
  22455. return Animation._ANIMATIONTYPE_VECTOR3;
  22456. },
  22457. enumerable: true,
  22458. configurable: true
  22459. });
  22460. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22461. get: function () {
  22462. return Animation._ANIMATIONTYPE_VECTOR2;
  22463. },
  22464. enumerable: true,
  22465. configurable: true
  22466. });
  22467. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22468. get: function () {
  22469. return Animation._ANIMATIONTYPE_QUATERNION;
  22470. },
  22471. enumerable: true,
  22472. configurable: true
  22473. });
  22474. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22475. get: function () {
  22476. return Animation._ANIMATIONTYPE_MATRIX;
  22477. },
  22478. enumerable: true,
  22479. configurable: true
  22480. });
  22481. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22482. get: function () {
  22483. return Animation._ANIMATIONTYPE_COLOR3;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22489. get: function () {
  22490. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22496. get: function () {
  22497. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22498. },
  22499. enumerable: true,
  22500. configurable: true
  22501. });
  22502. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22503. get: function () {
  22504. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. // Statics
  22510. Animation._ANIMATIONTYPE_FLOAT = 0;
  22511. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22512. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22513. Animation._ANIMATIONTYPE_MATRIX = 3;
  22514. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22515. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22516. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22517. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22518. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22519. return Animation;
  22520. })();
  22521. BABYLON.Animation = Animation;
  22522. })(BABYLON || (BABYLON = {}));
  22523. var BABYLON;
  22524. (function (BABYLON) {
  22525. var Animatable = (function () {
  22526. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22527. if (fromFrame === void 0) { fromFrame = 0; }
  22528. if (toFrame === void 0) { toFrame = 100; }
  22529. if (loopAnimation === void 0) { loopAnimation = false; }
  22530. if (speedRatio === void 0) { speedRatio = 1.0; }
  22531. this.target = target;
  22532. this.fromFrame = fromFrame;
  22533. this.toFrame = toFrame;
  22534. this.loopAnimation = loopAnimation;
  22535. this.speedRatio = speedRatio;
  22536. this.onAnimationEnd = onAnimationEnd;
  22537. this._animations = new Array();
  22538. this._paused = false;
  22539. this.animationStarted = false;
  22540. if (animations) {
  22541. this.appendAnimations(target, animations);
  22542. }
  22543. this._scene = scene;
  22544. scene._activeAnimatables.push(this);
  22545. }
  22546. // Methods
  22547. Animatable.prototype.appendAnimations = function (target, animations) {
  22548. for (var index = 0; index < animations.length; index++) {
  22549. var animation = animations[index];
  22550. animation._target = target;
  22551. this._animations.push(animation);
  22552. }
  22553. };
  22554. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22555. var animations = this._animations;
  22556. for (var index = 0; index < animations.length; index++) {
  22557. if (animations[index].targetProperty === property) {
  22558. return animations[index];
  22559. }
  22560. }
  22561. return null;
  22562. };
  22563. Animatable.prototype.reset = function () {
  22564. var animations = this._animations;
  22565. for (var index = 0; index < animations.length; index++) {
  22566. animations[index].reset();
  22567. }
  22568. this._localDelayOffset = null;
  22569. this._pausedDelay = null;
  22570. };
  22571. Animatable.prototype.pause = function () {
  22572. if (this._paused) {
  22573. return;
  22574. }
  22575. this._paused = true;
  22576. };
  22577. Animatable.prototype.restart = function () {
  22578. this._paused = false;
  22579. };
  22580. Animatable.prototype.stop = function () {
  22581. var index = this._scene._activeAnimatables.indexOf(this);
  22582. if (index > -1) {
  22583. this._scene._activeAnimatables.splice(index, 1);
  22584. }
  22585. if (this.onAnimationEnd) {
  22586. this.onAnimationEnd();
  22587. }
  22588. };
  22589. Animatable.prototype._animate = function (delay) {
  22590. if (this._paused) {
  22591. if (!this._pausedDelay) {
  22592. this._pausedDelay = delay;
  22593. }
  22594. return true;
  22595. }
  22596. if (!this._localDelayOffset) {
  22597. this._localDelayOffset = delay;
  22598. }
  22599. else if (this._pausedDelay) {
  22600. this._localDelayOffset += delay - this._pausedDelay;
  22601. this._pausedDelay = null;
  22602. }
  22603. // Animating
  22604. var running = false;
  22605. var animations = this._animations;
  22606. for (var index = 0; index < animations.length; index++) {
  22607. var animation = animations[index];
  22608. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22609. running = running || isRunning;
  22610. }
  22611. if (!running) {
  22612. // Remove from active animatables
  22613. index = this._scene._activeAnimatables.indexOf(this);
  22614. this._scene._activeAnimatables.splice(index, 1);
  22615. }
  22616. if (!running && this.onAnimationEnd) {
  22617. this.onAnimationEnd();
  22618. }
  22619. return running;
  22620. };
  22621. return Animatable;
  22622. })();
  22623. BABYLON.Animatable = Animatable;
  22624. })(BABYLON || (BABYLON = {}));
  22625. var BABYLON;
  22626. (function (BABYLON) {
  22627. var EasingFunction = (function () {
  22628. function EasingFunction() {
  22629. // Properties
  22630. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22631. }
  22632. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22633. get: function () {
  22634. return EasingFunction._EASINGMODE_EASEIN;
  22635. },
  22636. enumerable: true,
  22637. configurable: true
  22638. });
  22639. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22640. get: function () {
  22641. return EasingFunction._EASINGMODE_EASEOUT;
  22642. },
  22643. enumerable: true,
  22644. configurable: true
  22645. });
  22646. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22647. get: function () {
  22648. return EasingFunction._EASINGMODE_EASEINOUT;
  22649. },
  22650. enumerable: true,
  22651. configurable: true
  22652. });
  22653. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22654. var n = Math.min(Math.max(easingMode, 0), 2);
  22655. this._easingMode = n;
  22656. };
  22657. EasingFunction.prototype.getEasingMode = function () {
  22658. return this._easingMode;
  22659. };
  22660. EasingFunction.prototype.easeInCore = function (gradient) {
  22661. throw new Error('You must implement this method');
  22662. };
  22663. EasingFunction.prototype.ease = function (gradient) {
  22664. switch (this._easingMode) {
  22665. case EasingFunction.EASINGMODE_EASEIN:
  22666. return this.easeInCore(gradient);
  22667. case EasingFunction.EASINGMODE_EASEOUT:
  22668. return (1 - this.easeInCore(1 - gradient));
  22669. }
  22670. if (gradient >= 0.5) {
  22671. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22672. }
  22673. return (this.easeInCore(gradient * 2) * 0.5);
  22674. };
  22675. //Statics
  22676. EasingFunction._EASINGMODE_EASEIN = 0;
  22677. EasingFunction._EASINGMODE_EASEOUT = 1;
  22678. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22679. return EasingFunction;
  22680. })();
  22681. BABYLON.EasingFunction = EasingFunction;
  22682. var CircleEase = (function (_super) {
  22683. __extends(CircleEase, _super);
  22684. function CircleEase() {
  22685. _super.apply(this, arguments);
  22686. }
  22687. CircleEase.prototype.easeInCore = function (gradient) {
  22688. gradient = Math.max(0, Math.min(1, gradient));
  22689. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22690. };
  22691. return CircleEase;
  22692. })(EasingFunction);
  22693. BABYLON.CircleEase = CircleEase;
  22694. var BackEase = (function (_super) {
  22695. __extends(BackEase, _super);
  22696. function BackEase(amplitude) {
  22697. if (amplitude === void 0) { amplitude = 1; }
  22698. _super.call(this);
  22699. this.amplitude = amplitude;
  22700. }
  22701. BackEase.prototype.easeInCore = function (gradient) {
  22702. var num = Math.max(0, this.amplitude);
  22703. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22704. };
  22705. return BackEase;
  22706. })(EasingFunction);
  22707. BABYLON.BackEase = BackEase;
  22708. var BounceEase = (function (_super) {
  22709. __extends(BounceEase, _super);
  22710. function BounceEase(bounces, bounciness) {
  22711. if (bounces === void 0) { bounces = 3; }
  22712. if (bounciness === void 0) { bounciness = 2; }
  22713. _super.call(this);
  22714. this.bounces = bounces;
  22715. this.bounciness = bounciness;
  22716. }
  22717. BounceEase.prototype.easeInCore = function (gradient) {
  22718. var y = Math.max(0.0, this.bounces);
  22719. var bounciness = this.bounciness;
  22720. if (bounciness <= 1.0) {
  22721. bounciness = 1.001;
  22722. }
  22723. var num9 = Math.pow(bounciness, y);
  22724. var num5 = 1.0 - bounciness;
  22725. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22726. var num15 = gradient * num4;
  22727. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22728. var num3 = Math.floor(num65);
  22729. var num13 = num3 + 1.0;
  22730. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22731. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22732. var num7 = (num8 + num12) * 0.5;
  22733. var num6 = gradient - num7;
  22734. var num2 = num7 - num8;
  22735. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22736. };
  22737. return BounceEase;
  22738. })(EasingFunction);
  22739. BABYLON.BounceEase = BounceEase;
  22740. var CubicEase = (function (_super) {
  22741. __extends(CubicEase, _super);
  22742. function CubicEase() {
  22743. _super.apply(this, arguments);
  22744. }
  22745. CubicEase.prototype.easeInCore = function (gradient) {
  22746. return (gradient * gradient * gradient);
  22747. };
  22748. return CubicEase;
  22749. })(EasingFunction);
  22750. BABYLON.CubicEase = CubicEase;
  22751. var ElasticEase = (function (_super) {
  22752. __extends(ElasticEase, _super);
  22753. function ElasticEase(oscillations, springiness) {
  22754. if (oscillations === void 0) { oscillations = 3; }
  22755. if (springiness === void 0) { springiness = 3; }
  22756. _super.call(this);
  22757. this.oscillations = oscillations;
  22758. this.springiness = springiness;
  22759. }
  22760. ElasticEase.prototype.easeInCore = function (gradient) {
  22761. var num2;
  22762. var num3 = Math.max(0.0, this.oscillations);
  22763. var num = Math.max(0.0, this.springiness);
  22764. if (num == 0) {
  22765. num2 = gradient;
  22766. }
  22767. else {
  22768. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22769. }
  22770. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22771. };
  22772. return ElasticEase;
  22773. })(EasingFunction);
  22774. BABYLON.ElasticEase = ElasticEase;
  22775. var ExponentialEase = (function (_super) {
  22776. __extends(ExponentialEase, _super);
  22777. function ExponentialEase(exponent) {
  22778. if (exponent === void 0) { exponent = 2; }
  22779. _super.call(this);
  22780. this.exponent = exponent;
  22781. }
  22782. ExponentialEase.prototype.easeInCore = function (gradient) {
  22783. if (this.exponent <= 0) {
  22784. return gradient;
  22785. }
  22786. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22787. };
  22788. return ExponentialEase;
  22789. })(EasingFunction);
  22790. BABYLON.ExponentialEase = ExponentialEase;
  22791. var PowerEase = (function (_super) {
  22792. __extends(PowerEase, _super);
  22793. function PowerEase(power) {
  22794. if (power === void 0) { power = 2; }
  22795. _super.call(this);
  22796. this.power = power;
  22797. }
  22798. PowerEase.prototype.easeInCore = function (gradient) {
  22799. var y = Math.max(0.0, this.power);
  22800. return Math.pow(gradient, y);
  22801. };
  22802. return PowerEase;
  22803. })(EasingFunction);
  22804. BABYLON.PowerEase = PowerEase;
  22805. var QuadraticEase = (function (_super) {
  22806. __extends(QuadraticEase, _super);
  22807. function QuadraticEase() {
  22808. _super.apply(this, arguments);
  22809. }
  22810. QuadraticEase.prototype.easeInCore = function (gradient) {
  22811. return (gradient * gradient);
  22812. };
  22813. return QuadraticEase;
  22814. })(EasingFunction);
  22815. BABYLON.QuadraticEase = QuadraticEase;
  22816. var QuarticEase = (function (_super) {
  22817. __extends(QuarticEase, _super);
  22818. function QuarticEase() {
  22819. _super.apply(this, arguments);
  22820. }
  22821. QuarticEase.prototype.easeInCore = function (gradient) {
  22822. return (gradient * gradient * gradient * gradient);
  22823. };
  22824. return QuarticEase;
  22825. })(EasingFunction);
  22826. BABYLON.QuarticEase = QuarticEase;
  22827. var QuinticEase = (function (_super) {
  22828. __extends(QuinticEase, _super);
  22829. function QuinticEase() {
  22830. _super.apply(this, arguments);
  22831. }
  22832. QuinticEase.prototype.easeInCore = function (gradient) {
  22833. return (gradient * gradient * gradient * gradient * gradient);
  22834. };
  22835. return QuinticEase;
  22836. })(EasingFunction);
  22837. BABYLON.QuinticEase = QuinticEase;
  22838. var SineEase = (function (_super) {
  22839. __extends(SineEase, _super);
  22840. function SineEase() {
  22841. _super.apply(this, arguments);
  22842. }
  22843. SineEase.prototype.easeInCore = function (gradient) {
  22844. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22845. };
  22846. return SineEase;
  22847. })(EasingFunction);
  22848. BABYLON.SineEase = SineEase;
  22849. var BezierCurveEase = (function (_super) {
  22850. __extends(BezierCurveEase, _super);
  22851. function BezierCurveEase(x1, y1, x2, y2) {
  22852. if (x1 === void 0) { x1 = 0; }
  22853. if (y1 === void 0) { y1 = 0; }
  22854. if (x2 === void 0) { x2 = 1; }
  22855. if (y2 === void 0) { y2 = 1; }
  22856. _super.call(this);
  22857. this.x1 = x1;
  22858. this.y1 = y1;
  22859. this.x2 = x2;
  22860. this.y2 = y2;
  22861. }
  22862. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22863. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22864. };
  22865. return BezierCurveEase;
  22866. })(EasingFunction);
  22867. BABYLON.BezierCurveEase = BezierCurveEase;
  22868. })(BABYLON || (BABYLON = {}));
  22869. var BABYLON;
  22870. (function (BABYLON) {
  22871. var Octree = (function () {
  22872. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22873. if (maxDepth === void 0) { maxDepth = 2; }
  22874. this.maxDepth = maxDepth;
  22875. this.dynamicContent = new Array();
  22876. this._maxBlockCapacity = maxBlockCapacity || 64;
  22877. this._selectionContent = new BABYLON.SmartArray(1024);
  22878. this._creationFunc = creationFunc;
  22879. }
  22880. // Methods
  22881. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22882. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22883. };
  22884. Octree.prototype.addMesh = function (entry) {
  22885. for (var index = 0; index < this.blocks.length; index++) {
  22886. var block = this.blocks[index];
  22887. block.addEntry(entry);
  22888. }
  22889. };
  22890. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22891. this._selectionContent.reset();
  22892. for (var index = 0; index < this.blocks.length; index++) {
  22893. var block = this.blocks[index];
  22894. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22895. }
  22896. if (allowDuplicate) {
  22897. this._selectionContent.concat(this.dynamicContent);
  22898. }
  22899. else {
  22900. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22901. }
  22902. return this._selectionContent;
  22903. };
  22904. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22905. this._selectionContent.reset();
  22906. for (var index = 0; index < this.blocks.length; index++) {
  22907. var block = this.blocks[index];
  22908. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22909. }
  22910. if (allowDuplicate) {
  22911. this._selectionContent.concat(this.dynamicContent);
  22912. }
  22913. else {
  22914. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22915. }
  22916. return this._selectionContent;
  22917. };
  22918. Octree.prototype.intersectsRay = function (ray) {
  22919. this._selectionContent.reset();
  22920. for (var index = 0; index < this.blocks.length; index++) {
  22921. var block = this.blocks[index];
  22922. block.intersectsRay(ray, this._selectionContent);
  22923. }
  22924. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22925. return this._selectionContent;
  22926. };
  22927. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22928. target.blocks = new Array();
  22929. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22930. // Segmenting space
  22931. for (var x = 0; x < 2; x++) {
  22932. for (var y = 0; y < 2; y++) {
  22933. for (var z = 0; z < 2; z++) {
  22934. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22935. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22936. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22937. block.addEntries(entries);
  22938. target.blocks.push(block);
  22939. }
  22940. }
  22941. }
  22942. };
  22943. Octree.CreationFuncForMeshes = function (entry, block) {
  22944. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22945. block.entries.push(entry);
  22946. }
  22947. };
  22948. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22949. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22950. block.entries.push(entry);
  22951. }
  22952. };
  22953. return Octree;
  22954. })();
  22955. BABYLON.Octree = Octree;
  22956. })(BABYLON || (BABYLON = {}));
  22957. var BABYLON;
  22958. (function (BABYLON) {
  22959. var OctreeBlock = (function () {
  22960. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22961. this.entries = new Array();
  22962. this._boundingVectors = new Array();
  22963. this._capacity = capacity;
  22964. this._depth = depth;
  22965. this._maxDepth = maxDepth;
  22966. this._creationFunc = creationFunc;
  22967. this._minPoint = minPoint;
  22968. this._maxPoint = maxPoint;
  22969. this._boundingVectors.push(minPoint.clone());
  22970. this._boundingVectors.push(maxPoint.clone());
  22971. this._boundingVectors.push(minPoint.clone());
  22972. this._boundingVectors[2].x = maxPoint.x;
  22973. this._boundingVectors.push(minPoint.clone());
  22974. this._boundingVectors[3].y = maxPoint.y;
  22975. this._boundingVectors.push(minPoint.clone());
  22976. this._boundingVectors[4].z = maxPoint.z;
  22977. this._boundingVectors.push(maxPoint.clone());
  22978. this._boundingVectors[5].z = minPoint.z;
  22979. this._boundingVectors.push(maxPoint.clone());
  22980. this._boundingVectors[6].x = minPoint.x;
  22981. this._boundingVectors.push(maxPoint.clone());
  22982. this._boundingVectors[7].y = minPoint.y;
  22983. }
  22984. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22985. // Property
  22986. get: function () {
  22987. return this._capacity;
  22988. },
  22989. enumerable: true,
  22990. configurable: true
  22991. });
  22992. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22993. get: function () {
  22994. return this._minPoint;
  22995. },
  22996. enumerable: true,
  22997. configurable: true
  22998. });
  22999. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  23000. get: function () {
  23001. return this._maxPoint;
  23002. },
  23003. enumerable: true,
  23004. configurable: true
  23005. });
  23006. // Methods
  23007. OctreeBlock.prototype.addEntry = function (entry) {
  23008. if (this.blocks) {
  23009. for (var index = 0; index < this.blocks.length; index++) {
  23010. var block = this.blocks[index];
  23011. block.addEntry(entry);
  23012. }
  23013. return;
  23014. }
  23015. this._creationFunc(entry, this);
  23016. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  23017. this.createInnerBlocks();
  23018. }
  23019. };
  23020. OctreeBlock.prototype.addEntries = function (entries) {
  23021. for (var index = 0; index < entries.length; index++) {
  23022. var mesh = entries[index];
  23023. this.addEntry(mesh);
  23024. }
  23025. };
  23026. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  23027. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  23028. if (this.blocks) {
  23029. for (var index = 0; index < this.blocks.length; index++) {
  23030. var block = this.blocks[index];
  23031. block.select(frustumPlanes, selection, allowDuplicate);
  23032. }
  23033. return;
  23034. }
  23035. if (allowDuplicate) {
  23036. selection.concat(this.entries);
  23037. }
  23038. else {
  23039. selection.concatWithNoDuplicate(this.entries);
  23040. }
  23041. }
  23042. };
  23043. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  23044. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  23045. if (this.blocks) {
  23046. for (var index = 0; index < this.blocks.length; index++) {
  23047. var block = this.blocks[index];
  23048. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  23049. }
  23050. return;
  23051. }
  23052. if (allowDuplicate) {
  23053. selection.concat(this.entries);
  23054. }
  23055. else {
  23056. selection.concatWithNoDuplicate(this.entries);
  23057. }
  23058. }
  23059. };
  23060. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  23061. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  23062. if (this.blocks) {
  23063. for (var index = 0; index < this.blocks.length; index++) {
  23064. var block = this.blocks[index];
  23065. block.intersectsRay(ray, selection);
  23066. }
  23067. return;
  23068. }
  23069. selection.concatWithNoDuplicate(this.entries);
  23070. }
  23071. };
  23072. OctreeBlock.prototype.createInnerBlocks = function () {
  23073. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  23074. };
  23075. return OctreeBlock;
  23076. })();
  23077. BABYLON.OctreeBlock = OctreeBlock;
  23078. })(BABYLON || (BABYLON = {}));
  23079. var BABYLON;
  23080. (function (BABYLON) {
  23081. var Bone = (function (_super) {
  23082. __extends(Bone, _super);
  23083. function Bone(name, skeleton, parentBone, matrix) {
  23084. _super.call(this, name, skeleton.getScene());
  23085. this.name = name;
  23086. this.children = new Array();
  23087. this.animations = new Array();
  23088. this._worldTransform = new BABYLON.Matrix();
  23089. this._absoluteTransform = new BABYLON.Matrix();
  23090. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23091. this._skeleton = skeleton;
  23092. this._matrix = matrix;
  23093. this._baseMatrix = matrix;
  23094. skeleton.bones.push(this);
  23095. if (parentBone) {
  23096. this._parent = parentBone;
  23097. parentBone.children.push(this);
  23098. }
  23099. else {
  23100. this._parent = null;
  23101. }
  23102. this._updateDifferenceMatrix();
  23103. }
  23104. // Members
  23105. Bone.prototype.getParent = function () {
  23106. return this._parent;
  23107. };
  23108. Bone.prototype.getLocalMatrix = function () {
  23109. return this._matrix;
  23110. };
  23111. Bone.prototype.getBaseMatrix = function () {
  23112. return this._baseMatrix;
  23113. };
  23114. Bone.prototype.getWorldMatrix = function () {
  23115. return this._worldTransform;
  23116. };
  23117. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23118. return this._invertedAbsoluteTransform;
  23119. };
  23120. Bone.prototype.getAbsoluteMatrix = function () {
  23121. var matrix = this._matrix.clone();
  23122. var parent = this._parent;
  23123. while (parent) {
  23124. matrix = matrix.multiply(parent.getLocalMatrix());
  23125. parent = parent.getParent();
  23126. }
  23127. return matrix;
  23128. };
  23129. // Methods
  23130. Bone.prototype.updateMatrix = function (matrix) {
  23131. this._matrix = matrix;
  23132. this._skeleton._markAsDirty();
  23133. this._updateDifferenceMatrix();
  23134. };
  23135. Bone.prototype._updateDifferenceMatrix = function () {
  23136. if (this._parent) {
  23137. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23138. }
  23139. else {
  23140. this._absoluteTransform.copyFrom(this._matrix);
  23141. }
  23142. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23143. for (var index = 0; index < this.children.length; index++) {
  23144. this.children[index]._updateDifferenceMatrix();
  23145. }
  23146. };
  23147. Bone.prototype.markAsDirty = function () {
  23148. this._currentRenderId++;
  23149. this._skeleton._markAsDirty();
  23150. };
  23151. return Bone;
  23152. })(BABYLON.Node);
  23153. BABYLON.Bone = Bone;
  23154. })(BABYLON || (BABYLON = {}));
  23155. var BABYLON;
  23156. (function (BABYLON) {
  23157. var Skeleton = (function () {
  23158. function Skeleton(name, id, scene) {
  23159. this.name = name;
  23160. this.id = id;
  23161. this.bones = new Array();
  23162. this._isDirty = true;
  23163. this._identity = BABYLON.Matrix.Identity();
  23164. this.bones = [];
  23165. this._scene = scene;
  23166. scene.skeletons.push(this);
  23167. this.prepare();
  23168. //make sure it will recalculate the matrix next time prepare is called.
  23169. this._isDirty = true;
  23170. }
  23171. // Members
  23172. Skeleton.prototype.getTransformMatrices = function () {
  23173. return this._transformMatrices;
  23174. };
  23175. Skeleton.prototype.getScene = function () {
  23176. return this._scene;
  23177. };
  23178. // Methods
  23179. Skeleton.prototype._markAsDirty = function () {
  23180. this._isDirty = true;
  23181. };
  23182. Skeleton.prototype.prepare = function () {
  23183. if (!this._isDirty) {
  23184. return;
  23185. }
  23186. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23187. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23188. }
  23189. for (var index = 0; index < this.bones.length; index++) {
  23190. var bone = this.bones[index];
  23191. var parentBone = bone.getParent();
  23192. if (parentBone) {
  23193. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23194. }
  23195. else {
  23196. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23197. }
  23198. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  23199. }
  23200. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  23201. this._isDirty = false;
  23202. this._scene._activeBones += this.bones.length;
  23203. };
  23204. Skeleton.prototype.getAnimatables = function () {
  23205. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23206. this._animatables = [];
  23207. for (var index = 0; index < this.bones.length; index++) {
  23208. this._animatables.push(this.bones[index]);
  23209. }
  23210. }
  23211. return this._animatables;
  23212. };
  23213. Skeleton.prototype.clone = function (name, id) {
  23214. var result = new Skeleton(name, id || name, this._scene);
  23215. for (var index = 0; index < this.bones.length; index++) {
  23216. var source = this.bones[index];
  23217. var parentBone = null;
  23218. if (source.getParent()) {
  23219. var parentIndex = this.bones.indexOf(source.getParent());
  23220. parentBone = result.bones[parentIndex];
  23221. }
  23222. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  23223. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23224. }
  23225. return result;
  23226. };
  23227. return Skeleton;
  23228. })();
  23229. BABYLON.Skeleton = Skeleton;
  23230. })(BABYLON || (BABYLON = {}));
  23231. var BABYLON;
  23232. (function (BABYLON) {
  23233. var PostProcess = (function () {
  23234. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23235. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23236. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23237. this.name = name;
  23238. this.width = -1;
  23239. this.height = -1;
  23240. this._reusable = false;
  23241. this._textures = new BABYLON.SmartArray(2);
  23242. this._currentRenderTextureInd = 0;
  23243. if (camera != null) {
  23244. this._camera = camera;
  23245. this._scene = camera.getScene();
  23246. camera.attachPostProcess(this);
  23247. this._engine = this._scene.getEngine();
  23248. }
  23249. else {
  23250. this._engine = engine;
  23251. }
  23252. this._renderRatio = ratio;
  23253. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23254. this._reusable = reusable || false;
  23255. this._textureType = textureType;
  23256. samplers = samplers || [];
  23257. samplers.push("textureSampler");
  23258. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  23259. }
  23260. PostProcess.prototype.isReusable = function () {
  23261. return this._reusable;
  23262. };
  23263. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23264. camera = camera || this._camera;
  23265. var scene = camera.getScene();
  23266. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23267. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23268. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23269. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  23270. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  23271. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23272. if (this._textures.length > 0) {
  23273. for (var i = 0; i < this._textures.length; i++) {
  23274. this._engine._releaseTexture(this._textures.data[i]);
  23275. }
  23276. this._textures.reset();
  23277. }
  23278. this.width = desiredWidth;
  23279. this.height = desiredHeight;
  23280. 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 }));
  23281. if (this._reusable) {
  23282. 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 }));
  23283. }
  23284. if (this.onSizeChanged) {
  23285. this.onSizeChanged();
  23286. }
  23287. }
  23288. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23289. if (this.onActivate) {
  23290. this.onActivate(camera);
  23291. }
  23292. // Clear
  23293. if (this.clearColor) {
  23294. this._engine.clear(this.clearColor, true, true);
  23295. }
  23296. else {
  23297. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23298. }
  23299. if (this._reusable) {
  23300. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23301. }
  23302. };
  23303. PostProcess.prototype.apply = function () {
  23304. // Check
  23305. if (!this._effect.isReady())
  23306. return null;
  23307. // States
  23308. this._engine.enableEffect(this._effect);
  23309. this._engine.setState(false);
  23310. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23311. this._engine.setDepthBuffer(false);
  23312. this._engine.setDepthWrite(false);
  23313. // Texture
  23314. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23315. // Parameters
  23316. if (this.onApply) {
  23317. this.onApply(this._effect);
  23318. }
  23319. return this._effect;
  23320. };
  23321. PostProcess.prototype.dispose = function (camera) {
  23322. camera = camera || this._camera;
  23323. if (this._textures.length > 0) {
  23324. for (var i = 0; i < this._textures.length; i++) {
  23325. this._engine._releaseTexture(this._textures.data[i]);
  23326. }
  23327. this._textures.reset();
  23328. }
  23329. if (!camera) {
  23330. return;
  23331. }
  23332. camera.detachPostProcess(this);
  23333. var index = camera._postProcesses.indexOf(this);
  23334. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23335. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23336. }
  23337. };
  23338. return PostProcess;
  23339. })();
  23340. BABYLON.PostProcess = PostProcess;
  23341. })(BABYLON || (BABYLON = {}));
  23342. var BABYLON;
  23343. (function (BABYLON) {
  23344. var PostProcessManager = (function () {
  23345. function PostProcessManager(scene) {
  23346. this._vertexDeclaration = [2];
  23347. this._vertexStrideSize = 2 * 4;
  23348. this._scene = scene;
  23349. }
  23350. PostProcessManager.prototype._prepareBuffers = function () {
  23351. if (this._vertexBuffer) {
  23352. return;
  23353. }
  23354. // VBO
  23355. var vertices = [];
  23356. vertices.push(1, 1);
  23357. vertices.push(-1, 1);
  23358. vertices.push(-1, -1);
  23359. vertices.push(1, -1);
  23360. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23361. // Indices
  23362. var indices = [];
  23363. indices.push(0);
  23364. indices.push(1);
  23365. indices.push(2);
  23366. indices.push(0);
  23367. indices.push(2);
  23368. indices.push(3);
  23369. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23370. };
  23371. // Methods
  23372. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23373. var postProcesses = this._scene.activeCamera._postProcesses;
  23374. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23375. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23376. return false;
  23377. }
  23378. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23379. return true;
  23380. };
  23381. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23382. var engine = this._scene.getEngine();
  23383. for (var index = 0; index < postProcesses.length; index++) {
  23384. if (index < postProcesses.length - 1) {
  23385. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23386. }
  23387. else {
  23388. if (targetTexture) {
  23389. engine.bindFramebuffer(targetTexture);
  23390. }
  23391. else {
  23392. engine.restoreDefaultFramebuffer();
  23393. }
  23394. }
  23395. var pp = postProcesses[index];
  23396. var effect = pp.apply();
  23397. if (effect) {
  23398. if (pp.onBeforeRender) {
  23399. pp.onBeforeRender(effect);
  23400. }
  23401. // VBOs
  23402. this._prepareBuffers();
  23403. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23404. // Draw order
  23405. engine.draw(true, 0, 6);
  23406. if (pp.onAfterRender) {
  23407. pp.onAfterRender(effect);
  23408. }
  23409. }
  23410. }
  23411. // Restore depth buffer
  23412. engine.setDepthBuffer(true);
  23413. engine.setDepthWrite(true);
  23414. };
  23415. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23416. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23417. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23418. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23419. return;
  23420. }
  23421. var engine = this._scene.getEngine();
  23422. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23423. if (index < postProcessesTakenIndices.length - 1) {
  23424. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  23425. }
  23426. else {
  23427. if (targetTexture) {
  23428. engine.bindFramebuffer(targetTexture, faceIndex);
  23429. }
  23430. else {
  23431. engine.restoreDefaultFramebuffer();
  23432. }
  23433. }
  23434. if (doNotPresent) {
  23435. break;
  23436. }
  23437. var pp = postProcesses[postProcessesTakenIndices[index]];
  23438. var effect = pp.apply();
  23439. if (effect) {
  23440. if (pp.onBeforeRender) {
  23441. pp.onBeforeRender(effect);
  23442. }
  23443. // VBOs
  23444. this._prepareBuffers();
  23445. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23446. // Draw order
  23447. engine.draw(true, 0, 6);
  23448. if (pp.onAfterRender) {
  23449. pp.onAfterRender(effect);
  23450. }
  23451. }
  23452. }
  23453. // Restore depth buffer
  23454. engine.setDepthBuffer(true);
  23455. engine.setDepthWrite(true);
  23456. };
  23457. PostProcessManager.prototype.dispose = function () {
  23458. if (this._vertexBuffer) {
  23459. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23460. this._vertexBuffer = null;
  23461. }
  23462. if (this._indexBuffer) {
  23463. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23464. this._indexBuffer = null;
  23465. }
  23466. };
  23467. return PostProcessManager;
  23468. })();
  23469. BABYLON.PostProcessManager = PostProcessManager;
  23470. })(BABYLON || (BABYLON = {}));
  23471. var BABYLON;
  23472. (function (BABYLON) {
  23473. var PassPostProcess = (function (_super) {
  23474. __extends(PassPostProcess, _super);
  23475. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23476. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23477. }
  23478. return PassPostProcess;
  23479. })(BABYLON.PostProcess);
  23480. BABYLON.PassPostProcess = PassPostProcess;
  23481. })(BABYLON || (BABYLON = {}));
  23482. var BABYLON;
  23483. (function (BABYLON) {
  23484. var BlurPostProcess = (function (_super) {
  23485. __extends(BlurPostProcess, _super);
  23486. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  23487. var _this = this;
  23488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  23489. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  23490. this.direction = direction;
  23491. this.blurWidth = blurWidth;
  23492. this.onApply = function (effect) {
  23493. effect.setFloat2("screenSize", _this.width, _this.height);
  23494. effect.setVector2("direction", _this.direction);
  23495. effect.setFloat("blurWidth", _this.blurWidth);
  23496. };
  23497. }
  23498. return BlurPostProcess;
  23499. })(BABYLON.PostProcess);
  23500. BABYLON.BlurPostProcess = BlurPostProcess;
  23501. })(BABYLON || (BABYLON = {}));
  23502. var BABYLON;
  23503. (function (BABYLON) {
  23504. var RefractionPostProcess = (function (_super) {
  23505. __extends(RefractionPostProcess, _super);
  23506. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  23507. var _this = this;
  23508. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  23509. this.color = color;
  23510. this.depth = depth;
  23511. this.colorLevel = colorLevel;
  23512. this.onActivate = function (cam) {
  23513. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23514. };
  23515. this.onApply = function (effect) {
  23516. effect.setColor3("baseColor", _this.color);
  23517. effect.setFloat("depth", _this.depth);
  23518. effect.setFloat("colorLevel", _this.colorLevel);
  23519. effect.setTexture("refractionSampler", _this._refRexture);
  23520. };
  23521. }
  23522. // Methods
  23523. RefractionPostProcess.prototype.dispose = function (camera) {
  23524. if (this._refRexture) {
  23525. this._refRexture.dispose();
  23526. }
  23527. _super.prototype.dispose.call(this, camera);
  23528. };
  23529. return RefractionPostProcess;
  23530. })(BABYLON.PostProcess);
  23531. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23532. })(BABYLON || (BABYLON = {}));
  23533. var BABYLON;
  23534. (function (BABYLON) {
  23535. var BlackAndWhitePostProcess = (function (_super) {
  23536. __extends(BlackAndWhitePostProcess, _super);
  23537. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23538. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23539. }
  23540. return BlackAndWhitePostProcess;
  23541. })(BABYLON.PostProcess);
  23542. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23543. })(BABYLON || (BABYLON = {}));
  23544. var BABYLON;
  23545. (function (BABYLON) {
  23546. var ConvolutionPostProcess = (function (_super) {
  23547. __extends(ConvolutionPostProcess, _super);
  23548. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23549. var _this = this;
  23550. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23551. this.kernel = kernel;
  23552. this.onApply = function (effect) {
  23553. effect.setFloat2("screenSize", _this.width, _this.height);
  23554. effect.setArray("kernel", _this.kernel);
  23555. };
  23556. }
  23557. // Statics
  23558. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23559. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23560. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23561. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23562. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23563. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23564. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23565. return ConvolutionPostProcess;
  23566. })(BABYLON.PostProcess);
  23567. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23568. })(BABYLON || (BABYLON = {}));
  23569. var BABYLON;
  23570. (function (BABYLON) {
  23571. var FilterPostProcess = (function (_super) {
  23572. __extends(FilterPostProcess, _super);
  23573. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23574. var _this = this;
  23575. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23576. this.kernelMatrix = kernelMatrix;
  23577. this.onApply = function (effect) {
  23578. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23579. };
  23580. }
  23581. return FilterPostProcess;
  23582. })(BABYLON.PostProcess);
  23583. BABYLON.FilterPostProcess = FilterPostProcess;
  23584. })(BABYLON || (BABYLON = {}));
  23585. var BABYLON;
  23586. (function (BABYLON) {
  23587. var FxaaPostProcess = (function (_super) {
  23588. __extends(FxaaPostProcess, _super);
  23589. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23590. var _this = this;
  23591. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23592. this.onSizeChanged = function () {
  23593. _this.texelWidth = 1.0 / _this.width;
  23594. _this.texelHeight = 1.0 / _this.height;
  23595. };
  23596. this.onApply = function (effect) {
  23597. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23598. };
  23599. }
  23600. return FxaaPostProcess;
  23601. })(BABYLON.PostProcess);
  23602. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23603. })(BABYLON || (BABYLON = {}));
  23604. var BABYLON;
  23605. (function (BABYLON) {
  23606. var StereoscopicInterlacePostProcess = (function (_super) {
  23607. __extends(StereoscopicInterlacePostProcess, _super);
  23608. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23609. var _this = this;
  23610. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23611. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23612. this.onSizeChanged = function () {
  23613. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23614. };
  23615. this.onApply = function (effect) {
  23616. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23617. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23618. };
  23619. }
  23620. return StereoscopicInterlacePostProcess;
  23621. })(BABYLON.PostProcess);
  23622. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23623. })(BABYLON || (BABYLON = {}));
  23624. var BABYLON;
  23625. (function (BABYLON) {
  23626. var LensFlare = (function () {
  23627. function LensFlare(size, position, color, imgUrl, system) {
  23628. this.size = size;
  23629. this.position = position;
  23630. this.dispose = function () {
  23631. if (this.texture) {
  23632. this.texture.dispose();
  23633. }
  23634. // Remove from scene
  23635. var index = this._system.lensFlares.indexOf(this);
  23636. this._system.lensFlares.splice(index, 1);
  23637. };
  23638. this.color = color || new BABYLON.Color3(1, 1, 1);
  23639. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23640. this._system = system;
  23641. system.lensFlares.push(this);
  23642. }
  23643. return LensFlare;
  23644. })();
  23645. BABYLON.LensFlare = LensFlare;
  23646. })(BABYLON || (BABYLON = {}));
  23647. var BABYLON;
  23648. (function (BABYLON) {
  23649. var LensFlareSystem = (function () {
  23650. function LensFlareSystem(name, emitter, scene) {
  23651. this.name = name;
  23652. this.lensFlares = new Array();
  23653. this.borderLimit = 300;
  23654. this.layerMask = 0x0FFFFFFF;
  23655. this._vertexDeclaration = [2];
  23656. this._vertexStrideSize = 2 * 4;
  23657. this._isEnabled = true;
  23658. this._scene = scene;
  23659. this._emitter = emitter;
  23660. scene.lensFlareSystems.push(this);
  23661. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23662. // VBO
  23663. var vertices = [];
  23664. vertices.push(1, 1);
  23665. vertices.push(-1, 1);
  23666. vertices.push(-1, -1);
  23667. vertices.push(1, -1);
  23668. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23669. // Indices
  23670. var indices = [];
  23671. indices.push(0);
  23672. indices.push(1);
  23673. indices.push(2);
  23674. indices.push(0);
  23675. indices.push(2);
  23676. indices.push(3);
  23677. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23678. // Effects
  23679. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23680. }
  23681. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23682. get: function () {
  23683. return this._isEnabled;
  23684. },
  23685. set: function (value) {
  23686. this._isEnabled = value;
  23687. },
  23688. enumerable: true,
  23689. configurable: true
  23690. });
  23691. LensFlareSystem.prototype.getScene = function () {
  23692. return this._scene;
  23693. };
  23694. LensFlareSystem.prototype.getEmitter = function () {
  23695. return this._emitter;
  23696. };
  23697. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23698. this._emitter = newEmitter;
  23699. };
  23700. LensFlareSystem.prototype.getEmitterPosition = function () {
  23701. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23702. };
  23703. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23704. var position = this.getEmitterPosition();
  23705. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23706. this._positionX = position.x;
  23707. this._positionY = position.y;
  23708. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23709. if (position.z > 0) {
  23710. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23711. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23712. return true;
  23713. }
  23714. }
  23715. return false;
  23716. };
  23717. LensFlareSystem.prototype._isVisible = function () {
  23718. if (!this._isEnabled) {
  23719. return false;
  23720. }
  23721. var emitterPosition = this.getEmitterPosition();
  23722. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23723. var distance = direction.length();
  23724. direction.normalize();
  23725. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23726. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23727. return !pickInfo.hit || pickInfo.distance > distance;
  23728. };
  23729. LensFlareSystem.prototype.render = function () {
  23730. if (!this._effect.isReady())
  23731. return false;
  23732. var engine = this._scene.getEngine();
  23733. var viewport = this._scene.activeCamera.viewport;
  23734. var globalViewport = viewport.toGlobal(engine);
  23735. // Position
  23736. if (!this.computeEffectivePosition(globalViewport)) {
  23737. return false;
  23738. }
  23739. // Visibility
  23740. if (!this._isVisible()) {
  23741. return false;
  23742. }
  23743. // Intensity
  23744. var awayX;
  23745. var awayY;
  23746. if (this._positionX < this.borderLimit + globalViewport.x) {
  23747. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23748. }
  23749. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23750. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23751. }
  23752. else {
  23753. awayX = 0;
  23754. }
  23755. if (this._positionY < this.borderLimit + globalViewport.y) {
  23756. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23757. }
  23758. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23759. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23760. }
  23761. else {
  23762. awayY = 0;
  23763. }
  23764. var away = (awayX > awayY) ? awayX : awayY;
  23765. if (away > this.borderLimit) {
  23766. away = this.borderLimit;
  23767. }
  23768. var intensity = 1.0 - (away / this.borderLimit);
  23769. if (intensity < 0) {
  23770. return false;
  23771. }
  23772. if (intensity > 1.0) {
  23773. intensity = 1.0;
  23774. }
  23775. // Position
  23776. var centerX = globalViewport.x + globalViewport.width / 2;
  23777. var centerY = globalViewport.y + globalViewport.height / 2;
  23778. var distX = centerX - this._positionX;
  23779. var distY = centerY - this._positionY;
  23780. // Effects
  23781. engine.enableEffect(this._effect);
  23782. engine.setState(false);
  23783. engine.setDepthBuffer(false);
  23784. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23785. // VBOs
  23786. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23787. // Flares
  23788. for (var index = 0; index < this.lensFlares.length; index++) {
  23789. var flare = this.lensFlares[index];
  23790. var x = centerX - (distX * flare.position);
  23791. var y = centerY - (distY * flare.position);
  23792. var cw = flare.size;
  23793. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23794. var cx = 2 * (x / globalViewport.width) - 1.0;
  23795. var cy = 1.0 - 2 * (y / globalViewport.height);
  23796. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23797. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23798. // Texture
  23799. this._effect.setTexture("textureSampler", flare.texture);
  23800. // Color
  23801. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23802. // Draw order
  23803. engine.draw(true, 0, 6);
  23804. }
  23805. engine.setDepthBuffer(true);
  23806. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23807. return true;
  23808. };
  23809. LensFlareSystem.prototype.dispose = function () {
  23810. if (this._vertexBuffer) {
  23811. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23812. this._vertexBuffer = null;
  23813. }
  23814. if (this._indexBuffer) {
  23815. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23816. this._indexBuffer = null;
  23817. }
  23818. while (this.lensFlares.length) {
  23819. this.lensFlares[0].dispose();
  23820. }
  23821. // Remove from scene
  23822. var index = this._scene.lensFlareSystems.indexOf(this);
  23823. this._scene.lensFlareSystems.splice(index, 1);
  23824. };
  23825. return LensFlareSystem;
  23826. })();
  23827. BABYLON.LensFlareSystem = LensFlareSystem;
  23828. })(BABYLON || (BABYLON = {}));
  23829. var BABYLON;
  23830. (function (BABYLON) {
  23831. var CannonJSPlugin = (function () {
  23832. function CannonJSPlugin() {
  23833. this._registeredMeshes = [];
  23834. this._physicsMaterials = [];
  23835. this.updateBodyPosition = function (mesh) {
  23836. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23837. var registeredMesh = this._registeredMeshes[index];
  23838. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23839. var body = registeredMesh.body;
  23840. var center = mesh.getBoundingInfo().boundingBox.center;
  23841. body.position.set(center.x, center.z, center.y);
  23842. body.quaternion.x = mesh.rotationQuaternion.x;
  23843. body.quaternion.z = mesh.rotationQuaternion.y;
  23844. body.quaternion.y = mesh.rotationQuaternion.z;
  23845. body.quaternion.w = -mesh.rotationQuaternion.w;
  23846. return;
  23847. }
  23848. }
  23849. };
  23850. }
  23851. CannonJSPlugin.prototype.initialize = function (iterations) {
  23852. if (iterations === void 0) { iterations = 10; }
  23853. this._world = new CANNON.World();
  23854. this._world.broadphase = new CANNON.NaiveBroadphase();
  23855. this._world.solver.iterations = iterations;
  23856. };
  23857. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23858. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23859. };
  23860. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23861. this._world.step(delta);
  23862. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23863. var registeredMesh = this._registeredMeshes[index];
  23864. if (registeredMesh.isChild) {
  23865. continue;
  23866. }
  23867. // Body position
  23868. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23869. var deltaPos = registeredMesh.delta;
  23870. if (deltaPos) {
  23871. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23872. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23873. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23874. }
  23875. else {
  23876. registeredMesh.mesh.position.x = bodyX;
  23877. registeredMesh.mesh.position.y = bodyZ;
  23878. registeredMesh.mesh.position.z = bodyY;
  23879. }
  23880. if (!registeredMesh.mesh.rotationQuaternion) {
  23881. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23882. }
  23883. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23884. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23885. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23886. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23887. }
  23888. };
  23889. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23890. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23891. };
  23892. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23893. this.unregisterMesh(mesh);
  23894. mesh.computeWorldMatrix(true);
  23895. switch (impostor) {
  23896. case BABYLON.PhysicsEngine.SphereImpostor:
  23897. var bbox = mesh.getBoundingInfo().boundingBox;
  23898. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23899. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23900. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23901. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23902. case BABYLON.PhysicsEngine.BoxImpostor:
  23903. bbox = mesh.getBoundingInfo().boundingBox;
  23904. var min = bbox.minimumWorld;
  23905. var max = bbox.maximumWorld;
  23906. var box = max.subtract(min).scale(0.5);
  23907. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23908. case BABYLON.PhysicsEngine.PlaneImpostor:
  23909. return this._createPlane(mesh, options);
  23910. case BABYLON.PhysicsEngine.MeshImpostor:
  23911. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23912. var rawFaces = mesh.getIndices();
  23913. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23914. }
  23915. return null;
  23916. };
  23917. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23918. var shape = new CANNON.Sphere(radius);
  23919. if (!options) {
  23920. return shape;
  23921. }
  23922. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23923. };
  23924. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23925. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23926. if (!options) {
  23927. return shape;
  23928. }
  23929. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23930. };
  23931. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23932. var shape = new CANNON.Plane();
  23933. if (!options) {
  23934. return shape;
  23935. }
  23936. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23937. };
  23938. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23939. var verts = [], faces = [];
  23940. mesh.computeWorldMatrix(true);
  23941. // Get vertices
  23942. for (var i = 0; i < rawVerts.length; i += 3) {
  23943. var transformed = BABYLON.Vector3.Zero();
  23944. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23945. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23946. }
  23947. // Get faces
  23948. for (var j = 0; j < rawFaces.length; j += 3) {
  23949. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23950. }
  23951. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23952. if (!options) {
  23953. return shape;
  23954. }
  23955. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23956. };
  23957. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23958. var index;
  23959. var mat;
  23960. for (index = 0; index < this._physicsMaterials.length; index++) {
  23961. mat = this._physicsMaterials[index];
  23962. if (mat.friction === friction && mat.restitution === restitution) {
  23963. return mat;
  23964. }
  23965. }
  23966. var currentMat = new CANNON.Material();
  23967. currentMat.friction = friction;
  23968. currentMat.restitution = restitution;
  23969. this._physicsMaterials.push(currentMat);
  23970. for (index = 0; index < this._physicsMaterials.length; index++) {
  23971. mat = this._physicsMaterials[index];
  23972. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23973. contactMaterial.contactEquationStiffness = 1e10;
  23974. contactMaterial.contactEquationRegularizationTime = 10;
  23975. this._world.addContactMaterial(contactMaterial);
  23976. }
  23977. return currentMat;
  23978. };
  23979. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23980. var initialRotation = null;
  23981. if (mesh.rotationQuaternion) {
  23982. initialRotation = mesh.rotationQuaternion.clone();
  23983. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23984. }
  23985. // The delta between the mesh position and the mesh bounding box center
  23986. var bbox = mesh.getBoundingInfo().boundingBox;
  23987. var deltaPosition = mesh.position.subtract(bbox.center);
  23988. var material = this._addMaterial(friction, restitution);
  23989. var body = new CANNON.RigidBody(mass, shape, material);
  23990. if (initialRotation) {
  23991. body.quaternion.x = initialRotation.x;
  23992. body.quaternion.z = initialRotation.y;
  23993. body.quaternion.y = initialRotation.z;
  23994. body.quaternion.w = -initialRotation.w;
  23995. }
  23996. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23997. this._world.add(body);
  23998. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23999. return body;
  24000. };
  24001. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24002. var compoundShape = new CANNON.Compound();
  24003. for (var index = 0; index < parts.length; index++) {
  24004. var mesh = parts[index].mesh;
  24005. var shape = this.registerMesh(mesh, parts[index].impostor);
  24006. if (index == 0) {
  24007. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24008. }
  24009. else {
  24010. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24011. }
  24012. }
  24013. var initialMesh = parts[0].mesh;
  24014. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24015. body.parts = parts;
  24016. return body;
  24017. };
  24018. CannonJSPlugin.prototype._unbindBody = function (body) {
  24019. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24020. var registeredMesh = this._registeredMeshes[index];
  24021. if (registeredMesh.body === body) {
  24022. registeredMesh.body = null;
  24023. registeredMesh.delta = 0;
  24024. }
  24025. }
  24026. };
  24027. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24028. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24029. var registeredMesh = this._registeredMeshes[index];
  24030. if (registeredMesh.mesh === mesh) {
  24031. // Remove body
  24032. if (registeredMesh.body) {
  24033. this._world.remove(registeredMesh.body);
  24034. this._unbindBody(registeredMesh.body);
  24035. }
  24036. this._registeredMeshes.splice(index, 1);
  24037. return;
  24038. }
  24039. }
  24040. };
  24041. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24042. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24043. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24044. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24045. var registeredMesh = this._registeredMeshes[index];
  24046. if (registeredMesh.mesh === mesh) {
  24047. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24048. return;
  24049. }
  24050. }
  24051. };
  24052. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24053. var body1 = null, body2 = null;
  24054. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24055. var registeredMesh = this._registeredMeshes[index];
  24056. if (registeredMesh.mesh === mesh1) {
  24057. body1 = registeredMesh.body;
  24058. }
  24059. else if (registeredMesh.mesh === mesh2) {
  24060. body2 = registeredMesh.body;
  24061. }
  24062. }
  24063. if (!body1 || !body2) {
  24064. return false;
  24065. }
  24066. 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));
  24067. this._world.addConstraint(constraint);
  24068. return true;
  24069. };
  24070. CannonJSPlugin.prototype.dispose = function () {
  24071. while (this._registeredMeshes.length) {
  24072. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24073. }
  24074. };
  24075. CannonJSPlugin.prototype.isSupported = function () {
  24076. return window.CANNON !== undefined;
  24077. };
  24078. return CannonJSPlugin;
  24079. })();
  24080. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24081. })(BABYLON || (BABYLON = {}));
  24082. var BABYLON;
  24083. (function (BABYLON) {
  24084. var OimoJSPlugin = (function () {
  24085. function OimoJSPlugin() {
  24086. this._registeredMeshes = [];
  24087. /**
  24088. * Update the body position according to the mesh position
  24089. * @param mesh
  24090. */
  24091. this.updateBodyPosition = function (mesh) {
  24092. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24093. var registeredMesh = this._registeredMeshes[index];
  24094. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24095. var body = registeredMesh.body.body;
  24096. mesh.computeWorldMatrix(true);
  24097. var center = mesh.getBoundingInfo().boundingBox.center;
  24098. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  24099. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  24100. body.sleeping = false;
  24101. return;
  24102. }
  24103. // Case where the parent has been updated
  24104. if (registeredMesh.mesh.parent === mesh) {
  24105. mesh.computeWorldMatrix(true);
  24106. registeredMesh.mesh.computeWorldMatrix(true);
  24107. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  24108. var absoluteRotation = mesh.rotation;
  24109. body = registeredMesh.body.body;
  24110. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  24111. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  24112. body.sleeping = false;
  24113. return;
  24114. }
  24115. }
  24116. };
  24117. }
  24118. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  24119. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24120. };
  24121. OimoJSPlugin.prototype.initialize = function (iterations) {
  24122. this._world = new OIMO.World();
  24123. this._world.clear();
  24124. };
  24125. OimoJSPlugin.prototype.setGravity = function (gravity) {
  24126. this._world.gravity = gravity;
  24127. };
  24128. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24129. var body = null;
  24130. this.unregisterMesh(mesh);
  24131. mesh.computeWorldMatrix(true);
  24132. var initialRotation = null;
  24133. if (mesh.rotationQuaternion) {
  24134. initialRotation = mesh.rotationQuaternion.clone();
  24135. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24136. mesh.computeWorldMatrix(true);
  24137. }
  24138. var bbox = mesh.getBoundingInfo().boundingBox;
  24139. // The delta between the mesh position and the mesh bounding box center
  24140. var deltaPosition = mesh.position.subtract(bbox.center);
  24141. // Transform delta position with the rotation
  24142. if (initialRotation) {
  24143. var m = new BABYLON.Matrix();
  24144. initialRotation.toRotationMatrix(m);
  24145. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  24146. }
  24147. // register mesh
  24148. switch (impostor) {
  24149. case BABYLON.PhysicsEngine.SphereImpostor:
  24150. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24151. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24152. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24153. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  24154. body = new OIMO.Body({
  24155. type: 'sphere',
  24156. size: [size],
  24157. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  24158. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  24159. move: options.mass != 0,
  24160. config: [options.mass, options.friction, options.restitution],
  24161. world: this._world
  24162. });
  24163. break;
  24164. case BABYLON.PhysicsEngine.PlaneImpostor:
  24165. //Oimo "fakes" a cylinder as a box, so why don't we!
  24166. case BABYLON.PhysicsEngine.CylinderImpostor:
  24167. case BABYLON.PhysicsEngine.BoxImpostor:
  24168. var min = bbox.minimumWorld;
  24169. var max = bbox.maximumWorld;
  24170. var box = max.subtract(min);
  24171. var sizeX = this._checkWithEpsilon(box.x);
  24172. var sizeY = this._checkWithEpsilon(box.y);
  24173. var sizeZ = this._checkWithEpsilon(box.z);
  24174. body = new OIMO.Body({
  24175. type: 'box',
  24176. size: [sizeX, sizeY, sizeZ],
  24177. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  24178. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  24179. move: options.mass != 0,
  24180. config: [options.mass, options.friction, options.restitution],
  24181. world: this._world
  24182. });
  24183. break;
  24184. }
  24185. //If quaternion was set as the rotation of the object
  24186. if (initialRotation) {
  24187. //We have to access the rigid body's properties to set the quaternion.
  24188. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  24189. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  24190. //update the internal rotation matrix
  24191. body.body.syncShapes();
  24192. }
  24193. this._registeredMeshes.push({
  24194. mesh: mesh,
  24195. body: body,
  24196. delta: deltaPosition
  24197. });
  24198. return body;
  24199. };
  24200. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24201. var types = [], sizes = [], positions = [], rotations = [];
  24202. var initialMesh = parts[0].mesh;
  24203. for (var index = 0; index < parts.length; index++) {
  24204. var part = parts[index];
  24205. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  24206. types.push(bodyParameters.type);
  24207. sizes.push.apply(sizes, bodyParameters.size);
  24208. positions.push.apply(positions, bodyParameters.pos);
  24209. rotations.push.apply(rotations, bodyParameters.rot);
  24210. }
  24211. var body = new OIMO.Body({
  24212. type: types,
  24213. size: sizes,
  24214. pos: positions,
  24215. rot: rotations,
  24216. move: options.mass != 0,
  24217. config: [options.mass, options.friction, options.restitution],
  24218. world: this._world
  24219. });
  24220. this._registeredMeshes.push({
  24221. mesh: initialMesh,
  24222. body: body
  24223. });
  24224. return body;
  24225. };
  24226. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  24227. var bodyParameters = null;
  24228. var mesh = part.mesh;
  24229. // We need the bounding box/sphere info to compute the physics body
  24230. mesh.computeWorldMatrix();
  24231. switch (part.impostor) {
  24232. case BABYLON.PhysicsEngine.SphereImpostor:
  24233. var bbox = mesh.getBoundingInfo().boundingBox;
  24234. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24235. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24236. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24237. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  24238. bodyParameters = {
  24239. type: 'sphere',
  24240. /* bug with oimo : sphere needs 3 sizes in this case */
  24241. size: [size, -1, -1],
  24242. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  24243. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  24244. };
  24245. break;
  24246. case BABYLON.PhysicsEngine.PlaneImpostor:
  24247. case BABYLON.PhysicsEngine.BoxImpostor:
  24248. bbox = mesh.getBoundingInfo().boundingBox;
  24249. var min = bbox.minimumWorld;
  24250. var max = bbox.maximumWorld;
  24251. var box = max.subtract(min);
  24252. var sizeX = this._checkWithEpsilon(box.x);
  24253. var sizeY = this._checkWithEpsilon(box.y);
  24254. var sizeZ = this._checkWithEpsilon(box.z);
  24255. var relativePosition = mesh.position;
  24256. bodyParameters = {
  24257. type: 'box',
  24258. size: [sizeX, sizeY, sizeZ],
  24259. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  24260. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  24261. };
  24262. break;
  24263. }
  24264. return bodyParameters;
  24265. };
  24266. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  24267. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24268. var registeredMesh = this._registeredMeshes[index];
  24269. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24270. if (registeredMesh.body) {
  24271. this._world.removeRigidBody(registeredMesh.body.body);
  24272. this._unbindBody(registeredMesh.body);
  24273. }
  24274. this._registeredMeshes.splice(index, 1);
  24275. return;
  24276. }
  24277. }
  24278. };
  24279. OimoJSPlugin.prototype._unbindBody = function (body) {
  24280. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24281. var registeredMesh = this._registeredMeshes[index];
  24282. if (registeredMesh.body === body) {
  24283. registeredMesh.body = null;
  24284. }
  24285. }
  24286. };
  24287. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24288. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24289. var registeredMesh = this._registeredMeshes[index];
  24290. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24291. // Get object mass to have a behaviour similar to cannon.js
  24292. var mass = registeredMesh.body.body.massInfo.mass;
  24293. // The force is scaled with the mass of object
  24294. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  24295. return;
  24296. }
  24297. }
  24298. };
  24299. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24300. var body1 = null, body2 = null;
  24301. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24302. var registeredMesh = this._registeredMeshes[index];
  24303. if (registeredMesh.mesh === mesh1) {
  24304. body1 = registeredMesh.body.body;
  24305. }
  24306. else if (registeredMesh.mesh === mesh2) {
  24307. body2 = registeredMesh.body.body;
  24308. }
  24309. }
  24310. if (!body1 || !body2) {
  24311. return false;
  24312. }
  24313. if (!options) {
  24314. options = {};
  24315. }
  24316. new OIMO.Link({
  24317. type: options.type,
  24318. body1: body1,
  24319. body2: body2,
  24320. min: options.min,
  24321. max: options.max,
  24322. axe1: options.axe1,
  24323. axe2: options.axe2,
  24324. pos1: [pivot1.x, pivot1.y, pivot1.z],
  24325. pos2: [pivot2.x, pivot2.y, pivot2.z],
  24326. collision: options.collision,
  24327. spring: options.spring,
  24328. world: this._world
  24329. });
  24330. return true;
  24331. };
  24332. OimoJSPlugin.prototype.dispose = function () {
  24333. this._world.clear();
  24334. while (this._registeredMeshes.length) {
  24335. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24336. }
  24337. };
  24338. OimoJSPlugin.prototype.isSupported = function () {
  24339. return OIMO !== undefined;
  24340. };
  24341. OimoJSPlugin.prototype._getLastShape = function (body) {
  24342. var lastShape = body.shapes;
  24343. while (lastShape.next) {
  24344. lastShape = lastShape.next;
  24345. }
  24346. return lastShape;
  24347. };
  24348. OimoJSPlugin.prototype.runOneStep = function (time) {
  24349. this._world.step();
  24350. // Update the position of all registered meshes
  24351. var i = this._registeredMeshes.length;
  24352. var m;
  24353. while (i--) {
  24354. var body = this._registeredMeshes[i].body.body;
  24355. var mesh = this._registeredMeshes[i].mesh;
  24356. var delta = this._registeredMeshes[i].delta;
  24357. if (!body.sleeping) {
  24358. if (body.shapes.next) {
  24359. var parentShape = this._getLastShape(body);
  24360. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  24361. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  24362. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  24363. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  24364. if (!mesh.rotationQuaternion) {
  24365. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24366. }
  24367. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  24368. mesh.computeWorldMatrix();
  24369. }
  24370. else {
  24371. m = body.getMatrix();
  24372. mtx = BABYLON.Matrix.FromArray(m);
  24373. // Body position
  24374. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  24375. if (!delta) {
  24376. mesh.position.x = bodyX;
  24377. mesh.position.y = bodyY;
  24378. mesh.position.z = bodyZ;
  24379. }
  24380. else {
  24381. mesh.position.x = bodyX + delta.x;
  24382. mesh.position.y = bodyY + delta.y;
  24383. mesh.position.z = bodyZ + delta.z;
  24384. }
  24385. if (!mesh.rotationQuaternion) {
  24386. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24387. }
  24388. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  24389. mesh.computeWorldMatrix();
  24390. }
  24391. }
  24392. }
  24393. };
  24394. return OimoJSPlugin;
  24395. })();
  24396. BABYLON.OimoJSPlugin = OimoJSPlugin;
  24397. })(BABYLON || (BABYLON = {}));
  24398. var BABYLON;
  24399. (function (BABYLON) {
  24400. var PhysicsEngine = (function () {
  24401. function PhysicsEngine(plugin) {
  24402. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  24403. }
  24404. PhysicsEngine.prototype._initialize = function (gravity) {
  24405. this._currentPlugin.initialize();
  24406. this._setGravity(gravity);
  24407. };
  24408. PhysicsEngine.prototype._runOneStep = function (delta) {
  24409. if (delta > 0.1) {
  24410. delta = 0.1;
  24411. }
  24412. else if (delta <= 0) {
  24413. delta = 1.0 / 60.0;
  24414. }
  24415. this._currentPlugin.runOneStep(delta);
  24416. };
  24417. PhysicsEngine.prototype._setGravity = function (gravity) {
  24418. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24419. this._currentPlugin.setGravity(this.gravity);
  24420. };
  24421. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  24422. return this._currentPlugin.registerMesh(mesh, impostor, options);
  24423. };
  24424. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  24425. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  24426. };
  24427. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  24428. this._currentPlugin.unregisterMesh(mesh);
  24429. };
  24430. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  24431. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  24432. };
  24433. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24434. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  24435. };
  24436. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  24437. this._currentPlugin.updateBodyPosition(mesh);
  24438. };
  24439. PhysicsEngine.prototype.dispose = function () {
  24440. this._currentPlugin.dispose();
  24441. };
  24442. PhysicsEngine.prototype.isSupported = function () {
  24443. return this._currentPlugin.isSupported();
  24444. };
  24445. // Statics
  24446. PhysicsEngine.NoImpostor = 0;
  24447. PhysicsEngine.SphereImpostor = 1;
  24448. PhysicsEngine.BoxImpostor = 2;
  24449. PhysicsEngine.PlaneImpostor = 3;
  24450. PhysicsEngine.MeshImpostor = 4;
  24451. PhysicsEngine.CapsuleImpostor = 5;
  24452. PhysicsEngine.ConeImpostor = 6;
  24453. PhysicsEngine.CylinderImpostor = 7;
  24454. PhysicsEngine.ConvexHullImpostor = 8;
  24455. PhysicsEngine.Epsilon = 0.001;
  24456. return PhysicsEngine;
  24457. })();
  24458. BABYLON.PhysicsEngine = PhysicsEngine;
  24459. })(BABYLON || (BABYLON = {}));
  24460. var BABYLON;
  24461. (function (BABYLON) {
  24462. var serializeLight = function (light) {
  24463. var serializationObject = {};
  24464. serializationObject.name = light.name;
  24465. serializationObject.id = light.id;
  24466. serializationObject.tags = BABYLON.Tags.GetTags(light);
  24467. if (light instanceof BABYLON.PointLight) {
  24468. serializationObject.type = 0;
  24469. serializationObject.position = (light).position.asArray();
  24470. }
  24471. else if (light instanceof BABYLON.DirectionalLight) {
  24472. serializationObject.type = 1;
  24473. var directionalLight = light;
  24474. serializationObject.position = directionalLight.position.asArray();
  24475. serializationObject.direction = directionalLight.direction.asArray();
  24476. }
  24477. else if (light instanceof BABYLON.SpotLight) {
  24478. serializationObject.type = 2;
  24479. var spotLight = light;
  24480. serializationObject.position = spotLight.position.asArray();
  24481. serializationObject.direction = spotLight.position.asArray();
  24482. serializationObject.angle = spotLight.angle;
  24483. serializationObject.exponent = spotLight.exponent;
  24484. }
  24485. else if (light instanceof BABYLON.HemisphericLight) {
  24486. serializationObject.type = 3;
  24487. var hemisphericLight = light;
  24488. serializationObject.direction = hemisphericLight.direction.asArray();
  24489. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  24490. }
  24491. if (light.intensity) {
  24492. serializationObject.intensity = light.intensity;
  24493. }
  24494. serializationObject.range = light.range;
  24495. serializationObject.diffuse = light.diffuse.asArray();
  24496. serializationObject.specular = light.specular.asArray();
  24497. return serializationObject;
  24498. };
  24499. var serializeFresnelParameter = function (fresnelParameter) {
  24500. var serializationObject = {};
  24501. serializationObject.isEnabled = fresnelParameter.isEnabled;
  24502. serializationObject.leftColor = fresnelParameter.leftColor;
  24503. serializationObject.rightColor = fresnelParameter.rightColor;
  24504. serializationObject.bias = fresnelParameter.bias;
  24505. serializationObject.power = fresnelParameter.power;
  24506. return serializationObject;
  24507. };
  24508. var serializeAnimation;
  24509. var appendAnimations = function (source, destination) {
  24510. if (source.animations) {
  24511. destination.animations = [];
  24512. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24513. var animation = source.animations[animationIndex];
  24514. destination.animations.push(serializeAnimation(animation));
  24515. }
  24516. }
  24517. };
  24518. var serializeCamera = function (camera) {
  24519. var serializationObject = {};
  24520. serializationObject.name = camera.name;
  24521. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24522. serializationObject.id = camera.id;
  24523. serializationObject.position = camera.position.asArray();
  24524. // Parent
  24525. if (camera.parent) {
  24526. serializationObject.parentId = camera.parent.id;
  24527. }
  24528. serializationObject.fov = camera.fov;
  24529. serializationObject.minZ = camera.minZ;
  24530. serializationObject.maxZ = camera.maxZ;
  24531. serializationObject.inertia = camera.inertia;
  24532. //setting the type
  24533. if (camera instanceof BABYLON.FreeCamera) {
  24534. serializationObject.type = "FreeCamera";
  24535. }
  24536. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24537. serializationObject.type = "ArcRotateCamera";
  24538. }
  24539. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24540. serializationObject.type = "AnaglyphArcRotateCamera";
  24541. }
  24542. else if (camera instanceof BABYLON.GamepadCamera) {
  24543. serializationObject.type = "GamepadCamera";
  24544. }
  24545. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24546. serializationObject.type = "AnaglyphFreeCamera";
  24547. }
  24548. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24549. serializationObject.type = "DeviceOrientationCamera";
  24550. }
  24551. else if (camera instanceof BABYLON.FollowCamera) {
  24552. serializationObject.type = "FollowCamera";
  24553. }
  24554. else if (camera instanceof BABYLON.TouchCamera) {
  24555. serializationObject.type = "TouchCamera";
  24556. }
  24557. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24558. serializationObject.type = "VirtualJoysticksCamera";
  24559. }
  24560. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24561. serializationObject.type = "WebVRFreeCamera";
  24562. }
  24563. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24564. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24565. }
  24566. //special properties of specific cameras
  24567. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24568. var arcCamera = camera;
  24569. serializationObject.alpha = arcCamera.alpha;
  24570. serializationObject.beta = arcCamera.beta;
  24571. serializationObject.radius = arcCamera.radius;
  24572. if (arcCamera.target && arcCamera.target.id) {
  24573. serializationObject.lockedTargetId = arcCamera.target.id;
  24574. }
  24575. }
  24576. else if (camera instanceof BABYLON.FollowCamera) {
  24577. var followCam = camera;
  24578. serializationObject.radius = followCam.radius;
  24579. serializationObject.heightOffset = followCam.heightOffset;
  24580. serializationObject.rotationOffset = followCam.rotationOffset;
  24581. }
  24582. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24583. //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.
  24584. if (camera['_interaxialDistance'] !== undefined) {
  24585. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24586. }
  24587. }
  24588. //general properties that not all cameras have. The [] is due to typescript's type safety
  24589. if (camera['speed'] !== undefined) {
  24590. serializationObject.speed = camera['speed'];
  24591. }
  24592. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24593. serializationObject.target = camera['target'].asArray();
  24594. }
  24595. // Target
  24596. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24597. serializationObject.rotation = camera['rotation'].asArray();
  24598. }
  24599. // Locked target
  24600. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24601. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24602. }
  24603. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24604. serializationObject.applyGravity = camera['applyGravity'] || false;
  24605. if (camera['ellipsoid']) {
  24606. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24607. }
  24608. // Animations
  24609. appendAnimations(camera, serializationObject);
  24610. // Layer mask
  24611. serializationObject.layerMask = camera.layerMask;
  24612. return serializationObject;
  24613. };
  24614. serializeAnimation = function (animation) {
  24615. var serializationObject = {};
  24616. serializationObject.name = animation.name;
  24617. serializationObject.property = animation.targetProperty;
  24618. serializationObject.framePerSecond = animation.framePerSecond;
  24619. serializationObject.dataType = animation.dataType;
  24620. serializationObject.loopBehavior = animation.loopMode;
  24621. var dataType = animation.dataType;
  24622. serializationObject.keys = [];
  24623. var keys = animation.getKeys();
  24624. for (var index = 0; index < keys.length; index++) {
  24625. var animationKey = keys[index];
  24626. var key = {};
  24627. key.frame = animationKey.frame;
  24628. switch (dataType) {
  24629. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24630. key.values = [animationKey.value];
  24631. break;
  24632. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24633. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24634. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24635. key.values = animationKey.value.asArray();
  24636. break;
  24637. }
  24638. serializationObject.keys.push(key);
  24639. }
  24640. return serializationObject;
  24641. };
  24642. var serializeMultiMaterial = function (material) {
  24643. var serializationObject = {};
  24644. serializationObject.name = material.name;
  24645. serializationObject.id = material.id;
  24646. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24647. serializationObject.materials = [];
  24648. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24649. var subMat = material.subMaterials[matIndex];
  24650. if (subMat) {
  24651. serializationObject.materials.push(subMat.id);
  24652. }
  24653. else {
  24654. serializationObject.materials.push(null);
  24655. }
  24656. }
  24657. return serializationObject;
  24658. };
  24659. var serializeTexture;
  24660. var serializeMaterial = function (material) {
  24661. var serializationObject = {};
  24662. serializationObject.name = material.name;
  24663. serializationObject.ambient = material.ambientColor.asArray();
  24664. serializationObject.diffuse = material.diffuseColor.asArray();
  24665. serializationObject.specular = material.specularColor.asArray();
  24666. serializationObject.specularPower = material.specularPower;
  24667. serializationObject.emissive = material.emissiveColor.asArray();
  24668. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24669. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24670. serializationObject.alpha = material.alpha;
  24671. serializationObject.id = material.id;
  24672. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24673. serializationObject.backFaceCulling = material.backFaceCulling;
  24674. if (material.diffuseTexture) {
  24675. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24676. }
  24677. if (material.diffuseFresnelParameters) {
  24678. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24679. }
  24680. if (material.ambientTexture) {
  24681. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24682. }
  24683. if (material.opacityTexture) {
  24684. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24685. }
  24686. if (material.opacityFresnelParameters) {
  24687. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24688. }
  24689. if (material.reflectionTexture) {
  24690. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24691. }
  24692. if (material.reflectionFresnelParameters) {
  24693. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24694. }
  24695. if (material.emissiveTexture) {
  24696. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24697. }
  24698. if (material.lightmapTexture) {
  24699. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  24700. serializationObject.lightmapThreshold = material.lightmapThreshold;
  24701. }
  24702. if (material.emissiveFresnelParameters) {
  24703. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24704. }
  24705. if (material.specularTexture) {
  24706. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24707. }
  24708. if (material.bumpTexture) {
  24709. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24710. }
  24711. return serializationObject;
  24712. };
  24713. serializeTexture = function (texture) {
  24714. var serializationObject = {};
  24715. if (!texture.name) {
  24716. return null;
  24717. }
  24718. if (texture instanceof BABYLON.CubeTexture) {
  24719. serializationObject.name = texture.name;
  24720. serializationObject.hasAlpha = texture.hasAlpha;
  24721. serializationObject.isCube = true;
  24722. serializationObject.level = texture.level;
  24723. serializationObject.coordinatesMode = texture.coordinatesMode;
  24724. return serializationObject;
  24725. }
  24726. var index;
  24727. if (texture instanceof BABYLON.MirrorTexture) {
  24728. var mirrorTexture = texture;
  24729. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24730. serializationObject.renderList = [];
  24731. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24732. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24733. }
  24734. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24735. }
  24736. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24737. var renderTargetTexture = texture;
  24738. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24739. serializationObject.renderList = [];
  24740. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24741. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24742. }
  24743. }
  24744. var regularTexture = texture;
  24745. serializationObject.name = texture.name;
  24746. serializationObject.hasAlpha = texture.hasAlpha;
  24747. serializationObject.level = texture.level;
  24748. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24749. serializationObject.coordinatesMode = texture.coordinatesMode;
  24750. serializationObject.uOffset = regularTexture.uOffset;
  24751. serializationObject.vOffset = regularTexture.vOffset;
  24752. serializationObject.uScale = regularTexture.uScale;
  24753. serializationObject.vScale = regularTexture.vScale;
  24754. serializationObject.uAng = regularTexture.uAng;
  24755. serializationObject.vAng = regularTexture.vAng;
  24756. serializationObject.wAng = regularTexture.wAng;
  24757. serializationObject.wrapU = texture.wrapU;
  24758. serializationObject.wrapV = texture.wrapV;
  24759. // Animations
  24760. appendAnimations(texture, serializationObject);
  24761. return serializationObject;
  24762. };
  24763. var serializeSkeleton = function (skeleton) {
  24764. var serializationObject = {};
  24765. serializationObject.name = skeleton.name;
  24766. serializationObject.id = skeleton.id;
  24767. serializationObject.bones = [];
  24768. for (var index = 0; index < skeleton.bones.length; index++) {
  24769. var bone = skeleton.bones[index];
  24770. var serializedBone = {
  24771. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24772. name: bone.name,
  24773. matrix: bone.getLocalMatrix().toArray()
  24774. };
  24775. serializationObject.bones.push(serializedBone);
  24776. if (bone.animations && bone.animations.length > 0) {
  24777. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24778. }
  24779. }
  24780. return serializationObject;
  24781. };
  24782. var serializeParticleSystem = function (particleSystem) {
  24783. var serializationObject = {};
  24784. serializationObject.emitterId = particleSystem.emitter.id;
  24785. serializationObject.capacity = particleSystem.getCapacity();
  24786. if (particleSystem.particleTexture) {
  24787. serializationObject.textureName = particleSystem.particleTexture.name;
  24788. }
  24789. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24790. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24791. serializationObject.minSize = particleSystem.minSize;
  24792. serializationObject.maxSize = particleSystem.maxSize;
  24793. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24794. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24795. serializationObject.emitRate = particleSystem.emitRate;
  24796. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24797. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24798. serializationObject.gravity = particleSystem.gravity.asArray();
  24799. serializationObject.direction1 = particleSystem.direction1.asArray();
  24800. serializationObject.direction2 = particleSystem.direction2.asArray();
  24801. serializationObject.color1 = particleSystem.color1.asArray();
  24802. serializationObject.color2 = particleSystem.color2.asArray();
  24803. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24804. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24805. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24806. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24807. serializationObject.blendMode = particleSystem.blendMode;
  24808. return serializationObject;
  24809. };
  24810. var serializeLensFlareSystem = function (lensFlareSystem) {
  24811. var serializationObject = {};
  24812. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24813. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24814. serializationObject.flares = [];
  24815. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24816. var flare = lensFlareSystem.lensFlares[index];
  24817. serializationObject.flares.push({
  24818. size: flare.size,
  24819. position: flare.position,
  24820. color: flare.color.asArray(),
  24821. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24822. });
  24823. }
  24824. return serializationObject;
  24825. };
  24826. var serializeShadowGenerator = function (light) {
  24827. var serializationObject = {};
  24828. var shadowGenerator = light.getShadowGenerator();
  24829. serializationObject.lightId = light.id;
  24830. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24831. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24832. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24833. serializationObject.renderList = [];
  24834. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24835. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24836. serializationObject.renderList.push(mesh.id);
  24837. }
  24838. return serializationObject;
  24839. };
  24840. var serializedGeometries = [];
  24841. var serializeVertexData;
  24842. var serializeTorusKnot;
  24843. var serializePlane;
  24844. var serializeGround;
  24845. var serializeTorus;
  24846. var serializeCylinder;
  24847. var serializeSphere;
  24848. var serializeBox;
  24849. var serializeGeometry = function (geometry, serializationGeometries) {
  24850. if (serializedGeometries[geometry.id]) {
  24851. return;
  24852. }
  24853. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24854. serializationGeometries.boxes.push(serializeBox(geometry));
  24855. }
  24856. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24857. serializationGeometries.spheres.push(serializeSphere(geometry));
  24858. }
  24859. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24860. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24861. }
  24862. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24863. serializationGeometries.toruses.push(serializeTorus(geometry));
  24864. }
  24865. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24866. serializationGeometries.grounds.push(serializeGround(geometry));
  24867. }
  24868. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24869. serializationGeometries.planes.push(serializePlane(geometry));
  24870. }
  24871. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24872. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24873. }
  24874. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24875. throw new Error("Unknown primitive type");
  24876. }
  24877. else {
  24878. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24879. }
  24880. serializedGeometries[geometry.id] = true;
  24881. };
  24882. var serializeGeometryBase = function (geometry) {
  24883. var serializationObject = {};
  24884. serializationObject.id = geometry.id;
  24885. if (BABYLON.Tags.HasTags(geometry)) {
  24886. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24887. }
  24888. return serializationObject;
  24889. };
  24890. serializeVertexData = function (vertexData) {
  24891. var serializationObject = serializeGeometryBase(vertexData);
  24892. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24893. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24894. }
  24895. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24896. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24897. }
  24898. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24899. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24900. }
  24901. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24902. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24903. }
  24904. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24905. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24906. }
  24907. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24908. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24909. }
  24910. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24911. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24912. }
  24913. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24914. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24915. }
  24916. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24917. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24918. }
  24919. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24920. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24921. serializationObject.matricesIndices._isExpanded = true;
  24922. }
  24923. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24924. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24925. }
  24926. serializationObject.indices = vertexData.getIndices();
  24927. return serializationObject;
  24928. };
  24929. var serializePrimitive = function (primitive) {
  24930. var serializationObject = serializeGeometryBase(primitive);
  24931. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24932. return serializationObject;
  24933. };
  24934. serializeBox = function (box) {
  24935. var serializationObject = serializePrimitive(box);
  24936. serializationObject.size = box.size;
  24937. return serializationObject;
  24938. };
  24939. serializeSphere = function (sphere) {
  24940. var serializationObject = serializePrimitive(sphere);
  24941. serializationObject.segments = sphere.segments;
  24942. serializationObject.diameter = sphere.diameter;
  24943. return serializationObject;
  24944. };
  24945. serializeCylinder = function (cylinder) {
  24946. var serializationObject = serializePrimitive(cylinder);
  24947. serializationObject.height = cylinder.height;
  24948. serializationObject.diameterTop = cylinder.diameterTop;
  24949. serializationObject.diameterBottom = cylinder.diameterBottom;
  24950. serializationObject.tessellation = cylinder.tessellation;
  24951. return serializationObject;
  24952. };
  24953. serializeTorus = function (torus) {
  24954. var serializationObject = serializePrimitive(torus);
  24955. serializationObject.diameter = torus.diameter;
  24956. serializationObject.thickness = torus.thickness;
  24957. serializationObject.tessellation = torus.tessellation;
  24958. return serializationObject;
  24959. };
  24960. serializeGround = function (ground) {
  24961. var serializationObject = serializePrimitive(ground);
  24962. serializationObject.width = ground.width;
  24963. serializationObject.height = ground.height;
  24964. serializationObject.subdivisions = ground.subdivisions;
  24965. return serializationObject;
  24966. };
  24967. serializePlane = function (plane) {
  24968. var serializationObject = serializePrimitive(plane);
  24969. serializationObject.size = plane.size;
  24970. return serializationObject;
  24971. };
  24972. serializeTorusKnot = function (torusKnot) {
  24973. var serializationObject = serializePrimitive(torusKnot);
  24974. serializationObject.radius = torusKnot.radius;
  24975. serializationObject.tube = torusKnot.tube;
  24976. serializationObject.radialSegments = torusKnot.radialSegments;
  24977. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24978. serializationObject.p = torusKnot.p;
  24979. serializationObject.q = torusKnot.q;
  24980. return serializationObject;
  24981. };
  24982. var serializeMesh = function (mesh, serializationScene) {
  24983. var serializationObject = {};
  24984. serializationObject.name = mesh.name;
  24985. serializationObject.id = mesh.id;
  24986. if (BABYLON.Tags.HasTags(mesh)) {
  24987. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24988. }
  24989. serializationObject.position = mesh.position.asArray();
  24990. if (mesh.rotationQuaternion) {
  24991. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24992. }
  24993. else if (mesh.rotation) {
  24994. serializationObject.rotation = mesh.rotation.asArray();
  24995. }
  24996. serializationObject.scaling = mesh.scaling.asArray();
  24997. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24998. serializationObject.isEnabled = mesh.isEnabled();
  24999. serializationObject.isVisible = mesh.isVisible;
  25000. serializationObject.infiniteDistance = mesh.infiniteDistance;
  25001. serializationObject.pickable = mesh.isPickable;
  25002. serializationObject.receiveShadows = mesh.receiveShadows;
  25003. serializationObject.billboardMode = mesh.billboardMode;
  25004. serializationObject.visibility = mesh.visibility;
  25005. serializationObject.checkCollisions = mesh.checkCollisions;
  25006. // Parent
  25007. if (mesh.parent) {
  25008. serializationObject.parentId = mesh.parent.id;
  25009. }
  25010. // Geometry
  25011. var geometry = mesh._geometry;
  25012. if (geometry) {
  25013. var geometryId = geometry.id;
  25014. serializationObject.geometryId = geometryId;
  25015. if (!mesh.getScene().getGeometryByID(geometryId)) {
  25016. // 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
  25017. serializeGeometry(geometry, serializationScene.geometries);
  25018. }
  25019. // SubMeshes
  25020. serializationObject.subMeshes = [];
  25021. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25022. var subMesh = mesh.subMeshes[subIndex];
  25023. serializationObject.subMeshes.push({
  25024. materialIndex: subMesh.materialIndex,
  25025. verticesStart: subMesh.verticesStart,
  25026. verticesCount: subMesh.verticesCount,
  25027. indexStart: subMesh.indexStart,
  25028. indexCount: subMesh.indexCount
  25029. });
  25030. }
  25031. }
  25032. // Material
  25033. if (mesh.material) {
  25034. serializationObject.materialId = mesh.material.id;
  25035. }
  25036. else {
  25037. mesh.material = null;
  25038. }
  25039. // Skeleton
  25040. if (mesh.skeleton) {
  25041. serializationObject.skeletonId = mesh.skeleton.id;
  25042. }
  25043. // Physics
  25044. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  25045. serializationObject.physicsMass = mesh.getPhysicsMass();
  25046. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  25047. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  25048. switch (mesh.getPhysicsImpostor()) {
  25049. case BABYLON.PhysicsEngine.BoxImpostor:
  25050. serializationObject.physicsImpostor = 1;
  25051. break;
  25052. case BABYLON.PhysicsEngine.SphereImpostor:
  25053. serializationObject.physicsImpostor = 2;
  25054. break;
  25055. }
  25056. }
  25057. // Instances
  25058. serializationObject.instances = [];
  25059. for (var index = 0; index < mesh.instances.length; index++) {
  25060. var instance = mesh.instances[index];
  25061. var serializationInstance = {
  25062. name: instance.name,
  25063. position: instance.position.asArray(),
  25064. rotation: instance.rotation.asArray(),
  25065. rotationQuaternion: instance.rotationQuaternion.asArray(),
  25066. scaling: instance.scaling.asArray()
  25067. };
  25068. serializationObject.instances.push(serializationInstance);
  25069. // Animations
  25070. appendAnimations(instance, serializationInstance);
  25071. }
  25072. // Animations
  25073. appendAnimations(mesh, serializationObject);
  25074. // Layer mask
  25075. serializationObject.layerMask = mesh.layerMask;
  25076. return serializationObject;
  25077. };
  25078. var finalizeSingleMesh = function (mesh, serializationObject) {
  25079. //only works if the mesh is already loaded
  25080. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  25081. //serialize material
  25082. if (mesh.material) {
  25083. if (mesh.material instanceof BABYLON.StandardMaterial) {
  25084. serializationObject.materials = serializationObject.materials || [];
  25085. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  25086. serializationObject.materials.push(serializeMaterial(mesh.material));
  25087. }
  25088. }
  25089. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  25090. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  25091. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  25092. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  25093. }
  25094. }
  25095. }
  25096. //serialize geometry
  25097. var geometry = mesh._geometry;
  25098. if (geometry) {
  25099. if (!serializationObject.geometries) {
  25100. serializationObject.geometries = {};
  25101. serializationObject.geometries.boxes = [];
  25102. serializationObject.geometries.spheres = [];
  25103. serializationObject.geometries.cylinders = [];
  25104. serializationObject.geometries.toruses = [];
  25105. serializationObject.geometries.grounds = [];
  25106. serializationObject.geometries.planes = [];
  25107. serializationObject.geometries.torusKnots = [];
  25108. serializationObject.geometries.vertexData = [];
  25109. }
  25110. serializeGeometry(geometry, serializationObject.geometries);
  25111. }
  25112. // Skeletons
  25113. if (mesh.skeleton) {
  25114. serializationObject.skeletons = serializationObject.skeletons || [];
  25115. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  25116. }
  25117. //serialize the actual mesh
  25118. serializationObject.meshes = serializationObject.meshes || [];
  25119. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  25120. }
  25121. };
  25122. var SceneSerializer = (function () {
  25123. function SceneSerializer() {
  25124. }
  25125. SceneSerializer.Serialize = function (scene) {
  25126. var serializationObject = {};
  25127. // Scene
  25128. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  25129. serializationObject.autoClear = scene.autoClear;
  25130. serializationObject.clearColor = scene.clearColor.asArray();
  25131. serializationObject.ambientColor = scene.ambientColor.asArray();
  25132. serializationObject.gravity = scene.gravity.asArray();
  25133. // Fog
  25134. if (scene.fogMode && scene.fogMode !== 0) {
  25135. serializationObject.fogMode = scene.fogMode;
  25136. serializationObject.fogColor = scene.fogColor.asArray();
  25137. serializationObject.fogStart = scene.fogStart;
  25138. serializationObject.fogEnd = scene.fogEnd;
  25139. serializationObject.fogDensity = scene.fogDensity;
  25140. }
  25141. // Lights
  25142. serializationObject.lights = [];
  25143. var index;
  25144. var light;
  25145. for (index = 0; index < scene.lights.length; index++) {
  25146. light = scene.lights[index];
  25147. serializationObject.lights.push(serializeLight(light));
  25148. }
  25149. // Cameras
  25150. serializationObject.cameras = [];
  25151. for (index = 0; index < scene.cameras.length; index++) {
  25152. var camera = scene.cameras[index];
  25153. serializationObject.cameras.push(serializeCamera(camera));
  25154. }
  25155. if (scene.activeCamera) {
  25156. serializationObject.activeCameraID = scene.activeCamera.id;
  25157. }
  25158. // Materials
  25159. serializationObject.materials = [];
  25160. serializationObject.multiMaterials = [];
  25161. var material;
  25162. for (index = 0; index < scene.materials.length; index++) {
  25163. material = scene.materials[index];
  25164. serializationObject.materials.push(serializeMaterial(material));
  25165. }
  25166. // MultiMaterials
  25167. serializationObject.multiMaterials = [];
  25168. for (index = 0; index < scene.multiMaterials.length; index++) {
  25169. var multiMaterial = scene.multiMaterials[index];
  25170. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  25171. }
  25172. for (index = 0; index < scene.materials.length; index++) {
  25173. material = scene.materials[index];
  25174. if (material instanceof BABYLON.StandardMaterial) {
  25175. serializationObject.materials.push(serializeMaterial(material));
  25176. }
  25177. else if (material instanceof BABYLON.MultiMaterial) {
  25178. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  25179. }
  25180. }
  25181. // Skeletons
  25182. serializationObject.skeletons = [];
  25183. for (index = 0; index < scene.skeletons.length; index++) {
  25184. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  25185. }
  25186. // Geometries
  25187. serializationObject.geometries = {};
  25188. serializationObject.geometries.boxes = [];
  25189. serializationObject.geometries.spheres = [];
  25190. serializationObject.geometries.cylinders = [];
  25191. serializationObject.geometries.toruses = [];
  25192. serializationObject.geometries.grounds = [];
  25193. serializationObject.geometries.planes = [];
  25194. serializationObject.geometries.torusKnots = [];
  25195. serializationObject.geometries.vertexData = [];
  25196. serializedGeometries = [];
  25197. var geometries = scene.getGeometries();
  25198. for (index = 0; index < geometries.length; index++) {
  25199. var geometry = geometries[index];
  25200. if (geometry.isReady()) {
  25201. serializeGeometry(geometry, serializationObject.geometries);
  25202. }
  25203. }
  25204. // Meshes
  25205. serializationObject.meshes = [];
  25206. for (index = 0; index < scene.meshes.length; index++) {
  25207. var abstractMesh = scene.meshes[index];
  25208. if (abstractMesh instanceof BABYLON.Mesh) {
  25209. var mesh = abstractMesh;
  25210. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  25211. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  25212. }
  25213. }
  25214. }
  25215. // Particles Systems
  25216. serializationObject.particleSystems = [];
  25217. for (index = 0; index < scene.particleSystems.length; index++) {
  25218. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  25219. }
  25220. // Lens flares
  25221. serializationObject.lensFlareSystems = [];
  25222. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  25223. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  25224. }
  25225. // Shadows
  25226. serializationObject.shadowGenerators = [];
  25227. for (index = 0; index < scene.lights.length; index++) {
  25228. light = scene.lights[index];
  25229. if (light.getShadowGenerator()) {
  25230. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  25231. }
  25232. }
  25233. return serializationObject;
  25234. };
  25235. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  25236. if (withParents === void 0) { withParents = false; }
  25237. if (withChildren === void 0) { withChildren = false; }
  25238. var serializationObject = {};
  25239. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  25240. if (withParents || withChildren) {
  25241. //deliberate for loop! not for each, appended should be processed as well.
  25242. for (var i = 0; i < toSerialize.length; ++i) {
  25243. if (withChildren) {
  25244. toSerialize[i].getDescendants().forEach(function (node) {
  25245. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  25246. toSerialize.push(node);
  25247. }
  25248. });
  25249. }
  25250. //make sure the array doesn't contain the object already
  25251. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  25252. toSerialize.push(toSerialize[i].parent);
  25253. }
  25254. }
  25255. }
  25256. toSerialize.forEach(function (mesh) {
  25257. finalizeSingleMesh(mesh, serializationObject);
  25258. });
  25259. return serializationObject;
  25260. };
  25261. return SceneSerializer;
  25262. })();
  25263. BABYLON.SceneSerializer = SceneSerializer;
  25264. })(BABYLON || (BABYLON = {}));
  25265. var BABYLON;
  25266. (function (BABYLON) {
  25267. // Unique ID when we import meshes from Babylon to CSG
  25268. var currentCSGMeshId = 0;
  25269. // # class Vertex
  25270. // Represents a vertex of a polygon. Use your own vertex class instead of this
  25271. // one to provide additional features like texture coordinates and vertex
  25272. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  25273. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  25274. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  25275. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  25276. // is not used anywhere else.
  25277. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  25278. var Vertex = (function () {
  25279. function Vertex(pos, normal, uv) {
  25280. this.pos = pos;
  25281. this.normal = normal;
  25282. this.uv = uv;
  25283. }
  25284. Vertex.prototype.clone = function () {
  25285. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  25286. };
  25287. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  25288. // orientation of a polygon is flipped.
  25289. Vertex.prototype.flip = function () {
  25290. this.normal = this.normal.scale(-1);
  25291. };
  25292. // Create a new vertex between this vertex and `other` by linearly
  25293. // interpolating all properties using a parameter of `t`. Subclasses should
  25294. // override this to interpolate additional properties.
  25295. Vertex.prototype.interpolate = function (other, t) {
  25296. 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));
  25297. };
  25298. return Vertex;
  25299. })();
  25300. // # class Plane
  25301. // Represents a plane in 3D space.
  25302. var Plane = (function () {
  25303. function Plane(normal, w) {
  25304. this.normal = normal;
  25305. this.w = w;
  25306. }
  25307. Plane.FromPoints = function (a, b, c) {
  25308. var v0 = c.subtract(a);
  25309. var v1 = b.subtract(a);
  25310. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  25311. return null;
  25312. }
  25313. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  25314. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  25315. };
  25316. Plane.prototype.clone = function () {
  25317. return new Plane(this.normal.clone(), this.w);
  25318. };
  25319. Plane.prototype.flip = function () {
  25320. this.normal.scaleInPlace(-1);
  25321. this.w = -this.w;
  25322. };
  25323. // Split `polygon` by this plane if needed, then put the polygon or polygon
  25324. // fragments in the appropriate lists. Coplanar polygons go into either
  25325. // `coplanarFront` or `coplanarBack` depending on their orientation with
  25326. // respect to this plane. Polygons in front or in back of this plane go into
  25327. // either `front` or `back`.
  25328. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  25329. var COPLANAR = 0;
  25330. var FRONT = 1;
  25331. var BACK = 2;
  25332. var SPANNING = 3;
  25333. // Classify each point as well as the entire polygon into one of the above
  25334. // four classes.
  25335. var polygonType = 0;
  25336. var types = [];
  25337. for (var i = 0; i < polygon.vertices.length; i++) {
  25338. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  25339. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  25340. polygonType |= type;
  25341. types.push(type);
  25342. }
  25343. // Put the polygon in the correct list, splitting it when necessary.
  25344. switch (polygonType) {
  25345. case COPLANAR:
  25346. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  25347. break;
  25348. case FRONT:
  25349. front.push(polygon);
  25350. break;
  25351. case BACK:
  25352. back.push(polygon);
  25353. break;
  25354. case SPANNING:
  25355. var f = [], b = [];
  25356. for (i = 0; i < polygon.vertices.length; i++) {
  25357. var j = (i + 1) % polygon.vertices.length;
  25358. var ti = types[i], tj = types[j];
  25359. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  25360. if (ti != BACK)
  25361. f.push(vi);
  25362. if (ti != FRONT)
  25363. b.push(ti != BACK ? vi.clone() : vi);
  25364. if ((ti | tj) == SPANNING) {
  25365. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  25366. var v = vi.interpolate(vj, t);
  25367. f.push(v);
  25368. b.push(v.clone());
  25369. }
  25370. }
  25371. if (f.length >= 3) {
  25372. var poly = new Polygon(f, polygon.shared);
  25373. if (poly.plane)
  25374. front.push(poly);
  25375. }
  25376. if (b.length >= 3) {
  25377. poly = new Polygon(b, polygon.shared);
  25378. if (poly.plane)
  25379. back.push(poly);
  25380. }
  25381. break;
  25382. }
  25383. };
  25384. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  25385. // point is on the plane.
  25386. Plane.EPSILON = 1e-5;
  25387. return Plane;
  25388. })();
  25389. // # class Polygon
  25390. // Represents a convex polygon. The vertices used to initialize a polygon must
  25391. // be coplanar and form a convex loop.
  25392. //
  25393. // Each convex polygon has a `shared` property, which is shared between all
  25394. // polygons that are clones of each other or were split from the same polygon.
  25395. // This can be used to define per-polygon properties (such as surface color).
  25396. var Polygon = (function () {
  25397. function Polygon(vertices, shared) {
  25398. this.vertices = vertices;
  25399. this.shared = shared;
  25400. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  25401. }
  25402. Polygon.prototype.clone = function () {
  25403. var vertices = this.vertices.map(function (v) { return v.clone(); });
  25404. return new Polygon(vertices, this.shared);
  25405. };
  25406. Polygon.prototype.flip = function () {
  25407. this.vertices.reverse().map(function (v) { v.flip(); });
  25408. this.plane.flip();
  25409. };
  25410. return Polygon;
  25411. })();
  25412. // # class Node
  25413. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  25414. // by picking a polygon to split along. That polygon (and all other coplanar
  25415. // polygons) are added directly to that node and the other polygons are added to
  25416. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  25417. // no distinction between internal and leaf nodes.
  25418. var Node = (function () {
  25419. function Node(polygons) {
  25420. this.plane = null;
  25421. this.front = null;
  25422. this.back = null;
  25423. this.polygons = [];
  25424. if (polygons) {
  25425. this.build(polygons);
  25426. }
  25427. }
  25428. Node.prototype.clone = function () {
  25429. var node = new Node();
  25430. node.plane = this.plane && this.plane.clone();
  25431. node.front = this.front && this.front.clone();
  25432. node.back = this.back && this.back.clone();
  25433. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  25434. return node;
  25435. };
  25436. // Convert solid space to empty space and empty space to solid space.
  25437. Node.prototype.invert = function () {
  25438. for (var i = 0; i < this.polygons.length; i++) {
  25439. this.polygons[i].flip();
  25440. }
  25441. if (this.plane) {
  25442. this.plane.flip();
  25443. }
  25444. if (this.front) {
  25445. this.front.invert();
  25446. }
  25447. if (this.back) {
  25448. this.back.invert();
  25449. }
  25450. var temp = this.front;
  25451. this.front = this.back;
  25452. this.back = temp;
  25453. };
  25454. // Recursively remove all polygons in `polygons` that are inside this BSP
  25455. // tree.
  25456. Node.prototype.clipPolygons = function (polygons) {
  25457. if (!this.plane)
  25458. return polygons.slice();
  25459. var front = [], back = [];
  25460. for (var i = 0; i < polygons.length; i++) {
  25461. this.plane.splitPolygon(polygons[i], front, back, front, back);
  25462. }
  25463. if (this.front) {
  25464. front = this.front.clipPolygons(front);
  25465. }
  25466. if (this.back) {
  25467. back = this.back.clipPolygons(back);
  25468. }
  25469. else {
  25470. back = [];
  25471. }
  25472. return front.concat(back);
  25473. };
  25474. // Remove all polygons in this BSP tree that are inside the other BSP tree
  25475. // `bsp`.
  25476. Node.prototype.clipTo = function (bsp) {
  25477. this.polygons = bsp.clipPolygons(this.polygons);
  25478. if (this.front)
  25479. this.front.clipTo(bsp);
  25480. if (this.back)
  25481. this.back.clipTo(bsp);
  25482. };
  25483. // Return a list of all polygons in this BSP tree.
  25484. Node.prototype.allPolygons = function () {
  25485. var polygons = this.polygons.slice();
  25486. if (this.front)
  25487. polygons = polygons.concat(this.front.allPolygons());
  25488. if (this.back)
  25489. polygons = polygons.concat(this.back.allPolygons());
  25490. return polygons;
  25491. };
  25492. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  25493. // new polygons are filtered down to the bottom of the tree and become new
  25494. // nodes there. Each set of polygons is partitioned using the first polygon
  25495. // (no heuristic is used to pick a good split).
  25496. Node.prototype.build = function (polygons) {
  25497. if (!polygons.length)
  25498. return;
  25499. if (!this.plane)
  25500. this.plane = polygons[0].plane.clone();
  25501. var front = [], back = [];
  25502. for (var i = 0; i < polygons.length; i++) {
  25503. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  25504. }
  25505. if (front.length) {
  25506. if (!this.front)
  25507. this.front = new Node();
  25508. this.front.build(front);
  25509. }
  25510. if (back.length) {
  25511. if (!this.back)
  25512. this.back = new Node();
  25513. this.back.build(back);
  25514. }
  25515. };
  25516. return Node;
  25517. })();
  25518. var CSG = (function () {
  25519. function CSG() {
  25520. this.polygons = new Array();
  25521. }
  25522. // Convert BABYLON.Mesh to BABYLON.CSG
  25523. CSG.FromMesh = function (mesh) {
  25524. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25525. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25526. if (mesh instanceof BABYLON.Mesh) {
  25527. mesh.computeWorldMatrix(true);
  25528. matrix = mesh.getWorldMatrix();
  25529. meshPosition = mesh.position.clone();
  25530. meshRotation = mesh.rotation.clone();
  25531. if (mesh.rotationQuaternion) {
  25532. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25533. }
  25534. meshScaling = mesh.scaling.clone();
  25535. }
  25536. else {
  25537. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25538. }
  25539. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25540. var subMeshes = mesh.subMeshes;
  25541. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25542. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25543. vertices = [];
  25544. for (var j = 0; j < 3; j++) {
  25545. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25546. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25547. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25548. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25549. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25550. vertex = new Vertex(position, normal, uv);
  25551. vertices.push(vertex);
  25552. }
  25553. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25554. // To handle the case of degenerated triangle
  25555. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25556. if (polygon.plane)
  25557. polygons.push(polygon);
  25558. }
  25559. }
  25560. var csg = CSG.FromPolygons(polygons);
  25561. csg.matrix = matrix;
  25562. csg.position = meshPosition;
  25563. csg.rotation = meshRotation;
  25564. csg.scaling = meshScaling;
  25565. csg.rotationQuaternion = meshRotationQuaternion;
  25566. currentCSGMeshId++;
  25567. return csg;
  25568. };
  25569. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25570. CSG.FromPolygons = function (polygons) {
  25571. var csg = new CSG();
  25572. csg.polygons = polygons;
  25573. return csg;
  25574. };
  25575. CSG.prototype.clone = function () {
  25576. var csg = new CSG();
  25577. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25578. csg.copyTransformAttributes(this);
  25579. return csg;
  25580. };
  25581. CSG.prototype.toPolygons = function () {
  25582. return this.polygons;
  25583. };
  25584. CSG.prototype.union = function (csg) {
  25585. var a = new Node(this.clone().polygons);
  25586. var b = new Node(csg.clone().polygons);
  25587. a.clipTo(b);
  25588. b.clipTo(a);
  25589. b.invert();
  25590. b.clipTo(a);
  25591. b.invert();
  25592. a.build(b.allPolygons());
  25593. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25594. };
  25595. CSG.prototype.unionInPlace = function (csg) {
  25596. var a = new Node(this.polygons);
  25597. var b = new Node(csg.polygons);
  25598. a.clipTo(b);
  25599. b.clipTo(a);
  25600. b.invert();
  25601. b.clipTo(a);
  25602. b.invert();
  25603. a.build(b.allPolygons());
  25604. this.polygons = a.allPolygons();
  25605. };
  25606. CSG.prototype.subtract = function (csg) {
  25607. var a = new Node(this.clone().polygons);
  25608. var b = new Node(csg.clone().polygons);
  25609. a.invert();
  25610. a.clipTo(b);
  25611. b.clipTo(a);
  25612. b.invert();
  25613. b.clipTo(a);
  25614. b.invert();
  25615. a.build(b.allPolygons());
  25616. a.invert();
  25617. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25618. };
  25619. CSG.prototype.subtractInPlace = function (csg) {
  25620. var a = new Node(this.polygons);
  25621. var b = new Node(csg.polygons);
  25622. a.invert();
  25623. a.clipTo(b);
  25624. b.clipTo(a);
  25625. b.invert();
  25626. b.clipTo(a);
  25627. b.invert();
  25628. a.build(b.allPolygons());
  25629. a.invert();
  25630. this.polygons = a.allPolygons();
  25631. };
  25632. CSG.prototype.intersect = function (csg) {
  25633. var a = new Node(this.clone().polygons);
  25634. var b = new Node(csg.clone().polygons);
  25635. a.invert();
  25636. b.clipTo(a);
  25637. b.invert();
  25638. a.clipTo(b);
  25639. b.clipTo(a);
  25640. a.build(b.allPolygons());
  25641. a.invert();
  25642. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25643. };
  25644. CSG.prototype.intersectInPlace = function (csg) {
  25645. var a = new Node(this.polygons);
  25646. var b = new Node(csg.polygons);
  25647. a.invert();
  25648. b.clipTo(a);
  25649. b.invert();
  25650. a.clipTo(b);
  25651. b.clipTo(a);
  25652. a.build(b.allPolygons());
  25653. a.invert();
  25654. this.polygons = a.allPolygons();
  25655. };
  25656. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25657. // not modified.
  25658. CSG.prototype.inverse = function () {
  25659. var csg = this.clone();
  25660. csg.inverseInPlace();
  25661. return csg;
  25662. };
  25663. CSG.prototype.inverseInPlace = function () {
  25664. this.polygons.map(function (p) { p.flip(); });
  25665. };
  25666. // This is used to keep meshes transformations so they can be restored
  25667. // when we build back a Babylon Mesh
  25668. // NB : All CSG operations are performed in world coordinates
  25669. CSG.prototype.copyTransformAttributes = function (csg) {
  25670. this.matrix = csg.matrix;
  25671. this.position = csg.position;
  25672. this.rotation = csg.rotation;
  25673. this.scaling = csg.scaling;
  25674. this.rotationQuaternion = csg.rotationQuaternion;
  25675. return this;
  25676. };
  25677. // Build Raw mesh from CSG
  25678. // Coordinates here are in world space
  25679. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25680. var matrix = this.matrix.clone();
  25681. matrix.invert();
  25682. 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;
  25683. if (keepSubMeshes) {
  25684. // Sort Polygons, since subMeshes are indices range
  25685. polygons.sort(function (a, b) {
  25686. if (a.shared.meshId === b.shared.meshId) {
  25687. return a.shared.subMeshId - b.shared.subMeshId;
  25688. }
  25689. else {
  25690. return a.shared.meshId - b.shared.meshId;
  25691. }
  25692. });
  25693. }
  25694. for (var i = 0, il = polygons.length; i < il; i++) {
  25695. polygon = polygons[i];
  25696. // Building SubMeshes
  25697. if (!subMesh_dict[polygon.shared.meshId]) {
  25698. subMesh_dict[polygon.shared.meshId] = {};
  25699. }
  25700. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25701. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25702. indexStart: +Infinity,
  25703. indexEnd: -Infinity,
  25704. materialIndex: polygon.shared.materialIndex
  25705. };
  25706. }
  25707. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25708. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25709. polygonIndices[0] = 0;
  25710. polygonIndices[1] = j - 1;
  25711. polygonIndices[2] = j;
  25712. for (var k = 0; k < 3; k++) {
  25713. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25714. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25715. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25716. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25717. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25718. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25719. // Check if 2 points can be merged
  25720. if (!(typeof vertex_idx !== 'undefined' &&
  25721. normals[vertex_idx * 3] === localNormal.x &&
  25722. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25723. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25724. uvs[vertex_idx * 2] === uv.x &&
  25725. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25726. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25727. uvs.push(uv.x, uv.y);
  25728. normals.push(normal.x, normal.y, normal.z);
  25729. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25730. }
  25731. indices.push(vertex_idx);
  25732. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25733. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25734. currentIndex++;
  25735. }
  25736. }
  25737. }
  25738. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25739. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25740. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25741. mesh.setIndices(indices);
  25742. if (keepSubMeshes) {
  25743. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25744. var materialIndexOffset = 0, materialMaxIndex;
  25745. mesh.subMeshes.length = 0;
  25746. for (var m in subMesh_dict) {
  25747. materialMaxIndex = -1;
  25748. for (var sm in subMesh_dict[m]) {
  25749. subMesh_obj = subMesh_dict[m][sm];
  25750. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25751. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25752. }
  25753. materialIndexOffset += ++materialMaxIndex;
  25754. }
  25755. }
  25756. return mesh;
  25757. };
  25758. // Build Mesh from CSG taking material and transforms into account
  25759. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25760. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25761. mesh.material = material;
  25762. mesh.position.copyFrom(this.position);
  25763. mesh.rotation.copyFrom(this.rotation);
  25764. if (this.rotationQuaternion) {
  25765. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25766. }
  25767. mesh.scaling.copyFrom(this.scaling);
  25768. mesh.computeWorldMatrix(true);
  25769. return mesh;
  25770. };
  25771. return CSG;
  25772. })();
  25773. BABYLON.CSG = CSG;
  25774. })(BABYLON || (BABYLON = {}));
  25775. var BABYLON;
  25776. (function (BABYLON) {
  25777. var VRDistortionCorrectionPostProcess = (function (_super) {
  25778. __extends(VRDistortionCorrectionPostProcess, _super);
  25779. //ANY
  25780. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25781. var _this = this;
  25782. _super.call(this, name, "vrDistortionCorrection", [
  25783. 'LensCenter',
  25784. 'Scale',
  25785. 'ScaleIn',
  25786. 'HmdWarpParam'
  25787. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25788. this._isRightEye = isRightEye;
  25789. this._distortionFactors = vrMetrics.distortionK;
  25790. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25791. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25792. this.onSizeChanged = function () {
  25793. _this.aspectRatio = _this.width * .5 / _this.height;
  25794. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25795. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25796. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25797. };
  25798. this.onApply = function (effect) {
  25799. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25800. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25801. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25802. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25803. };
  25804. }
  25805. return VRDistortionCorrectionPostProcess;
  25806. })(BABYLON.PostProcess);
  25807. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25808. })(BABYLON || (BABYLON = {}));
  25809. // Mainly based on these 2 articles :
  25810. // 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
  25811. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25812. var BABYLON;
  25813. (function (BABYLON) {
  25814. (function (JoystickAxis) {
  25815. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25816. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25817. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25818. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25819. var JoystickAxis = BABYLON.JoystickAxis;
  25820. var VirtualJoystick = (function () {
  25821. function VirtualJoystick(leftJoystick) {
  25822. var _this = this;
  25823. if (leftJoystick) {
  25824. this._leftJoystick = true;
  25825. }
  25826. else {
  25827. this._leftJoystick = false;
  25828. }
  25829. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25830. VirtualJoystick._globalJoystickIndex++;
  25831. // By default left & right arrow keys are moving the X
  25832. // and up & down keys are moving the Y
  25833. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25834. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25835. this.reverseLeftRight = false;
  25836. this.reverseUpDown = false;
  25837. // collections of pointers
  25838. this._touches = new BABYLON.SmartCollection();
  25839. this.deltaPosition = BABYLON.Vector3.Zero();
  25840. this._joystickSensibility = 25;
  25841. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25842. this._rotationSpeed = 25;
  25843. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25844. this._rotateOnAxisRelativeToMesh = false;
  25845. this._onResize = function (evt) {
  25846. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25847. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25848. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25849. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25850. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25851. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25852. };
  25853. // injecting a canvas element on top of the canvas 3D game
  25854. if (!VirtualJoystick.vjCanvas) {
  25855. window.addEventListener("resize", this._onResize, false);
  25856. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25857. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25858. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25859. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25860. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25861. VirtualJoystick.vjCanvas.style.width = "100%";
  25862. VirtualJoystick.vjCanvas.style.height = "100%";
  25863. VirtualJoystick.vjCanvas.style.position = "absolute";
  25864. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25865. VirtualJoystick.vjCanvas.style.top = "0px";
  25866. VirtualJoystick.vjCanvas.style.left = "0px";
  25867. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25868. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25869. // Support for jQuery PEP polyfill
  25870. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  25871. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25872. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25873. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25874. document.body.appendChild(VirtualJoystick.vjCanvas);
  25875. }
  25876. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25877. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25878. this.pressed = false;
  25879. // default joystick color
  25880. this._joystickColor = "cyan";
  25881. this._joystickPointerID = -1;
  25882. // current joystick position
  25883. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25884. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25885. // origin joystick position
  25886. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25887. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25888. this._onPointerDownHandlerRef = function (evt) {
  25889. _this._onPointerDown(evt);
  25890. };
  25891. this._onPointerMoveHandlerRef = function (evt) {
  25892. _this._onPointerMove(evt);
  25893. };
  25894. this._onPointerOutHandlerRef = function (evt) {
  25895. _this._onPointerUp(evt);
  25896. };
  25897. this._onPointerUpHandlerRef = function (evt) {
  25898. _this._onPointerUp(evt);
  25899. };
  25900. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25901. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25902. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25903. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25904. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25905. evt.preventDefault(); // Disables system menu
  25906. }, false);
  25907. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25908. }
  25909. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25910. this._joystickSensibility = newJoystickSensibility;
  25911. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25912. };
  25913. VirtualJoystick.prototype._onPointerDown = function (e) {
  25914. var positionOnScreenCondition;
  25915. e.preventDefault();
  25916. if (this._leftJoystick === true) {
  25917. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25918. }
  25919. else {
  25920. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25921. }
  25922. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25923. // First contact will be dedicated to the virtual joystick
  25924. this._joystickPointerID = e.pointerId;
  25925. this._joystickPointerStartPos.x = e.clientX;
  25926. this._joystickPointerStartPos.y = e.clientY;
  25927. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25928. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25929. this._deltaJoystickVector.x = 0;
  25930. this._deltaJoystickVector.y = 0;
  25931. this.pressed = true;
  25932. this._touches.add(e.pointerId.toString(), e);
  25933. }
  25934. else {
  25935. // You can only trigger the action buttons with a joystick declared
  25936. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25937. this._action();
  25938. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25939. }
  25940. }
  25941. };
  25942. VirtualJoystick.prototype._onPointerMove = function (e) {
  25943. // If the current pointer is the one associated to the joystick (first touch contact)
  25944. if (this._joystickPointerID == e.pointerId) {
  25945. this._joystickPointerPos.x = e.clientX;
  25946. this._joystickPointerPos.y = e.clientY;
  25947. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25948. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25949. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25950. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25951. switch (this._axisTargetedByLeftAndRight) {
  25952. case JoystickAxis.X:
  25953. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25954. break;
  25955. case JoystickAxis.Y:
  25956. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25957. break;
  25958. case JoystickAxis.Z:
  25959. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25960. break;
  25961. }
  25962. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25963. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25964. switch (this._axisTargetedByUpAndDown) {
  25965. case JoystickAxis.X:
  25966. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25967. break;
  25968. case JoystickAxis.Y:
  25969. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25970. break;
  25971. case JoystickAxis.Z:
  25972. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25973. break;
  25974. }
  25975. }
  25976. else {
  25977. if (this._touches.item(e.pointerId.toString())) {
  25978. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25979. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25980. }
  25981. }
  25982. };
  25983. VirtualJoystick.prototype._onPointerUp = function (e) {
  25984. if (this._joystickPointerID == e.pointerId) {
  25985. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25986. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25987. this._joystickPointerID = -1;
  25988. this.pressed = false;
  25989. }
  25990. else {
  25991. var touch = this._touches.item(e.pointerId.toString());
  25992. if (touch) {
  25993. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25994. }
  25995. }
  25996. this._deltaJoystickVector.x = 0;
  25997. this._deltaJoystickVector.y = 0;
  25998. this._touches.remove(e.pointerId.toString());
  25999. };
  26000. /**
  26001. * Change the color of the virtual joystick
  26002. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  26003. */
  26004. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  26005. this._joystickColor = newColor;
  26006. };
  26007. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  26008. this._action = action;
  26009. };
  26010. // Define which axis you'd like to control for left & right
  26011. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  26012. switch (axis) {
  26013. case JoystickAxis.X:
  26014. case JoystickAxis.Y:
  26015. case JoystickAxis.Z:
  26016. this._axisTargetedByLeftAndRight = axis;
  26017. break;
  26018. default:
  26019. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  26020. break;
  26021. }
  26022. };
  26023. // Define which axis you'd like to control for up & down
  26024. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  26025. switch (axis) {
  26026. case JoystickAxis.X:
  26027. case JoystickAxis.Y:
  26028. case JoystickAxis.Z:
  26029. this._axisTargetedByUpAndDown = axis;
  26030. break;
  26031. default:
  26032. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  26033. break;
  26034. }
  26035. };
  26036. VirtualJoystick.prototype._clearCanvas = function () {
  26037. if (this._leftJoystick) {
  26038. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  26039. }
  26040. else {
  26041. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  26042. }
  26043. };
  26044. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  26045. var _this = this;
  26046. if (this.pressed) {
  26047. this._touches.forEach(function (touch) {
  26048. if (touch.pointerId === _this._joystickPointerID) {
  26049. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  26050. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  26051. VirtualJoystick.vjCanvasContext.beginPath();
  26052. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  26053. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26054. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  26055. VirtualJoystick.vjCanvasContext.stroke();
  26056. VirtualJoystick.vjCanvasContext.closePath();
  26057. VirtualJoystick.vjCanvasContext.beginPath();
  26058. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26059. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  26060. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  26061. VirtualJoystick.vjCanvasContext.stroke();
  26062. VirtualJoystick.vjCanvasContext.closePath();
  26063. VirtualJoystick.vjCanvasContext.beginPath();
  26064. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26065. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  26066. VirtualJoystick.vjCanvasContext.stroke();
  26067. VirtualJoystick.vjCanvasContext.closePath();
  26068. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  26069. }
  26070. else {
  26071. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  26072. VirtualJoystick.vjCanvasContext.beginPath();
  26073. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  26074. VirtualJoystick.vjCanvasContext.beginPath();
  26075. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  26076. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  26077. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  26078. VirtualJoystick.vjCanvasContext.stroke();
  26079. VirtualJoystick.vjCanvasContext.closePath();
  26080. touch.prevX = touch.x;
  26081. touch.prevY = touch.y;
  26082. }
  26083. ;
  26084. });
  26085. }
  26086. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  26087. };
  26088. VirtualJoystick.prototype.releaseCanvas = function () {
  26089. if (VirtualJoystick.vjCanvas) {
  26090. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  26091. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  26092. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  26093. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  26094. window.removeEventListener("resize", this._onResize);
  26095. document.body.removeChild(VirtualJoystick.vjCanvas);
  26096. VirtualJoystick.vjCanvas = null;
  26097. }
  26098. };
  26099. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  26100. VirtualJoystick._globalJoystickIndex = 0;
  26101. return VirtualJoystick;
  26102. })();
  26103. BABYLON.VirtualJoystick = VirtualJoystick;
  26104. })(BABYLON || (BABYLON = {}));
  26105. var BABYLON;
  26106. (function (BABYLON) {
  26107. // We're mainly based on the logic defined into the FreeCamera code
  26108. var VirtualJoysticksCamera = (function (_super) {
  26109. __extends(VirtualJoysticksCamera, _super);
  26110. function VirtualJoysticksCamera(name, position, scene) {
  26111. _super.call(this, name, position, scene);
  26112. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  26113. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  26114. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  26115. this._leftjoystick.setJoystickSensibility(0.15);
  26116. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  26117. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  26118. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  26119. this._rightjoystick.reverseUpDown = true;
  26120. this._rightjoystick.setJoystickSensibility(0.05);
  26121. this._rightjoystick.setJoystickColor("yellow");
  26122. }
  26123. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  26124. return this._leftjoystick;
  26125. };
  26126. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  26127. return this._rightjoystick;
  26128. };
  26129. VirtualJoysticksCamera.prototype._checkInputs = function () {
  26130. var speed = this._computeLocalCameraSpeed() * 50;
  26131. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26132. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  26133. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26134. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  26135. if (!this._leftjoystick.pressed) {
  26136. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  26137. }
  26138. if (!this._rightjoystick.pressed) {
  26139. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  26140. }
  26141. _super.prototype._checkInputs.call(this);
  26142. };
  26143. VirtualJoysticksCamera.prototype.dispose = function () {
  26144. this._leftjoystick.releaseCanvas();
  26145. _super.prototype.dispose.call(this);
  26146. };
  26147. return VirtualJoysticksCamera;
  26148. })(BABYLON.FreeCamera);
  26149. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  26150. })(BABYLON || (BABYLON = {}));
  26151. var BABYLON;
  26152. (function (BABYLON) {
  26153. var ShaderMaterial = (function (_super) {
  26154. __extends(ShaderMaterial, _super);
  26155. function ShaderMaterial(name, scene, shaderPath, options) {
  26156. _super.call(this, name, scene);
  26157. this._textures = new Array();
  26158. this._floats = new Array();
  26159. this._floatsArrays = {};
  26160. this._colors3 = new Array();
  26161. this._colors4 = new Array();
  26162. this._vectors2 = new Array();
  26163. this._vectors3 = new Array();
  26164. this._vectors4 = new Array();
  26165. this._matrices = new Array();
  26166. this._matrices3x3 = new Array();
  26167. this._matrices2x2 = new Array();
  26168. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  26169. this._shaderPath = shaderPath;
  26170. options.needAlphaBlending = options.needAlphaBlending || false;
  26171. options.needAlphaTesting = options.needAlphaTesting || false;
  26172. options.attributes = options.attributes || ["position", "normal", "uv"];
  26173. options.uniforms = options.uniforms || ["worldViewProjection"];
  26174. options.samplers = options.samplers || [];
  26175. options.defines = options.defines || [];
  26176. this._options = options;
  26177. }
  26178. ShaderMaterial.prototype.needAlphaBlending = function () {
  26179. return this._options.needAlphaBlending;
  26180. };
  26181. ShaderMaterial.prototype.needAlphaTesting = function () {
  26182. return this._options.needAlphaTesting;
  26183. };
  26184. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  26185. if (this._options.uniforms.indexOf(uniformName) === -1) {
  26186. this._options.uniforms.push(uniformName);
  26187. }
  26188. };
  26189. ShaderMaterial.prototype.setTexture = function (name, texture) {
  26190. if (this._options.samplers.indexOf(name) === -1) {
  26191. this._options.samplers.push(name);
  26192. }
  26193. this._textures[name] = texture;
  26194. return this;
  26195. };
  26196. ShaderMaterial.prototype.setFloat = function (name, value) {
  26197. this._checkUniform(name);
  26198. this._floats[name] = value;
  26199. return this;
  26200. };
  26201. ShaderMaterial.prototype.setFloats = function (name, value) {
  26202. this._checkUniform(name);
  26203. this._floatsArrays[name] = value;
  26204. return this;
  26205. };
  26206. ShaderMaterial.prototype.setColor3 = function (name, value) {
  26207. this._checkUniform(name);
  26208. this._colors3[name] = value;
  26209. return this;
  26210. };
  26211. ShaderMaterial.prototype.setColor4 = function (name, value) {
  26212. this._checkUniform(name);
  26213. this._colors4[name] = value;
  26214. return this;
  26215. };
  26216. ShaderMaterial.prototype.setVector2 = function (name, value) {
  26217. this._checkUniform(name);
  26218. this._vectors2[name] = value;
  26219. return this;
  26220. };
  26221. ShaderMaterial.prototype.setVector3 = function (name, value) {
  26222. this._checkUniform(name);
  26223. this._vectors3[name] = value;
  26224. return this;
  26225. };
  26226. ShaderMaterial.prototype.setVector4 = function (name, value) {
  26227. this._checkUniform(name);
  26228. this._vectors4[name] = value;
  26229. return this;
  26230. };
  26231. ShaderMaterial.prototype.setMatrix = function (name, value) {
  26232. this._checkUniform(name);
  26233. this._matrices[name] = value;
  26234. return this;
  26235. };
  26236. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  26237. this._checkUniform(name);
  26238. this._matrices3x3[name] = value;
  26239. return this;
  26240. };
  26241. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  26242. this._checkUniform(name);
  26243. this._matrices2x2[name] = value;
  26244. return this;
  26245. };
  26246. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  26247. var scene = this.getScene();
  26248. var engine = scene.getEngine();
  26249. if (!this.checkReadyOnEveryCall) {
  26250. if (this._renderId === scene.getRenderId()) {
  26251. return true;
  26252. }
  26253. }
  26254. // Instances
  26255. var defines = [];
  26256. var fallbacks = new BABYLON.EffectFallbacks();
  26257. if (useInstances) {
  26258. defines.push("#define INSTANCES");
  26259. }
  26260. for (var index = 0; index < this._options.defines.length; index++) {
  26261. defines.push(this._options.defines[index]);
  26262. }
  26263. // Bones
  26264. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26265. defines.push("#define BONES");
  26266. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26267. defines.push("#define BONES4");
  26268. fallbacks.addFallback(0, "BONES4");
  26269. }
  26270. // Alpha test
  26271. if (engine.getAlphaTesting()) {
  26272. defines.push("#define ALPHATEST");
  26273. }
  26274. var previousEffect = this._effect;
  26275. var join = defines.join("\n");
  26276. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  26277. if (!this._effect.isReady()) {
  26278. return false;
  26279. }
  26280. if (previousEffect !== this._effect) {
  26281. scene.resetCachedMaterial();
  26282. }
  26283. this._renderId = scene.getRenderId();
  26284. return true;
  26285. };
  26286. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26287. var scene = this.getScene();
  26288. if (this._options.uniforms.indexOf("world") !== -1) {
  26289. this._effect.setMatrix("world", world);
  26290. }
  26291. if (this._options.uniforms.indexOf("worldView") !== -1) {
  26292. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  26293. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  26294. }
  26295. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  26296. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  26297. }
  26298. };
  26299. ShaderMaterial.prototype.bind = function (world, mesh) {
  26300. // Std values
  26301. this.bindOnlyWorldMatrix(world);
  26302. if (this.getScene().getCachedMaterial() !== this) {
  26303. if (this._options.uniforms.indexOf("view") !== -1) {
  26304. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  26305. }
  26306. if (this._options.uniforms.indexOf("projection") !== -1) {
  26307. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  26308. }
  26309. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  26310. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26311. }
  26312. // Bones
  26313. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26314. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26315. }
  26316. // Texture
  26317. for (var name in this._textures) {
  26318. this._effect.setTexture(name, this._textures[name]);
  26319. }
  26320. // Float
  26321. for (name in this._floats) {
  26322. this._effect.setFloat(name, this._floats[name]);
  26323. }
  26324. // Float s
  26325. for (name in this._floatsArrays) {
  26326. this._effect.setArray(name, this._floatsArrays[name]);
  26327. }
  26328. // Color3
  26329. for (name in this._colors3) {
  26330. this._effect.setColor3(name, this._colors3[name]);
  26331. }
  26332. // Color4
  26333. for (name in this._colors4) {
  26334. var color = this._colors4[name];
  26335. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  26336. }
  26337. // Vector2
  26338. for (name in this._vectors2) {
  26339. this._effect.setVector2(name, this._vectors2[name]);
  26340. }
  26341. // Vector3
  26342. for (name in this._vectors3) {
  26343. this._effect.setVector3(name, this._vectors3[name]);
  26344. }
  26345. // Vector4
  26346. for (name in this._vectors4) {
  26347. this._effect.setVector4(name, this._vectors4[name]);
  26348. }
  26349. // Matrix
  26350. for (name in this._matrices) {
  26351. this._effect.setMatrix(name, this._matrices[name]);
  26352. }
  26353. // Matrix 3x3
  26354. for (name in this._matrices3x3) {
  26355. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  26356. }
  26357. // Matrix 2x2
  26358. for (name in this._matrices2x2) {
  26359. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  26360. }
  26361. }
  26362. _super.prototype.bind.call(this, world, mesh);
  26363. };
  26364. ShaderMaterial.prototype.clone = function (name) {
  26365. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  26366. return newShaderMaterial;
  26367. };
  26368. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  26369. for (var name in this._textures) {
  26370. this._textures[name].dispose();
  26371. }
  26372. this._textures = [];
  26373. _super.prototype.dispose.call(this, forceDisposeEffect);
  26374. };
  26375. return ShaderMaterial;
  26376. })(BABYLON.Material);
  26377. BABYLON.ShaderMaterial = ShaderMaterial;
  26378. })(BABYLON || (BABYLON = {}));
  26379. var BABYLON;
  26380. (function (BABYLON) {
  26381. var VertexData = (function () {
  26382. function VertexData() {
  26383. }
  26384. VertexData.prototype.set = function (data, kind) {
  26385. switch (kind) {
  26386. case BABYLON.VertexBuffer.PositionKind:
  26387. this.positions = data;
  26388. break;
  26389. case BABYLON.VertexBuffer.NormalKind:
  26390. this.normals = data;
  26391. break;
  26392. case BABYLON.VertexBuffer.UVKind:
  26393. this.uvs = data;
  26394. break;
  26395. case BABYLON.VertexBuffer.UV2Kind:
  26396. this.uvs2 = data;
  26397. break;
  26398. case BABYLON.VertexBuffer.UV3Kind:
  26399. this.uvs3 = data;
  26400. break;
  26401. case BABYLON.VertexBuffer.UV4Kind:
  26402. this.uvs4 = data;
  26403. break;
  26404. case BABYLON.VertexBuffer.UV5Kind:
  26405. this.uvs5 = data;
  26406. break;
  26407. case BABYLON.VertexBuffer.UV6Kind:
  26408. this.uvs6 = data;
  26409. break;
  26410. case BABYLON.VertexBuffer.ColorKind:
  26411. this.colors = data;
  26412. break;
  26413. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26414. this.matricesIndices = data;
  26415. break;
  26416. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26417. this.matricesWeights = data;
  26418. break;
  26419. }
  26420. };
  26421. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26422. this._applyTo(mesh, updatable);
  26423. };
  26424. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26425. this._applyTo(geometry, updatable);
  26426. };
  26427. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26428. this._update(mesh);
  26429. };
  26430. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26431. this._update(geometry);
  26432. };
  26433. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26434. if (this.positions) {
  26435. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26436. }
  26437. if (this.normals) {
  26438. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26439. }
  26440. if (this.uvs) {
  26441. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26442. }
  26443. if (this.uvs2) {
  26444. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26445. }
  26446. if (this.uvs3) {
  26447. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26448. }
  26449. if (this.uvs4) {
  26450. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26451. }
  26452. if (this.uvs5) {
  26453. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26454. }
  26455. if (this.uvs6) {
  26456. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26457. }
  26458. if (this.colors) {
  26459. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26460. }
  26461. if (this.matricesIndices) {
  26462. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26463. }
  26464. if (this.matricesWeights) {
  26465. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26466. }
  26467. if (this.indices) {
  26468. meshOrGeometry.setIndices(this.indices);
  26469. }
  26470. };
  26471. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26472. if (this.positions) {
  26473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26474. }
  26475. if (this.normals) {
  26476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26477. }
  26478. if (this.uvs) {
  26479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26480. }
  26481. if (this.uvs2) {
  26482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26483. }
  26484. if (this.uvs3) {
  26485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26486. }
  26487. if (this.uvs4) {
  26488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26489. }
  26490. if (this.uvs5) {
  26491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26492. }
  26493. if (this.uvs6) {
  26494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26495. }
  26496. if (this.colors) {
  26497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26498. }
  26499. if (this.matricesIndices) {
  26500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26501. }
  26502. if (this.matricesWeights) {
  26503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26504. }
  26505. if (this.indices) {
  26506. meshOrGeometry.setIndices(this.indices);
  26507. }
  26508. };
  26509. VertexData.prototype.transform = function (matrix) {
  26510. var transformed = BABYLON.Vector3.Zero();
  26511. var index;
  26512. if (this.positions) {
  26513. var position = BABYLON.Vector3.Zero();
  26514. for (index = 0; index < this.positions.length; index += 3) {
  26515. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26516. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26517. this.positions[index] = transformed.x;
  26518. this.positions[index + 1] = transformed.y;
  26519. this.positions[index + 2] = transformed.z;
  26520. }
  26521. }
  26522. if (this.normals) {
  26523. var normal = BABYLON.Vector3.Zero();
  26524. for (index = 0; index < this.normals.length; index += 3) {
  26525. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26526. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26527. this.normals[index] = transformed.x;
  26528. this.normals[index + 1] = transformed.y;
  26529. this.normals[index + 2] = transformed.z;
  26530. }
  26531. }
  26532. };
  26533. VertexData.prototype.merge = function (other) {
  26534. var index;
  26535. if (other.indices) {
  26536. if (!this.indices) {
  26537. this.indices = [];
  26538. }
  26539. var offset = this.positions ? this.positions.length / 3 : 0;
  26540. for (index = 0; index < other.indices.length; index++) {
  26541. this.indices.push(other.indices[index] + offset);
  26542. }
  26543. }
  26544. if (other.positions) {
  26545. if (!this.positions) {
  26546. this.positions = [];
  26547. }
  26548. for (index = 0; index < other.positions.length; index++) {
  26549. this.positions.push(other.positions[index]);
  26550. }
  26551. }
  26552. if (other.normals) {
  26553. if (!this.normals) {
  26554. this.normals = [];
  26555. }
  26556. for (index = 0; index < other.normals.length; index++) {
  26557. this.normals.push(other.normals[index]);
  26558. }
  26559. }
  26560. if (other.uvs) {
  26561. if (!this.uvs) {
  26562. this.uvs = [];
  26563. }
  26564. for (index = 0; index < other.uvs.length; index++) {
  26565. this.uvs.push(other.uvs[index]);
  26566. }
  26567. }
  26568. if (other.uvs2) {
  26569. if (!this.uvs2) {
  26570. this.uvs2 = [];
  26571. }
  26572. for (index = 0; index < other.uvs2.length; index++) {
  26573. this.uvs2.push(other.uvs2[index]);
  26574. }
  26575. }
  26576. if (other.uvs3) {
  26577. if (!this.uvs3) {
  26578. this.uvs3 = [];
  26579. }
  26580. for (index = 0; index < other.uvs3.length; index++) {
  26581. this.uvs3.push(other.uvs3[index]);
  26582. }
  26583. }
  26584. if (other.uvs4) {
  26585. if (!this.uvs4) {
  26586. this.uvs4 = [];
  26587. }
  26588. for (index = 0; index < other.uvs4.length; index++) {
  26589. this.uvs4.push(other.uvs4[index]);
  26590. }
  26591. }
  26592. if (other.uvs5) {
  26593. if (!this.uvs5) {
  26594. this.uvs5 = [];
  26595. }
  26596. for (index = 0; index < other.uvs5.length; index++) {
  26597. this.uvs5.push(other.uvs5[index]);
  26598. }
  26599. }
  26600. if (other.uvs6) {
  26601. if (!this.uvs6) {
  26602. this.uvs6 = [];
  26603. }
  26604. for (index = 0; index < other.uvs6.length; index++) {
  26605. this.uvs6.push(other.uvs6[index]);
  26606. }
  26607. }
  26608. if (other.matricesIndices) {
  26609. if (!this.matricesIndices) {
  26610. this.matricesIndices = [];
  26611. }
  26612. for (index = 0; index < other.matricesIndices.length; index++) {
  26613. this.matricesIndices.push(other.matricesIndices[index]);
  26614. }
  26615. }
  26616. if (other.matricesWeights) {
  26617. if (!this.matricesWeights) {
  26618. this.matricesWeights = [];
  26619. }
  26620. for (index = 0; index < other.matricesWeights.length; index++) {
  26621. this.matricesWeights.push(other.matricesWeights[index]);
  26622. }
  26623. }
  26624. if (other.colors) {
  26625. if (!this.colors) {
  26626. this.colors = [];
  26627. }
  26628. for (index = 0; index < other.colors.length; index++) {
  26629. this.colors.push(other.colors[index]);
  26630. }
  26631. }
  26632. };
  26633. // Statics
  26634. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26635. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26636. };
  26637. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26638. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26639. };
  26640. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26641. var result = new VertexData();
  26642. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26643. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26644. }
  26645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26646. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26647. }
  26648. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26649. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26650. }
  26651. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26652. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26653. }
  26654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26655. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26656. }
  26657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26658. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26659. }
  26660. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26661. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26662. }
  26663. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26664. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26665. }
  26666. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26667. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26668. }
  26669. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26670. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26671. }
  26672. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26673. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26674. }
  26675. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26676. return result;
  26677. };
  26678. VertexData.CreateRibbon = function (options) {
  26679. var pathArray = options.pathArray;
  26680. var closeArray = options.closeArray || false;
  26681. var closePath = options.closePath || false;
  26682. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26683. var offset = options.offset || defaultOffset;
  26684. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26685. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26686. var positions = [];
  26687. var indices = [];
  26688. var normals = [];
  26689. var uvs = [];
  26690. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26691. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26692. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26693. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26694. var minlg; // minimal length among all paths from pathArray
  26695. var lg = []; // array of path lengths : nb of vertex per path
  26696. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26697. var p; // path iterator
  26698. var i; // point iterator
  26699. var j; // point iterator
  26700. // if single path in pathArray
  26701. if (pathArray.length < 2) {
  26702. var ar1 = [];
  26703. var ar2 = [];
  26704. for (i = 0; i < pathArray[0].length - offset; i++) {
  26705. ar1.push(pathArray[0][i]);
  26706. ar2.push(pathArray[0][i + offset]);
  26707. }
  26708. pathArray = [ar1, ar2];
  26709. }
  26710. // positions and horizontal distances (u)
  26711. var idc = 0;
  26712. var closePathCorr = (closePath) ? 1 : 0;
  26713. var path;
  26714. var l;
  26715. minlg = pathArray[0].length;
  26716. var vectlg;
  26717. var dist;
  26718. for (p = 0; p < pathArray.length; p++) {
  26719. uTotalDistance[p] = 0;
  26720. us[p] = [0];
  26721. path = pathArray[p];
  26722. l = path.length;
  26723. minlg = (minlg < l) ? minlg : l;
  26724. j = 0;
  26725. while (j < l) {
  26726. positions.push(path[j].x, path[j].y, path[j].z);
  26727. if (j > 0) {
  26728. vectlg = path[j].subtract(path[j - 1]).length();
  26729. dist = vectlg + uTotalDistance[p];
  26730. us[p].push(dist);
  26731. uTotalDistance[p] = dist;
  26732. }
  26733. j++;
  26734. }
  26735. if (closePath) {
  26736. j--;
  26737. positions.push(path[0].x, path[0].y, path[0].z);
  26738. vectlg = path[j].subtract(path[0]).length();
  26739. dist = vectlg + uTotalDistance[p];
  26740. us[p].push(dist);
  26741. uTotalDistance[p] = dist;
  26742. }
  26743. lg[p] = l + closePathCorr;
  26744. idx[p] = idc;
  26745. idc += (l + closePathCorr);
  26746. }
  26747. // vertical distances (v)
  26748. var path1;
  26749. var path2;
  26750. var vertex1;
  26751. var vertex2;
  26752. for (i = 0; i < minlg + closePathCorr; i++) {
  26753. vTotalDistance[i] = 0;
  26754. vs[i] = [0];
  26755. for (p = 0; p < pathArray.length - 1; p++) {
  26756. path1 = pathArray[p];
  26757. path2 = pathArray[p + 1];
  26758. if (i === minlg) {
  26759. vertex1 = path1[0];
  26760. vertex2 = path2[0];
  26761. }
  26762. else {
  26763. vertex1 = path1[i];
  26764. vertex2 = path2[i];
  26765. }
  26766. vectlg = vertex2.subtract(vertex1).length();
  26767. dist = vectlg + vTotalDistance[i];
  26768. vs[i].push(dist);
  26769. vTotalDistance[i] = dist;
  26770. }
  26771. if (closeArray) {
  26772. path1 = pathArray[p];
  26773. path2 = pathArray[0];
  26774. if (i === minlg) {
  26775. vertex2 = path2[0];
  26776. }
  26777. vectlg = vertex2.subtract(vertex1).length();
  26778. dist = vectlg + vTotalDistance[i];
  26779. vTotalDistance[i] = dist;
  26780. }
  26781. }
  26782. // uvs
  26783. var u;
  26784. var v;
  26785. for (p = 0; p < pathArray.length; p++) {
  26786. for (i = 0; i < minlg + closePathCorr; i++) {
  26787. u = us[p][i] / uTotalDistance[p];
  26788. v = vs[i][p] / vTotalDistance[i];
  26789. uvs.push(u, v);
  26790. }
  26791. }
  26792. // indices
  26793. p = 0; // path index
  26794. var pi = 0; // positions array index
  26795. var l1 = lg[p] - 1; // path1 length
  26796. var l2 = lg[p + 1] - 1; // path2 length
  26797. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26798. var shft = idx[1] - idx[0]; // shift
  26799. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26800. while (pi <= min && p < path1nb) {
  26801. // 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
  26802. indices.push(pi, pi + shft, pi + 1);
  26803. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26804. pi += 1;
  26805. if (pi === min) {
  26806. p++;
  26807. if (p === lg.length - 1) {
  26808. shft = idx[0] - idx[p];
  26809. l1 = lg[p] - 1;
  26810. l2 = lg[0] - 1;
  26811. }
  26812. else {
  26813. shft = idx[p + 1] - idx[p];
  26814. l1 = lg[p] - 1;
  26815. l2 = lg[p + 1] - 1;
  26816. }
  26817. pi = idx[p];
  26818. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26819. }
  26820. }
  26821. // normals
  26822. VertexData.ComputeNormals(positions, indices, normals);
  26823. if (closePath) {
  26824. var indexFirst = 0;
  26825. var indexLast = 0;
  26826. for (p = 0; p < pathArray.length; p++) {
  26827. indexFirst = idx[p] * 3;
  26828. if (p + 1 < pathArray.length) {
  26829. indexLast = (idx[p + 1] - 1) * 3;
  26830. }
  26831. else {
  26832. indexLast = normals.length - 3;
  26833. }
  26834. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26835. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26836. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26837. normals[indexLast] = normals[indexFirst];
  26838. normals[indexLast + 1] = normals[indexFirst + 1];
  26839. normals[indexLast + 2] = normals[indexFirst + 2];
  26840. }
  26841. }
  26842. // sides
  26843. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26844. // Result
  26845. var vertexData = new VertexData();
  26846. vertexData.indices = indices;
  26847. vertexData.positions = positions;
  26848. vertexData.normals = normals;
  26849. vertexData.uvs = uvs;
  26850. if (closePath) {
  26851. vertexData._idx = idx;
  26852. }
  26853. return vertexData;
  26854. };
  26855. VertexData.CreateBox = function (options) {
  26856. var normalsSource = [
  26857. new BABYLON.Vector3(0, 0, 1),
  26858. new BABYLON.Vector3(0, 0, -1),
  26859. new BABYLON.Vector3(1, 0, 0),
  26860. new BABYLON.Vector3(-1, 0, 0),
  26861. new BABYLON.Vector3(0, 1, 0),
  26862. new BABYLON.Vector3(0, -1, 0)
  26863. ];
  26864. var indices = [];
  26865. var positions = [];
  26866. var normals = [];
  26867. var uvs = [];
  26868. var width = options.width || options.size || 1;
  26869. var height = options.height || options.size || 1;
  26870. var depth = options.depth || options.size || 1;
  26871. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26872. var faceUV = options.faceUV || new Array(6);
  26873. var faceColors = options.faceColors;
  26874. var colors = [];
  26875. // default face colors and UV if undefined
  26876. for (var f = 0; f < 6; f++) {
  26877. if (faceUV[f] === undefined) {
  26878. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26879. }
  26880. if (faceColors && faceColors[f] === undefined) {
  26881. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26882. }
  26883. }
  26884. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26885. // Create each face in turn.
  26886. for (var index = 0; index < normalsSource.length; index++) {
  26887. var normal = normalsSource[index];
  26888. // Get two vectors perpendicular to the face normal and to each other.
  26889. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26890. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26891. // Six indices (two triangles) per face.
  26892. var verticesLength = positions.length / 3;
  26893. indices.push(verticesLength);
  26894. indices.push(verticesLength + 1);
  26895. indices.push(verticesLength + 2);
  26896. indices.push(verticesLength);
  26897. indices.push(verticesLength + 2);
  26898. indices.push(verticesLength + 3);
  26899. // Four vertices per face.
  26900. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26901. positions.push(vertex.x, vertex.y, vertex.z);
  26902. normals.push(normal.x, normal.y, normal.z);
  26903. uvs.push(faceUV[index].z, faceUV[index].w);
  26904. if (faceColors) {
  26905. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26906. }
  26907. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26908. positions.push(vertex.x, vertex.y, vertex.z);
  26909. normals.push(normal.x, normal.y, normal.z);
  26910. uvs.push(faceUV[index].x, faceUV[index].w);
  26911. if (faceColors) {
  26912. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26913. }
  26914. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26915. positions.push(vertex.x, vertex.y, vertex.z);
  26916. normals.push(normal.x, normal.y, normal.z);
  26917. uvs.push(faceUV[index].x, faceUV[index].y);
  26918. if (faceColors) {
  26919. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26920. }
  26921. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26922. positions.push(vertex.x, vertex.y, vertex.z);
  26923. normals.push(normal.x, normal.y, normal.z);
  26924. uvs.push(faceUV[index].z, faceUV[index].y);
  26925. if (faceColors) {
  26926. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26927. }
  26928. }
  26929. // sides
  26930. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26931. // Result
  26932. var vertexData = new VertexData();
  26933. vertexData.indices = indices;
  26934. vertexData.positions = positions;
  26935. vertexData.normals = normals;
  26936. vertexData.uvs = uvs;
  26937. if (faceColors) {
  26938. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26939. vertexData.colors = totalColors;
  26940. }
  26941. return vertexData;
  26942. };
  26943. VertexData.CreateSphere = function (options) {
  26944. var segments = options.segments || 32;
  26945. var diameterX = options.diameterX || options.diameter || 1;
  26946. var diameterY = options.diameterY || options.diameter || 1;
  26947. var diameterZ = options.diameterZ || options.diameter || 1;
  26948. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  26949. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26950. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26951. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26952. var totalZRotationSteps = 2 + segments;
  26953. var totalYRotationSteps = 2 * totalZRotationSteps;
  26954. var indices = [];
  26955. var positions = [];
  26956. var normals = [];
  26957. var uvs = [];
  26958. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26959. var normalizedZ = zRotationStep / totalZRotationSteps;
  26960. var angleZ = normalizedZ * Math.PI * slice;
  26961. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26962. var normalizedY = yRotationStep / totalYRotationSteps;
  26963. var angleY = normalizedY * Math.PI * 2 * arc;
  26964. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26965. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26966. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26967. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26968. var vertex = complete.multiply(radius);
  26969. var normal = BABYLON.Vector3.Normalize(vertex);
  26970. positions.push(vertex.x, vertex.y, vertex.z);
  26971. normals.push(normal.x, normal.y, normal.z);
  26972. uvs.push(normalizedY, normalizedZ);
  26973. }
  26974. if (zRotationStep > 0) {
  26975. var verticesCount = positions.length / 3;
  26976. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26977. indices.push((firstIndex));
  26978. indices.push((firstIndex + 1));
  26979. indices.push(firstIndex + totalYRotationSteps + 1);
  26980. indices.push((firstIndex + totalYRotationSteps + 1));
  26981. indices.push((firstIndex + 1));
  26982. indices.push((firstIndex + totalYRotationSteps + 2));
  26983. }
  26984. }
  26985. }
  26986. // Sides
  26987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26988. // Result
  26989. var vertexData = new VertexData();
  26990. vertexData.indices = indices;
  26991. vertexData.positions = positions;
  26992. vertexData.normals = normals;
  26993. vertexData.uvs = uvs;
  26994. return vertexData;
  26995. };
  26996. // Cylinder and cone
  26997. VertexData.CreateCylinder = function (options) {
  26998. var height = options.height || 2;
  26999. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || 1;
  27000. var diameterBottom = options.diameterBottom || 1;
  27001. var tessellation = options.tessellation || 24;
  27002. var subdivisions = options.subdivisions || 1;
  27003. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  27004. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27005. var faceUV = options.faceUV || new Array(3);
  27006. var faceColors = options.faceColors;
  27007. // default face colors and UV if undefined
  27008. for (var f = 0; f < 3; f++) {
  27009. if (faceColors && faceColors[f] === undefined) {
  27010. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27011. }
  27012. if (faceUV && faceUV[f] === undefined) {
  27013. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27014. }
  27015. }
  27016. var indices = [];
  27017. var positions = [];
  27018. var normals = [];
  27019. var uvs = [];
  27020. var colors = [];
  27021. var angle_step = Math.PI * 2 * arc / tessellation;
  27022. var angle;
  27023. var h;
  27024. var radius;
  27025. var tan = (diameterBottom - diameterTop) / 2 / height;
  27026. var ringVertex = BABYLON.Vector3.Zero();
  27027. var ringNormal = BABYLON.Vector3.Zero();
  27028. // positions, normals, uvs
  27029. var i;
  27030. var j;
  27031. for (i = 0; i <= subdivisions; i++) {
  27032. h = i / subdivisions;
  27033. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27034. for (j = 0; j <= tessellation; j++) {
  27035. angle = j * angle_step;
  27036. ringVertex.x = Math.cos(-angle) * radius;
  27037. ringVertex.y = -height / 2 + h * height;
  27038. ringVertex.z = Math.sin(-angle) * radius;
  27039. if (diameterTop === 0 && i === subdivisions) {
  27040. // if no top cap, reuse former normals
  27041. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27042. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27043. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27044. }
  27045. else {
  27046. ringNormal.x = ringVertex.x;
  27047. ringNormal.z = ringVertex.z;
  27048. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27049. ringNormal.normalize();
  27050. }
  27051. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27052. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27053. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  27054. if (faceColors) {
  27055. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  27056. }
  27057. }
  27058. }
  27059. // indices
  27060. for (i = 0; i < subdivisions; i++) {
  27061. for (j = 0; j < tessellation; j++) {
  27062. var i0 = i * (tessellation + 1) + j;
  27063. var i1 = (i + 1) * (tessellation + 1) + j;
  27064. var i2 = i * (tessellation + 1) + (j + 1);
  27065. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  27066. indices.push(i0, i1, i2);
  27067. indices.push(i3, i2, i1);
  27068. }
  27069. }
  27070. // Caps
  27071. var createCylinderCap = function (isTop) {
  27072. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27073. if (radius === 0) {
  27074. return;
  27075. }
  27076. // Cap positions, normals & uvs
  27077. var angle;
  27078. var circleVector;
  27079. var i;
  27080. var u = (isTop) ? faceUV[2] : faceUV[0];
  27081. var c;
  27082. if (faceColors) {
  27083. c = (isTop) ? faceColors[2] : faceColors[0];
  27084. }
  27085. // cap center
  27086. var vbase = positions.length / 3;
  27087. var offset = isTop ? height / 2 : -height / 2;
  27088. var center = new BABYLON.Vector3(0, offset, 0);
  27089. positions.push(center.x, center.y, center.z);
  27090. normals.push(0, isTop ? 1 : -1, 0);
  27091. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27092. if (faceColors) {
  27093. colors.push(c.r, c.g, c.b, c.a);
  27094. }
  27095. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27096. for (i = 0; i <= tessellation; i++) {
  27097. angle = Math.PI * 2 * i * arc / tessellation;
  27098. var cos = Math.cos(-angle);
  27099. var sin = Math.sin(-angle);
  27100. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27101. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27102. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27103. normals.push(0, isTop ? 1 : -1, 0);
  27104. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27105. if (faceColors) {
  27106. colors.push(c.r, c.g, c.b, c.a);
  27107. }
  27108. }
  27109. // Cap indices
  27110. for (i = 0; i < tessellation; i++) {
  27111. if (!isTop) {
  27112. indices.push(vbase);
  27113. indices.push(vbase + (i + 1));
  27114. indices.push(vbase + (i + 2));
  27115. }
  27116. else {
  27117. indices.push(vbase);
  27118. indices.push(vbase + (i + 2));
  27119. indices.push(vbase + (i + 1));
  27120. }
  27121. }
  27122. };
  27123. // add caps to geometry
  27124. createCylinderCap(false);
  27125. createCylinderCap(true);
  27126. // Sides
  27127. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27128. var vertexData = new VertexData();
  27129. vertexData.indices = indices;
  27130. vertexData.positions = positions;
  27131. vertexData.normals = normals;
  27132. vertexData.uvs = uvs;
  27133. if (faceColors) {
  27134. vertexData.colors = colors;
  27135. }
  27136. return vertexData;
  27137. };
  27138. VertexData.CreateTorus = function (options) {
  27139. var indices = [];
  27140. var positions = [];
  27141. var normals = [];
  27142. var uvs = [];
  27143. var diameter = options.diameter || 1;
  27144. var thickness = options.thickness || 0.5;
  27145. var tessellation = options.tessellation || 16;
  27146. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27147. var stride = tessellation + 1;
  27148. for (var i = 0; i <= tessellation; i++) {
  27149. var u = i / tessellation;
  27150. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27151. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27152. for (var j = 0; j <= tessellation; j++) {
  27153. var v = 1 - j / tessellation;
  27154. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27155. var dx = Math.cos(innerAngle);
  27156. var dy = Math.sin(innerAngle);
  27157. // Create a vertex.
  27158. var normal = new BABYLON.Vector3(dx, dy, 0);
  27159. var position = normal.scale(thickness / 2);
  27160. var textureCoordinate = new BABYLON.Vector2(u, v);
  27161. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27162. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27163. positions.push(position.x, position.y, position.z);
  27164. normals.push(normal.x, normal.y, normal.z);
  27165. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27166. // And create indices for two triangles.
  27167. var nextI = (i + 1) % stride;
  27168. var nextJ = (j + 1) % stride;
  27169. indices.push(i * stride + j);
  27170. indices.push(i * stride + nextJ);
  27171. indices.push(nextI * stride + j);
  27172. indices.push(i * stride + nextJ);
  27173. indices.push(nextI * stride + nextJ);
  27174. indices.push(nextI * stride + j);
  27175. }
  27176. }
  27177. // Sides
  27178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27179. // Result
  27180. var vertexData = new VertexData();
  27181. vertexData.indices = indices;
  27182. vertexData.positions = positions;
  27183. vertexData.normals = normals;
  27184. vertexData.uvs = uvs;
  27185. return vertexData;
  27186. };
  27187. VertexData.CreateLines = function (options) {
  27188. var indices = [];
  27189. var positions = [];
  27190. var points = options.points;
  27191. for (var index = 0; index < points.length; index++) {
  27192. positions.push(points[index].x, points[index].y, points[index].z);
  27193. if (index > 0) {
  27194. indices.push(index - 1);
  27195. indices.push(index);
  27196. }
  27197. }
  27198. // Result
  27199. var vertexData = new VertexData();
  27200. vertexData.indices = indices;
  27201. vertexData.positions = positions;
  27202. return vertexData;
  27203. };
  27204. VertexData.CreateDashedLines = function (options) {
  27205. var dashSize = options.dashSize || 3;
  27206. var gapSize = options.gapSize || 1;
  27207. var dashNb = options.dashNb || 200;
  27208. var points = options.points;
  27209. var positions = new Array();
  27210. var indices = new Array();
  27211. var curvect = BABYLON.Vector3.Zero();
  27212. var lg = 0;
  27213. var nb = 0;
  27214. var shft = 0;
  27215. var dashshft = 0;
  27216. var curshft = 0;
  27217. var idx = 0;
  27218. var i = 0;
  27219. for (i = 0; i < points.length - 1; i++) {
  27220. points[i + 1].subtractToRef(points[i], curvect);
  27221. lg += curvect.length();
  27222. }
  27223. shft = lg / dashNb;
  27224. dashshft = dashSize * shft / (dashSize + gapSize);
  27225. for (i = 0; i < points.length - 1; i++) {
  27226. points[i + 1].subtractToRef(points[i], curvect);
  27227. nb = Math.floor(curvect.length() / shft);
  27228. curvect.normalize();
  27229. for (var j = 0; j < nb; j++) {
  27230. curshft = shft * j;
  27231. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27232. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27233. indices.push(idx, idx + 1);
  27234. idx += 2;
  27235. }
  27236. }
  27237. // Result
  27238. var vertexData = new VertexData();
  27239. vertexData.positions = positions;
  27240. vertexData.indices = indices;
  27241. return vertexData;
  27242. };
  27243. VertexData.CreateGround = function (options) {
  27244. var indices = [];
  27245. var positions = [];
  27246. var normals = [];
  27247. var uvs = [];
  27248. var row, col;
  27249. var width = options.width || 1;
  27250. var height = options.height || 1;
  27251. var subdivisions = options.subdivisions || 1;
  27252. for (row = 0; row <= subdivisions; row++) {
  27253. for (col = 0; col <= subdivisions; col++) {
  27254. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  27255. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27256. positions.push(position.x, position.y, position.z);
  27257. normals.push(normal.x, normal.y, normal.z);
  27258. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  27259. }
  27260. }
  27261. for (row = 0; row < subdivisions; row++) {
  27262. for (col = 0; col < subdivisions; col++) {
  27263. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27264. indices.push(col + 1 + row * (subdivisions + 1));
  27265. indices.push(col + row * (subdivisions + 1));
  27266. indices.push(col + (row + 1) * (subdivisions + 1));
  27267. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27268. indices.push(col + row * (subdivisions + 1));
  27269. }
  27270. }
  27271. // Result
  27272. var vertexData = new VertexData();
  27273. vertexData.indices = indices;
  27274. vertexData.positions = positions;
  27275. vertexData.normals = normals;
  27276. vertexData.uvs = uvs;
  27277. return vertexData;
  27278. };
  27279. VertexData.CreateTiledGround = function (options) {
  27280. var xmin = options.xmin;
  27281. var zmin = options.zmin;
  27282. var xmax = options.xmax;
  27283. var zmax = options.zmax;
  27284. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27285. var precision = options.precision || { w: 1, h: 1 };
  27286. var indices = [];
  27287. var positions = [];
  27288. var normals = [];
  27289. var uvs = [];
  27290. var row, col, tileRow, tileCol;
  27291. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  27292. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27293. precision.w = (precision.w < 1) ? 1 : precision.w;
  27294. precision.h = (precision.h < 1) ? 1 : precision.h;
  27295. var tileSize = {
  27296. 'w': (xmax - xmin) / subdivisions.w,
  27297. 'h': (zmax - zmin) / subdivisions.h
  27298. };
  27299. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27300. // Indices
  27301. var base = positions.length / 3;
  27302. var rowLength = precision.w + 1;
  27303. for (row = 0; row < precision.h; row++) {
  27304. for (col = 0; col < precision.w; col++) {
  27305. var square = [
  27306. base + col + row * rowLength,
  27307. base + (col + 1) + row * rowLength,
  27308. base + (col + 1) + (row + 1) * rowLength,
  27309. base + col + (row + 1) * rowLength
  27310. ];
  27311. indices.push(square[1]);
  27312. indices.push(square[2]);
  27313. indices.push(square[3]);
  27314. indices.push(square[0]);
  27315. indices.push(square[1]);
  27316. indices.push(square[3]);
  27317. }
  27318. }
  27319. // Position, normals and uvs
  27320. var position = BABYLON.Vector3.Zero();
  27321. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27322. for (row = 0; row <= precision.h; row++) {
  27323. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27324. for (col = 0; col <= precision.w; col++) {
  27325. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27326. position.y = 0;
  27327. positions.push(position.x, position.y, position.z);
  27328. normals.push(normal.x, normal.y, normal.z);
  27329. uvs.push(col / precision.w, row / precision.h);
  27330. }
  27331. }
  27332. }
  27333. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27334. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27335. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27336. }
  27337. }
  27338. // Result
  27339. var vertexData = new VertexData();
  27340. vertexData.indices = indices;
  27341. vertexData.positions = positions;
  27342. vertexData.normals = normals;
  27343. vertexData.uvs = uvs;
  27344. return vertexData;
  27345. };
  27346. VertexData.CreateGroundFromHeightMap = function (options) {
  27347. var indices = [];
  27348. var positions = [];
  27349. var normals = [];
  27350. var uvs = [];
  27351. var row, col;
  27352. // Vertices
  27353. for (row = 0; row <= options.subdivisions; row++) {
  27354. for (col = 0; col <= options.subdivisions; col++) {
  27355. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  27356. // Compute height
  27357. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27358. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27359. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27360. var r = options.buffer[pos] / 255.0;
  27361. var g = options.buffer[pos + 1] / 255.0;
  27362. var b = options.buffer[pos + 2] / 255.0;
  27363. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27364. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27365. // Add vertex
  27366. positions.push(position.x, position.y, position.z);
  27367. normals.push(0, 0, 0);
  27368. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27369. }
  27370. }
  27371. // Indices
  27372. for (row = 0; row < options.subdivisions; row++) {
  27373. for (col = 0; col < options.subdivisions; col++) {
  27374. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27375. indices.push(col + 1 + row * (options.subdivisions + 1));
  27376. indices.push(col + row * (options.subdivisions + 1));
  27377. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27378. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27379. indices.push(col + row * (options.subdivisions + 1));
  27380. }
  27381. }
  27382. // Normals
  27383. VertexData.ComputeNormals(positions, indices, normals);
  27384. // Result
  27385. var vertexData = new VertexData();
  27386. vertexData.indices = indices;
  27387. vertexData.positions = positions;
  27388. vertexData.normals = normals;
  27389. vertexData.uvs = uvs;
  27390. return vertexData;
  27391. };
  27392. VertexData.CreatePlane = function (options) {
  27393. var indices = [];
  27394. var positions = [];
  27395. var normals = [];
  27396. var uvs = [];
  27397. var width = options.width || options.size || 1;
  27398. var height = options.height || options.size || 1;
  27399. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27400. // Vertices
  27401. var halfWidth = width / 2.0;
  27402. var halfHeight = height / 2.0;
  27403. positions.push(-halfWidth, -halfHeight, 0);
  27404. normals.push(0, 0, -1.0);
  27405. uvs.push(0.0, 0.0);
  27406. positions.push(halfWidth, -halfHeight, 0);
  27407. normals.push(0, 0, -1.0);
  27408. uvs.push(1.0, 0.0);
  27409. positions.push(halfWidth, halfHeight, 0);
  27410. normals.push(0, 0, -1.0);
  27411. uvs.push(1.0, 1.0);
  27412. positions.push(-halfWidth, halfHeight, 0);
  27413. normals.push(0, 0, -1.0);
  27414. uvs.push(0.0, 1.0);
  27415. // Indices
  27416. indices.push(0);
  27417. indices.push(1);
  27418. indices.push(2);
  27419. indices.push(0);
  27420. indices.push(2);
  27421. indices.push(3);
  27422. // Sides
  27423. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27424. // Result
  27425. var vertexData = new VertexData();
  27426. vertexData.indices = indices;
  27427. vertexData.positions = positions;
  27428. vertexData.normals = normals;
  27429. vertexData.uvs = uvs;
  27430. return vertexData;
  27431. };
  27432. VertexData.CreateDisc = function (options) {
  27433. var positions = [];
  27434. var indices = [];
  27435. var normals = [];
  27436. var uvs = [];
  27437. var radius = options.radius || 0.5;
  27438. var tessellation = options.tessellation || 64;
  27439. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27440. // positions and uvs
  27441. positions.push(0, 0, 0); // disc center first
  27442. uvs.push(0.5, 0.5);
  27443. var step = Math.PI * 2 / tessellation;
  27444. for (var a = 0; a < Math.PI * 2; a += step) {
  27445. var x = Math.cos(a);
  27446. var y = Math.sin(a);
  27447. var u = (x + 1) / 2;
  27448. var v = (1 - y) / 2;
  27449. positions.push(radius * x, radius * y, 0);
  27450. uvs.push(u, v);
  27451. }
  27452. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27453. uvs.push(uvs[2], uvs[3]);
  27454. //indices
  27455. var vertexNb = positions.length / 3;
  27456. for (var i = 1; i < vertexNb - 1; i++) {
  27457. indices.push(i + 1, 0, i);
  27458. }
  27459. // result
  27460. VertexData.ComputeNormals(positions, indices, normals);
  27461. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27462. var vertexData = new VertexData();
  27463. vertexData.indices = indices;
  27464. vertexData.positions = positions;
  27465. vertexData.normals = normals;
  27466. vertexData.uvs = uvs;
  27467. return vertexData;
  27468. };
  27469. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27470. VertexData.CreateTorusKnot = function (options) {
  27471. var indices = [];
  27472. var positions = [];
  27473. var normals = [];
  27474. var uvs = [];
  27475. var radius = options.radius || 2;
  27476. var tube = options.tube || 0.5;
  27477. var radialSegments = options.radialSegments || 32;
  27478. var tubularSegments = options.tubularSegments || 32;
  27479. var p = options.p || 2;
  27480. var q = options.q || 3;
  27481. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27482. // Helper
  27483. var getPos = function (angle) {
  27484. var cu = Math.cos(angle);
  27485. var su = Math.sin(angle);
  27486. var quOverP = q / p * angle;
  27487. var cs = Math.cos(quOverP);
  27488. var tx = radius * (2 + cs) * 0.5 * cu;
  27489. var ty = radius * (2 + cs) * su * 0.5;
  27490. var tz = radius * Math.sin(quOverP) * 0.5;
  27491. return new BABYLON.Vector3(tx, ty, tz);
  27492. };
  27493. // Vertices
  27494. var i;
  27495. var j;
  27496. for (i = 0; i <= radialSegments; i++) {
  27497. var modI = i % radialSegments;
  27498. var u = modI / radialSegments * 2 * p * Math.PI;
  27499. var p1 = getPos(u);
  27500. var p2 = getPos(u + 0.01);
  27501. var tang = p2.subtract(p1);
  27502. var n = p2.add(p1);
  27503. var bitan = BABYLON.Vector3.Cross(tang, n);
  27504. n = BABYLON.Vector3.Cross(bitan, tang);
  27505. bitan.normalize();
  27506. n.normalize();
  27507. for (j = 0; j < tubularSegments; j++) {
  27508. var modJ = j % tubularSegments;
  27509. var v = modJ / tubularSegments * 2 * Math.PI;
  27510. var cx = -tube * Math.cos(v);
  27511. var cy = tube * Math.sin(v);
  27512. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27513. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27514. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27515. uvs.push(i / radialSegments);
  27516. uvs.push(j / tubularSegments);
  27517. }
  27518. }
  27519. for (i = 0; i < radialSegments; i++) {
  27520. for (j = 0; j < tubularSegments; j++) {
  27521. var jNext = (j + 1) % tubularSegments;
  27522. var a = i * tubularSegments + j;
  27523. var b = (i + 1) * tubularSegments + j;
  27524. var c = (i + 1) * tubularSegments + jNext;
  27525. var d = i * tubularSegments + jNext;
  27526. indices.push(d);
  27527. indices.push(b);
  27528. indices.push(a);
  27529. indices.push(d);
  27530. indices.push(c);
  27531. indices.push(b);
  27532. }
  27533. }
  27534. // Normals
  27535. VertexData.ComputeNormals(positions, indices, normals);
  27536. // Sides
  27537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27538. // Result
  27539. var vertexData = new VertexData();
  27540. vertexData.indices = indices;
  27541. vertexData.positions = positions;
  27542. vertexData.normals = normals;
  27543. vertexData.uvs = uvs;
  27544. return vertexData;
  27545. };
  27546. // Tools
  27547. /**
  27548. * @param {any} - positions (number[] or Float32Array)
  27549. * @param {any} - indices (number[] or Uint16Array)
  27550. * @param {any} - normals (number[] or Float32Array)
  27551. */
  27552. VertexData.ComputeNormals = function (positions, indices, normals) {
  27553. var index = 0;
  27554. // temp Vector3
  27555. var p1p2 = BABYLON.Vector3.Zero();
  27556. var p3p2 = BABYLON.Vector3.Zero();
  27557. var faceNormal = BABYLON.Vector3.Zero();
  27558. var vertexNormali1 = BABYLON.Vector3.Zero();
  27559. for (index = 0; index < positions.length; index++) {
  27560. normals[index] = 0.0;
  27561. }
  27562. // indice triplet = 1 face
  27563. var nbFaces = indices.length / 3;
  27564. for (index = 0; index < nbFaces; index++) {
  27565. var i1 = indices[index * 3];
  27566. var i2 = indices[index * 3 + 1];
  27567. var i3 = indices[index * 3 + 2];
  27568. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27569. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27570. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27571. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27572. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27573. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27574. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27575. faceNormal.normalize();
  27576. normals[i1 * 3] += faceNormal.x;
  27577. normals[i1 * 3 + 1] += faceNormal.y;
  27578. normals[i1 * 3 + 2] += faceNormal.z;
  27579. normals[i2 * 3] += faceNormal.x;
  27580. normals[i2 * 3 + 1] += faceNormal.y;
  27581. normals[i2 * 3 + 2] += faceNormal.z;
  27582. normals[i3 * 3] += faceNormal.x;
  27583. normals[i3 * 3 + 1] += faceNormal.y;
  27584. normals[i3 * 3 + 2] += faceNormal.z;
  27585. }
  27586. // last normalization
  27587. for (index = 0; index < normals.length / 3; index++) {
  27588. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27589. vertexNormali1.normalize();
  27590. normals[index * 3] = vertexNormali1.x;
  27591. normals[index * 3 + 1] = vertexNormali1.y;
  27592. normals[index * 3 + 2] = vertexNormali1.z;
  27593. }
  27594. };
  27595. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27596. var li = indices.length;
  27597. var ln = normals.length;
  27598. var i;
  27599. var n;
  27600. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27601. switch (sideOrientation) {
  27602. case BABYLON.Mesh.FRONTSIDE:
  27603. // nothing changed
  27604. break;
  27605. case BABYLON.Mesh.BACKSIDE:
  27606. var tmp;
  27607. // indices
  27608. for (i = 0; i < li; i += 3) {
  27609. tmp = indices[i];
  27610. indices[i] = indices[i + 2];
  27611. indices[i + 2] = tmp;
  27612. }
  27613. // normals
  27614. for (n = 0; n < ln; n++) {
  27615. normals[n] = -normals[n];
  27616. }
  27617. break;
  27618. case BABYLON.Mesh.DOUBLESIDE:
  27619. // positions
  27620. var lp = positions.length;
  27621. var l = lp / 3;
  27622. for (var p = 0; p < lp; p++) {
  27623. positions[lp + p] = positions[p];
  27624. }
  27625. // indices
  27626. for (i = 0; i < li; i += 3) {
  27627. indices[i + li] = indices[i + 2] + l;
  27628. indices[i + 1 + li] = indices[i + 1] + l;
  27629. indices[i + 2 + li] = indices[i] + l;
  27630. }
  27631. // normals
  27632. for (n = 0; n < ln; n++) {
  27633. normals[ln + n] = -normals[n];
  27634. }
  27635. // uvs
  27636. var lu = uvs.length;
  27637. for (var u = 0; u < lu; u++) {
  27638. uvs[u + lu] = uvs[u];
  27639. }
  27640. break;
  27641. }
  27642. };
  27643. return VertexData;
  27644. })();
  27645. BABYLON.VertexData = VertexData;
  27646. })(BABYLON || (BABYLON = {}));
  27647. var BABYLON;
  27648. (function (BABYLON) {
  27649. var AnaglyphPostProcess = (function (_super) {
  27650. __extends(AnaglyphPostProcess, _super);
  27651. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27652. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27653. }
  27654. return AnaglyphPostProcess;
  27655. })(BABYLON.PostProcess);
  27656. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27657. })(BABYLON || (BABYLON = {}));
  27658. var BABYLON;
  27659. (function (BABYLON) {
  27660. var Tags = (function () {
  27661. function Tags() {
  27662. }
  27663. Tags.EnableFor = function (obj) {
  27664. obj._tags = obj._tags || {};
  27665. obj.hasTags = function () {
  27666. return Tags.HasTags(obj);
  27667. };
  27668. obj.addTags = function (tagsString) {
  27669. return Tags.AddTagsTo(obj, tagsString);
  27670. };
  27671. obj.removeTags = function (tagsString) {
  27672. return Tags.RemoveTagsFrom(obj, tagsString);
  27673. };
  27674. obj.matchesTagsQuery = function (tagsQuery) {
  27675. return Tags.MatchesQuery(obj, tagsQuery);
  27676. };
  27677. };
  27678. Tags.DisableFor = function (obj) {
  27679. delete obj._tags;
  27680. delete obj.hasTags;
  27681. delete obj.addTags;
  27682. delete obj.removeTags;
  27683. delete obj.matchesTagsQuery;
  27684. };
  27685. Tags.HasTags = function (obj) {
  27686. if (!obj._tags) {
  27687. return false;
  27688. }
  27689. return !BABYLON.Tools.IsEmpty(obj._tags);
  27690. };
  27691. Tags.GetTags = function (obj) {
  27692. if (!obj._tags) {
  27693. return null;
  27694. }
  27695. return obj._tags;
  27696. };
  27697. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27698. // a tag cannot start with '||', '&&', and '!'
  27699. // it cannot contain whitespaces
  27700. Tags.AddTagsTo = function (obj, tagsString) {
  27701. if (!tagsString) {
  27702. return;
  27703. }
  27704. var tags = tagsString.split(" ");
  27705. for (var t in tags) {
  27706. Tags._AddTagTo(obj, tags[t]);
  27707. }
  27708. };
  27709. Tags._AddTagTo = function (obj, tag) {
  27710. tag = tag.trim();
  27711. if (tag === "" || tag === "true" || tag === "false") {
  27712. return;
  27713. }
  27714. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27715. return;
  27716. }
  27717. Tags.EnableFor(obj);
  27718. obj._tags[tag] = true;
  27719. };
  27720. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27721. if (!Tags.HasTags(obj)) {
  27722. return;
  27723. }
  27724. var tags = tagsString.split(" ");
  27725. for (var t in tags) {
  27726. Tags._RemoveTagFrom(obj, tags[t]);
  27727. }
  27728. };
  27729. Tags._RemoveTagFrom = function (obj, tag) {
  27730. delete obj._tags[tag];
  27731. };
  27732. Tags.MatchesQuery = function (obj, tagsQuery) {
  27733. if (tagsQuery === undefined) {
  27734. return true;
  27735. }
  27736. if (tagsQuery === "") {
  27737. return Tags.HasTags(obj);
  27738. }
  27739. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27740. };
  27741. return Tags;
  27742. })();
  27743. BABYLON.Tags = Tags;
  27744. })(BABYLON || (BABYLON = {}));
  27745. var BABYLON;
  27746. (function (BABYLON) {
  27747. var Internals;
  27748. (function (Internals) {
  27749. var AndOrNotEvaluator = (function () {
  27750. function AndOrNotEvaluator() {
  27751. }
  27752. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27753. if (!query.match(/\([^\(\)]*\)/g)) {
  27754. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27755. }
  27756. else {
  27757. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27758. // remove parenthesis
  27759. r = r.slice(1, r.length - 1);
  27760. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27761. });
  27762. }
  27763. if (query === "true") {
  27764. return true;
  27765. }
  27766. if (query === "false") {
  27767. return false;
  27768. }
  27769. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27770. };
  27771. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27772. evaluateCallback = evaluateCallback || (function (r) {
  27773. return r === "true" ? true : false;
  27774. });
  27775. var result;
  27776. var or = parenthesisContent.split("||");
  27777. for (var i in or) {
  27778. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27779. var and = ori.split("&&");
  27780. if (and.length > 1) {
  27781. for (var j = 0; j < and.length; ++j) {
  27782. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27783. if (andj !== "true" && andj !== "false") {
  27784. if (andj[0] === "!") {
  27785. result = !evaluateCallback(andj.substring(1));
  27786. }
  27787. else {
  27788. result = evaluateCallback(andj);
  27789. }
  27790. }
  27791. else {
  27792. result = andj === "true" ? true : false;
  27793. }
  27794. if (!result) {
  27795. ori = "false";
  27796. break;
  27797. }
  27798. }
  27799. }
  27800. if (result || ori === "true") {
  27801. result = true;
  27802. break;
  27803. }
  27804. // result equals false (or undefined)
  27805. if (ori !== "true" && ori !== "false") {
  27806. if (ori[0] === "!") {
  27807. result = !evaluateCallback(ori.substring(1));
  27808. }
  27809. else {
  27810. result = evaluateCallback(ori);
  27811. }
  27812. }
  27813. else {
  27814. result = ori === "true" ? true : false;
  27815. }
  27816. }
  27817. // the whole parenthesis scope is replaced by 'true' or 'false'
  27818. return result ? "true" : "false";
  27819. };
  27820. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27821. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27822. // remove whitespaces
  27823. r = r.replace(/[\s]/g, function () { return ""; });
  27824. return r.length % 2 ? "!" : "";
  27825. });
  27826. booleanString = booleanString.trim();
  27827. if (booleanString === "!true") {
  27828. booleanString = "false";
  27829. }
  27830. else if (booleanString === "!false") {
  27831. booleanString = "true";
  27832. }
  27833. return booleanString;
  27834. };
  27835. return AndOrNotEvaluator;
  27836. })();
  27837. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27838. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27839. })(BABYLON || (BABYLON = {}));
  27840. var BABYLON;
  27841. (function (BABYLON) {
  27842. var PostProcessRenderPass = (function () {
  27843. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27844. this._enabled = true;
  27845. this._refCount = 0;
  27846. this._name = name;
  27847. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27848. this.setRenderList(renderList);
  27849. this._renderTexture.onBeforeRender = beforeRender;
  27850. this._renderTexture.onAfterRender = afterRender;
  27851. this._scene = scene;
  27852. this._renderList = renderList;
  27853. }
  27854. // private
  27855. PostProcessRenderPass.prototype._incRefCount = function () {
  27856. if (this._refCount === 0) {
  27857. this._scene.customRenderTargets.push(this._renderTexture);
  27858. }
  27859. return ++this._refCount;
  27860. };
  27861. PostProcessRenderPass.prototype._decRefCount = function () {
  27862. this._refCount--;
  27863. if (this._refCount <= 0) {
  27864. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27865. }
  27866. return this._refCount;
  27867. };
  27868. PostProcessRenderPass.prototype._update = function () {
  27869. this.setRenderList(this._renderList);
  27870. };
  27871. // public
  27872. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27873. this._renderTexture.renderList = renderList;
  27874. };
  27875. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27876. return this._renderTexture;
  27877. };
  27878. return PostProcessRenderPass;
  27879. })();
  27880. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27881. })(BABYLON || (BABYLON = {}));
  27882. var BABYLON;
  27883. (function (BABYLON) {
  27884. var PostProcessRenderEffect = (function () {
  27885. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27886. this._engine = engine;
  27887. this._name = name;
  27888. this._singleInstance = singleInstance || true;
  27889. this._getPostProcess = getPostProcess;
  27890. this._cameras = [];
  27891. this._indicesForCamera = [];
  27892. this._postProcesses = {};
  27893. this._renderPasses = {};
  27894. this._renderEffectAsPasses = {};
  27895. }
  27896. PostProcessRenderEffect.prototype._update = function () {
  27897. for (var renderPassName in this._renderPasses) {
  27898. this._renderPasses[renderPassName]._update();
  27899. }
  27900. };
  27901. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27902. this._renderPasses[renderPass._name] = renderPass;
  27903. this._linkParameters();
  27904. };
  27905. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27906. delete this._renderPasses[renderPass._name];
  27907. this._linkParameters();
  27908. };
  27909. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27910. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27911. this._linkParameters();
  27912. };
  27913. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27914. for (var renderPassName in this._renderPasses) {
  27915. if (renderPassName === passName) {
  27916. return this._renderPasses[passName];
  27917. }
  27918. }
  27919. };
  27920. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27921. this._renderPasses = {};
  27922. this._linkParameters();
  27923. };
  27924. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27925. var cameraKey;
  27926. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27927. for (var i = 0; i < _cam.length; i++) {
  27928. var camera = _cam[i];
  27929. var cameraName = camera.name;
  27930. if (this._singleInstance) {
  27931. cameraKey = 0;
  27932. }
  27933. else {
  27934. cameraKey = cameraName;
  27935. }
  27936. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27937. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27938. if (!this._indicesForCamera[cameraName]) {
  27939. this._indicesForCamera[cameraName] = [];
  27940. }
  27941. this._indicesForCamera[cameraName].push(index);
  27942. if (this._cameras.indexOf(camera) === -1) {
  27943. this._cameras[cameraName] = camera;
  27944. }
  27945. for (var passName in this._renderPasses) {
  27946. this._renderPasses[passName]._incRefCount();
  27947. }
  27948. }
  27949. this._linkParameters();
  27950. };
  27951. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27952. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27953. for (var i = 0; i < _cam.length; i++) {
  27954. var camera = _cam[i];
  27955. var cameraName = camera.name;
  27956. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27957. var index = this._cameras.indexOf(cameraName);
  27958. this._indicesForCamera.splice(index, 1);
  27959. this._cameras.splice(index, 1);
  27960. for (var passName in this._renderPasses) {
  27961. this._renderPasses[passName]._decRefCount();
  27962. }
  27963. }
  27964. };
  27965. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27966. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27967. for (var i = 0; i < _cam.length; i++) {
  27968. var camera = _cam[i];
  27969. var cameraName = camera.name;
  27970. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27971. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27972. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27973. }
  27974. }
  27975. for (var passName in this._renderPasses) {
  27976. this._renderPasses[passName]._incRefCount();
  27977. }
  27978. }
  27979. };
  27980. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27981. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27982. for (var i = 0; i < _cam.length; i++) {
  27983. var camera = _cam[i];
  27984. var cameraName = camera.Name;
  27985. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27986. for (var passName in this._renderPasses) {
  27987. this._renderPasses[passName]._decRefCount();
  27988. }
  27989. }
  27990. };
  27991. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27992. if (this._singleInstance) {
  27993. return this._postProcesses[0];
  27994. }
  27995. else {
  27996. return this._postProcesses[camera.name];
  27997. }
  27998. };
  27999. PostProcessRenderEffect.prototype._linkParameters = function () {
  28000. var _this = this;
  28001. for (var index in this._postProcesses) {
  28002. if (this.applyParameters) {
  28003. this.applyParameters(this._postProcesses[index]);
  28004. }
  28005. this._postProcesses[index].onBeforeRender = function (effect) {
  28006. _this._linkTextures(effect);
  28007. };
  28008. }
  28009. };
  28010. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  28011. for (var renderPassName in this._renderPasses) {
  28012. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  28013. }
  28014. for (var renderEffectName in this._renderEffectAsPasses) {
  28015. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  28016. }
  28017. };
  28018. return PostProcessRenderEffect;
  28019. })();
  28020. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  28021. })(BABYLON || (BABYLON = {}));
  28022. var BABYLON;
  28023. (function (BABYLON) {
  28024. var PostProcessRenderPipeline = (function () {
  28025. function PostProcessRenderPipeline(engine, name) {
  28026. this._engine = engine;
  28027. this._name = name;
  28028. this._renderEffects = {};
  28029. this._renderEffectsForIsolatedPass = {};
  28030. this._cameras = [];
  28031. }
  28032. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  28033. this._renderEffects[renderEffect._name] = renderEffect;
  28034. };
  28035. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  28036. var renderEffects = this._renderEffects[renderEffectName];
  28037. if (!renderEffects) {
  28038. return;
  28039. }
  28040. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28041. };
  28042. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  28043. var renderEffects = this._renderEffects[renderEffectName];
  28044. if (!renderEffects) {
  28045. return;
  28046. }
  28047. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28048. };
  28049. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  28050. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28051. var indicesToDelete = [];
  28052. for (var i = 0; i < _cam.length; i++) {
  28053. var camera = _cam[i];
  28054. var cameraName = camera.name;
  28055. if (this._cameras.indexOf(camera) === -1) {
  28056. this._cameras[cameraName] = camera;
  28057. }
  28058. else if (unique) {
  28059. indicesToDelete.push(i);
  28060. }
  28061. }
  28062. for (var i = 0; i < indicesToDelete.length; i++) {
  28063. cameras.splice(indicesToDelete[i], 1);
  28064. }
  28065. for (var renderEffectName in this._renderEffects) {
  28066. this._renderEffects[renderEffectName]._attachCameras(_cam);
  28067. }
  28068. };
  28069. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  28070. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28071. for (var renderEffectName in this._renderEffects) {
  28072. this._renderEffects[renderEffectName]._detachCameras(_cam);
  28073. }
  28074. for (var i = 0; i < _cam.length; i++) {
  28075. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  28076. }
  28077. };
  28078. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  28079. var _this = this;
  28080. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28081. var pass = null;
  28082. for (var renderEffectName in this._renderEffects) {
  28083. pass = this._renderEffects[renderEffectName].getPass(passName);
  28084. if (pass != null) {
  28085. break;
  28086. }
  28087. }
  28088. if (pass === null) {
  28089. return;
  28090. }
  28091. for (var renderEffectName in this._renderEffects) {
  28092. this._renderEffects[renderEffectName]._disable(_cam);
  28093. }
  28094. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  28095. for (var i = 0; i < _cam.length; i++) {
  28096. var camera = _cam[i];
  28097. var cameraName = camera.name;
  28098. 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); });
  28099. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  28100. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  28101. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  28102. }
  28103. };
  28104. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  28105. var _this = this;
  28106. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28107. for (var i = 0; i < _cam.length; i++) {
  28108. var camera = _cam[i];
  28109. var cameraName = camera.name;
  28110. 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); });
  28111. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  28112. }
  28113. for (var renderEffectName in this._renderEffects) {
  28114. this._renderEffects[renderEffectName]._enable(_cam);
  28115. }
  28116. };
  28117. PostProcessRenderPipeline.prototype._update = function () {
  28118. for (var renderEffectName in this._renderEffects) {
  28119. this._renderEffects[renderEffectName]._update();
  28120. }
  28121. for (var i = 0; i < this._cameras.length; i++) {
  28122. var cameraName = this._cameras[i].name;
  28123. if (this._renderEffectsForIsolatedPass[cameraName]) {
  28124. this._renderEffectsForIsolatedPass[cameraName]._update();
  28125. }
  28126. }
  28127. };
  28128. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  28129. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  28130. return PostProcessRenderPipeline;
  28131. })();
  28132. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  28133. })(BABYLON || (BABYLON = {}));
  28134. var BABYLON;
  28135. (function (BABYLON) {
  28136. var PostProcessRenderPipelineManager = (function () {
  28137. function PostProcessRenderPipelineManager() {
  28138. this._renderPipelines = {};
  28139. }
  28140. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  28141. this._renderPipelines[renderPipeline._name] = renderPipeline;
  28142. };
  28143. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  28144. var renderPipeline = this._renderPipelines[renderPipelineName];
  28145. if (!renderPipeline) {
  28146. return;
  28147. }
  28148. renderPipeline._attachCameras(cameras, unique);
  28149. };
  28150. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  28151. var renderPipeline = this._renderPipelines[renderPipelineName];
  28152. if (!renderPipeline) {
  28153. return;
  28154. }
  28155. renderPipeline._detachCameras(cameras);
  28156. };
  28157. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28158. var renderPipeline = this._renderPipelines[renderPipelineName];
  28159. if (!renderPipeline) {
  28160. return;
  28161. }
  28162. renderPipeline._enableEffect(renderEffectName, cameras);
  28163. };
  28164. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28165. var renderPipeline = this._renderPipelines[renderPipelineName];
  28166. if (!renderPipeline) {
  28167. return;
  28168. }
  28169. renderPipeline._disableEffect(renderEffectName, cameras);
  28170. };
  28171. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  28172. var renderPipeline = this._renderPipelines[renderPipelineName];
  28173. if (!renderPipeline) {
  28174. return;
  28175. }
  28176. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  28177. };
  28178. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  28179. var renderPipeline = this._renderPipelines[renderPipelineName];
  28180. if (!renderPipeline) {
  28181. return;
  28182. }
  28183. renderPipeline._disableDisplayOnlyPass(cameras);
  28184. };
  28185. PostProcessRenderPipelineManager.prototype.update = function () {
  28186. for (var renderPipelineName in this._renderPipelines) {
  28187. this._renderPipelines[renderPipelineName]._update();
  28188. }
  28189. };
  28190. return PostProcessRenderPipelineManager;
  28191. })();
  28192. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  28193. })(BABYLON || (BABYLON = {}));
  28194. var BABYLON;
  28195. (function (BABYLON) {
  28196. var DisplayPassPostProcess = (function (_super) {
  28197. __extends(DisplayPassPostProcess, _super);
  28198. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28199. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28200. }
  28201. return DisplayPassPostProcess;
  28202. })(BABYLON.PostProcess);
  28203. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28204. })(BABYLON || (BABYLON = {}));
  28205. var BABYLON;
  28206. (function (BABYLON) {
  28207. var BoundingBoxRenderer = (function () {
  28208. function BoundingBoxRenderer(scene) {
  28209. this.frontColor = new BABYLON.Color3(1, 1, 1);
  28210. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  28211. this.showBackLines = true;
  28212. this.renderList = new BABYLON.SmartArray(32);
  28213. this._scene = scene;
  28214. }
  28215. BoundingBoxRenderer.prototype._prepareRessources = function () {
  28216. if (this._colorShader) {
  28217. return;
  28218. }
  28219. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  28220. attributes: ["position"],
  28221. uniforms: ["worldViewProjection", "color"]
  28222. });
  28223. var engine = this._scene.getEngine();
  28224. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  28225. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  28226. 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]);
  28227. };
  28228. BoundingBoxRenderer.prototype.reset = function () {
  28229. this.renderList.reset();
  28230. };
  28231. BoundingBoxRenderer.prototype.render = function () {
  28232. if (this.renderList.length === 0) {
  28233. return;
  28234. }
  28235. this._prepareRessources();
  28236. if (!this._colorShader.isReady()) {
  28237. return;
  28238. }
  28239. var engine = this._scene.getEngine();
  28240. engine.setDepthWrite(false);
  28241. this._colorShader._preBind();
  28242. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  28243. var boundingBox = this.renderList.data[boundingBoxIndex];
  28244. var min = boundingBox.minimum;
  28245. var max = boundingBox.maximum;
  28246. var diff = max.subtract(min);
  28247. var median = min.add(diff.scale(0.5));
  28248. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  28249. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  28250. .multiply(boundingBox.getWorldMatrix());
  28251. // VBOs
  28252. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  28253. if (this.showBackLines) {
  28254. // Back
  28255. engine.setDepthFunctionToGreaterOrEqual();
  28256. this._scene.resetCachedMaterial();
  28257. this._colorShader.setColor4("color", this.backColor.toColor4());
  28258. this._colorShader.bind(worldMatrix);
  28259. // Draw order
  28260. engine.draw(false, 0, 24);
  28261. }
  28262. // Front
  28263. engine.setDepthFunctionToLess();
  28264. this._scene.resetCachedMaterial();
  28265. this._colorShader.setColor4("color", this.frontColor.toColor4());
  28266. this._colorShader.bind(worldMatrix);
  28267. // Draw order
  28268. engine.draw(false, 0, 24);
  28269. }
  28270. this._colorShader.unbind();
  28271. engine.setDepthFunctionToLessOrEqual();
  28272. engine.setDepthWrite(true);
  28273. };
  28274. BoundingBoxRenderer.prototype.dispose = function () {
  28275. if (!this._colorShader) {
  28276. return;
  28277. }
  28278. this._colorShader.dispose();
  28279. this._vb.dispose();
  28280. this._scene.getEngine()._releaseBuffer(this._ib);
  28281. };
  28282. return BoundingBoxRenderer;
  28283. })();
  28284. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  28285. })(BABYLON || (BABYLON = {}));
  28286. var BABYLON;
  28287. (function (BABYLON) {
  28288. var Condition = (function () {
  28289. function Condition(actionManager) {
  28290. this._actionManager = actionManager;
  28291. }
  28292. Condition.prototype.isValid = function () {
  28293. return true;
  28294. };
  28295. Condition.prototype._getProperty = function (propertyPath) {
  28296. return this._actionManager._getProperty(propertyPath);
  28297. };
  28298. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  28299. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28300. };
  28301. return Condition;
  28302. })();
  28303. BABYLON.Condition = Condition;
  28304. var ValueCondition = (function (_super) {
  28305. __extends(ValueCondition, _super);
  28306. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  28307. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  28308. _super.call(this, actionManager);
  28309. this.propertyPath = propertyPath;
  28310. this.value = value;
  28311. this.operator = operator;
  28312. this._target = this._getEffectiveTarget(target, this.propertyPath);
  28313. this._property = this._getProperty(this.propertyPath);
  28314. }
  28315. Object.defineProperty(ValueCondition, "IsEqual", {
  28316. get: function () {
  28317. return ValueCondition._IsEqual;
  28318. },
  28319. enumerable: true,
  28320. configurable: true
  28321. });
  28322. Object.defineProperty(ValueCondition, "IsDifferent", {
  28323. get: function () {
  28324. return ValueCondition._IsDifferent;
  28325. },
  28326. enumerable: true,
  28327. configurable: true
  28328. });
  28329. Object.defineProperty(ValueCondition, "IsGreater", {
  28330. get: function () {
  28331. return ValueCondition._IsGreater;
  28332. },
  28333. enumerable: true,
  28334. configurable: true
  28335. });
  28336. Object.defineProperty(ValueCondition, "IsLesser", {
  28337. get: function () {
  28338. return ValueCondition._IsLesser;
  28339. },
  28340. enumerable: true,
  28341. configurable: true
  28342. });
  28343. // Methods
  28344. ValueCondition.prototype.isValid = function () {
  28345. switch (this.operator) {
  28346. case ValueCondition.IsGreater:
  28347. return this._target[this._property] > this.value;
  28348. case ValueCondition.IsLesser:
  28349. return this._target[this._property] < this.value;
  28350. case ValueCondition.IsEqual:
  28351. case ValueCondition.IsDifferent:
  28352. var check;
  28353. if (this.value.equals) {
  28354. check = this.value.equals(this._target[this._property]);
  28355. }
  28356. else {
  28357. check = this.value === this._target[this._property];
  28358. }
  28359. return this.operator === ValueCondition.IsEqual ? check : !check;
  28360. }
  28361. return false;
  28362. };
  28363. // Statics
  28364. ValueCondition._IsEqual = 0;
  28365. ValueCondition._IsDifferent = 1;
  28366. ValueCondition._IsGreater = 2;
  28367. ValueCondition._IsLesser = 3;
  28368. return ValueCondition;
  28369. })(Condition);
  28370. BABYLON.ValueCondition = ValueCondition;
  28371. var PredicateCondition = (function (_super) {
  28372. __extends(PredicateCondition, _super);
  28373. function PredicateCondition(actionManager, predicate) {
  28374. _super.call(this, actionManager);
  28375. this.predicate = predicate;
  28376. }
  28377. PredicateCondition.prototype.isValid = function () {
  28378. return this.predicate();
  28379. };
  28380. return PredicateCondition;
  28381. })(Condition);
  28382. BABYLON.PredicateCondition = PredicateCondition;
  28383. var StateCondition = (function (_super) {
  28384. __extends(StateCondition, _super);
  28385. function StateCondition(actionManager, target, value) {
  28386. _super.call(this, actionManager);
  28387. this.value = value;
  28388. this._target = target;
  28389. }
  28390. // Methods
  28391. StateCondition.prototype.isValid = function () {
  28392. return this._target.state === this.value;
  28393. };
  28394. return StateCondition;
  28395. })(Condition);
  28396. BABYLON.StateCondition = StateCondition;
  28397. })(BABYLON || (BABYLON = {}));
  28398. var BABYLON;
  28399. (function (BABYLON) {
  28400. var Action = (function () {
  28401. function Action(triggerOptions, condition) {
  28402. this.triggerOptions = triggerOptions;
  28403. if (triggerOptions.parameter) {
  28404. this.trigger = triggerOptions.trigger;
  28405. this._triggerParameter = triggerOptions.parameter;
  28406. }
  28407. else {
  28408. this.trigger = triggerOptions;
  28409. }
  28410. this._nextActiveAction = this;
  28411. this._condition = condition;
  28412. }
  28413. // Methods
  28414. Action.prototype._prepare = function () {
  28415. };
  28416. Action.prototype.getTriggerParameter = function () {
  28417. return this._triggerParameter;
  28418. };
  28419. Action.prototype._executeCurrent = function (evt) {
  28420. if (this._nextActiveAction._condition) {
  28421. var condition = this._nextActiveAction._condition;
  28422. var currentRenderId = this._actionManager.getScene().getRenderId();
  28423. // We cache the current evaluation for the current frame
  28424. if (condition._evaluationId === currentRenderId) {
  28425. if (!condition._currentResult) {
  28426. return;
  28427. }
  28428. }
  28429. else {
  28430. condition._evaluationId = currentRenderId;
  28431. if (!condition.isValid()) {
  28432. condition._currentResult = false;
  28433. return;
  28434. }
  28435. condition._currentResult = true;
  28436. }
  28437. }
  28438. this._nextActiveAction.execute(evt);
  28439. if (this._nextActiveAction._child) {
  28440. if (!this._nextActiveAction._child._actionManager) {
  28441. this._nextActiveAction._child._actionManager = this._actionManager;
  28442. }
  28443. this._nextActiveAction = this._nextActiveAction._child;
  28444. }
  28445. else {
  28446. this._nextActiveAction = this;
  28447. }
  28448. };
  28449. Action.prototype.execute = function (evt) {
  28450. };
  28451. Action.prototype.then = function (action) {
  28452. this._child = action;
  28453. action._actionManager = this._actionManager;
  28454. action._prepare();
  28455. return action;
  28456. };
  28457. Action.prototype._getProperty = function (propertyPath) {
  28458. return this._actionManager._getProperty(propertyPath);
  28459. };
  28460. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28461. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28462. };
  28463. return Action;
  28464. })();
  28465. BABYLON.Action = Action;
  28466. })(BABYLON || (BABYLON = {}));
  28467. var BABYLON;
  28468. (function (BABYLON) {
  28469. /**
  28470. * ActionEvent is the event beint sent when an action is triggered.
  28471. */
  28472. var ActionEvent = (function () {
  28473. /**
  28474. * @constructor
  28475. * @param source The mesh that triggered the action.
  28476. * @param pointerX the X mouse cursor position at the time of the event
  28477. * @param pointerY the Y mouse cursor position at the time of the event
  28478. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28479. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28480. */
  28481. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28482. this.source = source;
  28483. this.pointerX = pointerX;
  28484. this.pointerY = pointerY;
  28485. this.meshUnderPointer = meshUnderPointer;
  28486. this.sourceEvent = sourceEvent;
  28487. this.additionalData = additionalData;
  28488. }
  28489. /**
  28490. * Helper function to auto-create an ActionEvent from a source mesh.
  28491. * @param source the source mesh that triggered the event
  28492. * @param evt {Event} The original (browser) event
  28493. */
  28494. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28495. var scene = source.getScene();
  28496. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28497. };
  28498. /**
  28499. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28500. * @param scene the scene where the event occurred
  28501. * @param evt {Event} The original (browser) event
  28502. */
  28503. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28504. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28505. };
  28506. return ActionEvent;
  28507. })();
  28508. BABYLON.ActionEvent = ActionEvent;
  28509. /**
  28510. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28511. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28512. */
  28513. var ActionManager = (function () {
  28514. function ActionManager(scene) {
  28515. // Members
  28516. this.actions = new Array();
  28517. this._scene = scene;
  28518. scene._actionManagers.push(this);
  28519. }
  28520. Object.defineProperty(ActionManager, "NothingTrigger", {
  28521. get: function () {
  28522. return ActionManager._NothingTrigger;
  28523. },
  28524. enumerable: true,
  28525. configurable: true
  28526. });
  28527. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28528. get: function () {
  28529. return ActionManager._OnPickTrigger;
  28530. },
  28531. enumerable: true,
  28532. configurable: true
  28533. });
  28534. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28535. get: function () {
  28536. return ActionManager._OnLeftPickTrigger;
  28537. },
  28538. enumerable: true,
  28539. configurable: true
  28540. });
  28541. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28542. get: function () {
  28543. return ActionManager._OnRightPickTrigger;
  28544. },
  28545. enumerable: true,
  28546. configurable: true
  28547. });
  28548. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28549. get: function () {
  28550. return ActionManager._OnCenterPickTrigger;
  28551. },
  28552. enumerable: true,
  28553. configurable: true
  28554. });
  28555. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28556. get: function () {
  28557. return ActionManager._OnPointerOverTrigger;
  28558. },
  28559. enumerable: true,
  28560. configurable: true
  28561. });
  28562. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28563. get: function () {
  28564. return ActionManager._OnPointerOutTrigger;
  28565. },
  28566. enumerable: true,
  28567. configurable: true
  28568. });
  28569. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28570. get: function () {
  28571. return ActionManager._OnEveryFrameTrigger;
  28572. },
  28573. enumerable: true,
  28574. configurable: true
  28575. });
  28576. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28577. get: function () {
  28578. return ActionManager._OnIntersectionEnterTrigger;
  28579. },
  28580. enumerable: true,
  28581. configurable: true
  28582. });
  28583. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28584. get: function () {
  28585. return ActionManager._OnIntersectionExitTrigger;
  28586. },
  28587. enumerable: true,
  28588. configurable: true
  28589. });
  28590. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28591. get: function () {
  28592. return ActionManager._OnKeyDownTrigger;
  28593. },
  28594. enumerable: true,
  28595. configurable: true
  28596. });
  28597. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28598. get: function () {
  28599. return ActionManager._OnKeyUpTrigger;
  28600. },
  28601. enumerable: true,
  28602. configurable: true
  28603. });
  28604. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28605. get: function () {
  28606. return ActionManager._OnPickUpTrigger;
  28607. },
  28608. enumerable: true,
  28609. configurable: true
  28610. });
  28611. // Methods
  28612. ActionManager.prototype.dispose = function () {
  28613. var index = this._scene._actionManagers.indexOf(this);
  28614. if (index > -1) {
  28615. this._scene._actionManagers.splice(index, 1);
  28616. }
  28617. };
  28618. ActionManager.prototype.getScene = function () {
  28619. return this._scene;
  28620. };
  28621. /**
  28622. * Does this action manager handles actions of any of the given triggers
  28623. * @param {number[]} triggers - the triggers to be tested
  28624. * @return {boolean} whether one (or more) of the triggers is handeled
  28625. */
  28626. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28627. for (var index = 0; index < this.actions.length; index++) {
  28628. var action = this.actions[index];
  28629. if (triggers.indexOf(action.trigger) > -1) {
  28630. return true;
  28631. }
  28632. }
  28633. return false;
  28634. };
  28635. /**
  28636. * Does this action manager handles actions of a given trigger
  28637. * @param {number} trigger - the trigger to be tested
  28638. * @return {boolean} whether the trigger is handeled
  28639. */
  28640. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28641. for (var index = 0; index < this.actions.length; index++) {
  28642. var action = this.actions[index];
  28643. if (action.trigger === trigger) {
  28644. return true;
  28645. }
  28646. }
  28647. return false;
  28648. };
  28649. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28650. /**
  28651. * Does this action manager has pointer triggers
  28652. * @return {boolean} whether or not it has pointer triggers
  28653. */
  28654. get: function () {
  28655. for (var index = 0; index < this.actions.length; index++) {
  28656. var action = this.actions[index];
  28657. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28658. return true;
  28659. }
  28660. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28661. return true;
  28662. }
  28663. }
  28664. return false;
  28665. },
  28666. enumerable: true,
  28667. configurable: true
  28668. });
  28669. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28670. /**
  28671. * Does this action manager has pick triggers
  28672. * @return {boolean} whether or not it has pick triggers
  28673. */
  28674. get: function () {
  28675. for (var index = 0; index < this.actions.length; index++) {
  28676. var action = this.actions[index];
  28677. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28678. return true;
  28679. }
  28680. }
  28681. return false;
  28682. },
  28683. enumerable: true,
  28684. configurable: true
  28685. });
  28686. /**
  28687. * Registers an action to this action manager
  28688. * @param {BABYLON.Action} action - the action to be registered
  28689. * @return {BABYLON.Action} the action amended (prepared) after registration
  28690. */
  28691. ActionManager.prototype.registerAction = function (action) {
  28692. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28693. if (this.getScene().actionManager !== this) {
  28694. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28695. return null;
  28696. }
  28697. }
  28698. this.actions.push(action);
  28699. action._actionManager = this;
  28700. action._prepare();
  28701. return action;
  28702. };
  28703. /**
  28704. * Process a specific trigger
  28705. * @param {number} trigger - the trigger to process
  28706. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28707. */
  28708. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28709. for (var index = 0; index < this.actions.length; index++) {
  28710. var action = this.actions[index];
  28711. if (action.trigger === trigger) {
  28712. if (trigger === ActionManager.OnKeyUpTrigger
  28713. || trigger === ActionManager.OnKeyDownTrigger) {
  28714. var parameter = action.getTriggerParameter();
  28715. if (parameter) {
  28716. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28717. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28718. if (actualkey !== parameter.toLowerCase()) {
  28719. continue;
  28720. }
  28721. }
  28722. }
  28723. action._executeCurrent(evt);
  28724. }
  28725. }
  28726. };
  28727. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28728. var properties = propertyPath.split(".");
  28729. for (var index = 0; index < properties.length - 1; index++) {
  28730. target = target[properties[index]];
  28731. }
  28732. return target;
  28733. };
  28734. ActionManager.prototype._getProperty = function (propertyPath) {
  28735. var properties = propertyPath.split(".");
  28736. return properties[properties.length - 1];
  28737. };
  28738. // Statics
  28739. ActionManager._NothingTrigger = 0;
  28740. ActionManager._OnPickTrigger = 1;
  28741. ActionManager._OnLeftPickTrigger = 2;
  28742. ActionManager._OnRightPickTrigger = 3;
  28743. ActionManager._OnCenterPickTrigger = 4;
  28744. ActionManager._OnPointerOverTrigger = 5;
  28745. ActionManager._OnPointerOutTrigger = 6;
  28746. ActionManager._OnEveryFrameTrigger = 7;
  28747. ActionManager._OnIntersectionEnterTrigger = 8;
  28748. ActionManager._OnIntersectionExitTrigger = 9;
  28749. ActionManager._OnKeyDownTrigger = 10;
  28750. ActionManager._OnKeyUpTrigger = 11;
  28751. ActionManager._OnPickUpTrigger = 12;
  28752. return ActionManager;
  28753. })();
  28754. BABYLON.ActionManager = ActionManager;
  28755. })(BABYLON || (BABYLON = {}));
  28756. var BABYLON;
  28757. (function (BABYLON) {
  28758. var InterpolateValueAction = (function (_super) {
  28759. __extends(InterpolateValueAction, _super);
  28760. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  28761. if (duration === void 0) { duration = 1000; }
  28762. _super.call(this, triggerOptions, condition);
  28763. this.propertyPath = propertyPath;
  28764. this.value = value;
  28765. this.duration = duration;
  28766. this.stopOtherAnimations = stopOtherAnimations;
  28767. this.onInterpolationDone = onInterpolationDone;
  28768. this._target = target;
  28769. }
  28770. InterpolateValueAction.prototype._prepare = function () {
  28771. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28772. this._property = this._getProperty(this.propertyPath);
  28773. };
  28774. InterpolateValueAction.prototype.execute = function () {
  28775. var scene = this._actionManager.getScene();
  28776. var keys = [
  28777. {
  28778. frame: 0,
  28779. value: this._target[this._property]
  28780. }, {
  28781. frame: 100,
  28782. value: this.value
  28783. }
  28784. ];
  28785. var dataType;
  28786. if (typeof this.value === "number") {
  28787. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28788. }
  28789. else if (this.value instanceof BABYLON.Color3) {
  28790. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28791. }
  28792. else if (this.value instanceof BABYLON.Vector3) {
  28793. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28794. }
  28795. else if (this.value instanceof BABYLON.Matrix) {
  28796. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28797. }
  28798. else if (this.value instanceof BABYLON.Quaternion) {
  28799. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28800. }
  28801. else {
  28802. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28803. return;
  28804. }
  28805. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28806. animation.setKeys(keys);
  28807. if (this.stopOtherAnimations) {
  28808. scene.stopAnimation(this._target);
  28809. }
  28810. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  28811. };
  28812. return InterpolateValueAction;
  28813. })(BABYLON.Action);
  28814. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28815. })(BABYLON || (BABYLON = {}));
  28816. var BABYLON;
  28817. (function (BABYLON) {
  28818. var SwitchBooleanAction = (function (_super) {
  28819. __extends(SwitchBooleanAction, _super);
  28820. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28821. _super.call(this, triggerOptions, condition);
  28822. this.propertyPath = propertyPath;
  28823. this._target = target;
  28824. }
  28825. SwitchBooleanAction.prototype._prepare = function () {
  28826. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28827. this._property = this._getProperty(this.propertyPath);
  28828. };
  28829. SwitchBooleanAction.prototype.execute = function () {
  28830. this._target[this._property] = !this._target[this._property];
  28831. };
  28832. return SwitchBooleanAction;
  28833. })(BABYLON.Action);
  28834. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28835. var SetStateAction = (function (_super) {
  28836. __extends(SetStateAction, _super);
  28837. function SetStateAction(triggerOptions, target, value, condition) {
  28838. _super.call(this, triggerOptions, condition);
  28839. this.value = value;
  28840. this._target = target;
  28841. }
  28842. SetStateAction.prototype.execute = function () {
  28843. this._target.state = this.value;
  28844. };
  28845. return SetStateAction;
  28846. })(BABYLON.Action);
  28847. BABYLON.SetStateAction = SetStateAction;
  28848. var SetValueAction = (function (_super) {
  28849. __extends(SetValueAction, _super);
  28850. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28851. _super.call(this, triggerOptions, condition);
  28852. this.propertyPath = propertyPath;
  28853. this.value = value;
  28854. this._target = target;
  28855. }
  28856. SetValueAction.prototype._prepare = function () {
  28857. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28858. this._property = this._getProperty(this.propertyPath);
  28859. };
  28860. SetValueAction.prototype.execute = function () {
  28861. this._target[this._property] = this.value;
  28862. };
  28863. return SetValueAction;
  28864. })(BABYLON.Action);
  28865. BABYLON.SetValueAction = SetValueAction;
  28866. var IncrementValueAction = (function (_super) {
  28867. __extends(IncrementValueAction, _super);
  28868. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28869. _super.call(this, triggerOptions, condition);
  28870. this.propertyPath = propertyPath;
  28871. this.value = value;
  28872. this._target = target;
  28873. }
  28874. IncrementValueAction.prototype._prepare = function () {
  28875. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28876. this._property = this._getProperty(this.propertyPath);
  28877. if (typeof this._target[this._property] !== "number") {
  28878. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28879. }
  28880. };
  28881. IncrementValueAction.prototype.execute = function () {
  28882. this._target[this._property] += this.value;
  28883. };
  28884. return IncrementValueAction;
  28885. })(BABYLON.Action);
  28886. BABYLON.IncrementValueAction = IncrementValueAction;
  28887. var PlayAnimationAction = (function (_super) {
  28888. __extends(PlayAnimationAction, _super);
  28889. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28890. _super.call(this, triggerOptions, condition);
  28891. this.from = from;
  28892. this.to = to;
  28893. this.loop = loop;
  28894. this._target = target;
  28895. }
  28896. PlayAnimationAction.prototype._prepare = function () {
  28897. };
  28898. PlayAnimationAction.prototype.execute = function () {
  28899. var scene = this._actionManager.getScene();
  28900. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28901. };
  28902. return PlayAnimationAction;
  28903. })(BABYLON.Action);
  28904. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28905. var StopAnimationAction = (function (_super) {
  28906. __extends(StopAnimationAction, _super);
  28907. function StopAnimationAction(triggerOptions, target, condition) {
  28908. _super.call(this, triggerOptions, condition);
  28909. this._target = target;
  28910. }
  28911. StopAnimationAction.prototype._prepare = function () {
  28912. };
  28913. StopAnimationAction.prototype.execute = function () {
  28914. var scene = this._actionManager.getScene();
  28915. scene.stopAnimation(this._target);
  28916. };
  28917. return StopAnimationAction;
  28918. })(BABYLON.Action);
  28919. BABYLON.StopAnimationAction = StopAnimationAction;
  28920. var DoNothingAction = (function (_super) {
  28921. __extends(DoNothingAction, _super);
  28922. function DoNothingAction(triggerOptions, condition) {
  28923. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28924. _super.call(this, triggerOptions, condition);
  28925. }
  28926. DoNothingAction.prototype.execute = function () {
  28927. };
  28928. return DoNothingAction;
  28929. })(BABYLON.Action);
  28930. BABYLON.DoNothingAction = DoNothingAction;
  28931. var CombineAction = (function (_super) {
  28932. __extends(CombineAction, _super);
  28933. function CombineAction(triggerOptions, children, condition) {
  28934. _super.call(this, triggerOptions, condition);
  28935. this.children = children;
  28936. }
  28937. CombineAction.prototype._prepare = function () {
  28938. for (var index = 0; index < this.children.length; index++) {
  28939. this.children[index]._actionManager = this._actionManager;
  28940. this.children[index]._prepare();
  28941. }
  28942. };
  28943. CombineAction.prototype.execute = function (evt) {
  28944. for (var index = 0; index < this.children.length; index++) {
  28945. this.children[index].execute(evt);
  28946. }
  28947. };
  28948. return CombineAction;
  28949. })(BABYLON.Action);
  28950. BABYLON.CombineAction = CombineAction;
  28951. var ExecuteCodeAction = (function (_super) {
  28952. __extends(ExecuteCodeAction, _super);
  28953. function ExecuteCodeAction(triggerOptions, func, condition) {
  28954. _super.call(this, triggerOptions, condition);
  28955. this.func = func;
  28956. }
  28957. ExecuteCodeAction.prototype.execute = function (evt) {
  28958. this.func(evt);
  28959. };
  28960. return ExecuteCodeAction;
  28961. })(BABYLON.Action);
  28962. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28963. var SetParentAction = (function (_super) {
  28964. __extends(SetParentAction, _super);
  28965. function SetParentAction(triggerOptions, target, parent, condition) {
  28966. _super.call(this, triggerOptions, condition);
  28967. this._target = target;
  28968. this._parent = parent;
  28969. }
  28970. SetParentAction.prototype._prepare = function () {
  28971. };
  28972. SetParentAction.prototype.execute = function () {
  28973. if (this._target.parent === this._parent) {
  28974. return;
  28975. }
  28976. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28977. invertParentWorldMatrix.invert();
  28978. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28979. this._target.parent = this._parent;
  28980. };
  28981. return SetParentAction;
  28982. })(BABYLON.Action);
  28983. BABYLON.SetParentAction = SetParentAction;
  28984. var PlaySoundAction = (function (_super) {
  28985. __extends(PlaySoundAction, _super);
  28986. function PlaySoundAction(triggerOptions, sound, condition) {
  28987. _super.call(this, triggerOptions, condition);
  28988. this._sound = sound;
  28989. }
  28990. PlaySoundAction.prototype._prepare = function () {
  28991. };
  28992. PlaySoundAction.prototype.execute = function () {
  28993. if (this._sound !== undefined)
  28994. this._sound.play();
  28995. };
  28996. return PlaySoundAction;
  28997. })(BABYLON.Action);
  28998. BABYLON.PlaySoundAction = PlaySoundAction;
  28999. var StopSoundAction = (function (_super) {
  29000. __extends(StopSoundAction, _super);
  29001. function StopSoundAction(triggerOptions, sound, condition) {
  29002. _super.call(this, triggerOptions, condition);
  29003. this._sound = sound;
  29004. }
  29005. StopSoundAction.prototype._prepare = function () {
  29006. };
  29007. StopSoundAction.prototype.execute = function () {
  29008. if (this._sound !== undefined)
  29009. this._sound.stop();
  29010. };
  29011. return StopSoundAction;
  29012. })(BABYLON.Action);
  29013. BABYLON.StopSoundAction = StopSoundAction;
  29014. })(BABYLON || (BABYLON = {}));
  29015. var BABYLON;
  29016. (function (BABYLON) {
  29017. var Geometry = (function () {
  29018. function Geometry(id, scene, vertexData, updatable, mesh) {
  29019. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29020. this._totalVertices = 0;
  29021. this._indices = [];
  29022. this._isDisposed = false;
  29023. this.id = id;
  29024. this._engine = scene.getEngine();
  29025. this._meshes = [];
  29026. this._scene = scene;
  29027. // vertexData
  29028. if (vertexData) {
  29029. this.setAllVerticesData(vertexData, updatable);
  29030. }
  29031. else {
  29032. this._totalVertices = 0;
  29033. this._indices = [];
  29034. }
  29035. // applyToMesh
  29036. if (mesh) {
  29037. this.applyToMesh(mesh);
  29038. mesh.computeWorldMatrix(true);
  29039. }
  29040. }
  29041. Geometry.prototype.getScene = function () {
  29042. return this._scene;
  29043. };
  29044. Geometry.prototype.getEngine = function () {
  29045. return this._engine;
  29046. };
  29047. Geometry.prototype.isReady = function () {
  29048. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29049. };
  29050. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29051. vertexData.applyToGeometry(this, updatable);
  29052. this.notifyUpdate();
  29053. };
  29054. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29055. this._vertexBuffers = this._vertexBuffers || {};
  29056. if (this._vertexBuffers[kind]) {
  29057. this._vertexBuffers[kind].dispose();
  29058. }
  29059. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29060. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29061. stride = this._vertexBuffers[kind].getStrideSize();
  29062. this._totalVertices = data.length / stride;
  29063. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29064. var meshes = this._meshes;
  29065. var numOfMeshes = meshes.length;
  29066. for (var index = 0; index < numOfMeshes; index++) {
  29067. var mesh = meshes[index];
  29068. mesh._resetPointsArrayCache();
  29069. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29070. mesh._createGlobalSubMesh();
  29071. mesh.computeWorldMatrix(true);
  29072. }
  29073. }
  29074. this.notifyUpdate(kind);
  29075. };
  29076. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29077. var vertexBuffer = this.getVertexBuffer(kind);
  29078. if (!vertexBuffer) {
  29079. return;
  29080. }
  29081. vertexBuffer.updateDirectly(data, offset);
  29082. this.notifyUpdate(kind);
  29083. };
  29084. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29085. var vertexBuffer = this.getVertexBuffer(kind);
  29086. if (!vertexBuffer) {
  29087. return;
  29088. }
  29089. vertexBuffer.update(data);
  29090. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29091. var extend;
  29092. var stride = vertexBuffer.getStrideSize();
  29093. this._totalVertices = data.length / stride;
  29094. if (updateExtends) {
  29095. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29096. }
  29097. var meshes = this._meshes;
  29098. var numOfMeshes = meshes.length;
  29099. for (var index = 0; index < numOfMeshes; index++) {
  29100. var mesh = meshes[index];
  29101. mesh._resetPointsArrayCache();
  29102. if (updateExtends) {
  29103. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29104. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29105. var subMesh = mesh.subMeshes[subIndex];
  29106. subMesh.refreshBoundingInfo();
  29107. }
  29108. }
  29109. }
  29110. }
  29111. this.notifyUpdate(kind);
  29112. };
  29113. Geometry.prototype.getTotalVertices = function () {
  29114. if (!this.isReady()) {
  29115. return 0;
  29116. }
  29117. return this._totalVertices;
  29118. };
  29119. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  29120. var vertexBuffer = this.getVertexBuffer(kind);
  29121. if (!vertexBuffer) {
  29122. return null;
  29123. }
  29124. var orig = vertexBuffer.getData();
  29125. if (!copyWhenShared || this._meshes.length === 1) {
  29126. return orig;
  29127. }
  29128. else {
  29129. var len = orig.length;
  29130. var copy = [];
  29131. for (var i = 0; i < len; i++) {
  29132. copy.push(orig[i]);
  29133. }
  29134. return copy;
  29135. }
  29136. };
  29137. Geometry.prototype.getVertexBuffer = function (kind) {
  29138. if (!this.isReady()) {
  29139. return null;
  29140. }
  29141. return this._vertexBuffers[kind];
  29142. };
  29143. Geometry.prototype.getVertexBuffers = function () {
  29144. if (!this.isReady()) {
  29145. return null;
  29146. }
  29147. return this._vertexBuffers;
  29148. };
  29149. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29150. if (!this._vertexBuffers) {
  29151. if (this._delayInfo) {
  29152. return this._delayInfo.indexOf(kind) !== -1;
  29153. }
  29154. return false;
  29155. }
  29156. return this._vertexBuffers[kind] !== undefined;
  29157. };
  29158. Geometry.prototype.getVerticesDataKinds = function () {
  29159. var result = [];
  29160. if (!this._vertexBuffers && this._delayInfo) {
  29161. for (var kind in this._delayInfo) {
  29162. result.push(kind);
  29163. }
  29164. }
  29165. else {
  29166. for (kind in this._vertexBuffers) {
  29167. result.push(kind);
  29168. }
  29169. }
  29170. return result;
  29171. };
  29172. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29173. if (this._indexBuffer) {
  29174. this._engine._releaseBuffer(this._indexBuffer);
  29175. }
  29176. this._indices = indices;
  29177. if (this._meshes.length !== 0 && this._indices) {
  29178. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29179. }
  29180. if (totalVertices !== undefined) {
  29181. this._totalVertices = totalVertices;
  29182. }
  29183. var meshes = this._meshes;
  29184. var numOfMeshes = meshes.length;
  29185. for (var index = 0; index < numOfMeshes; index++) {
  29186. meshes[index]._createGlobalSubMesh();
  29187. }
  29188. this.notifyUpdate();
  29189. };
  29190. Geometry.prototype.getTotalIndices = function () {
  29191. if (!this.isReady()) {
  29192. return 0;
  29193. }
  29194. return this._indices.length;
  29195. };
  29196. Geometry.prototype.getIndices = function (copyWhenShared) {
  29197. if (!this.isReady()) {
  29198. return null;
  29199. }
  29200. var orig = this._indices;
  29201. if (!copyWhenShared || this._meshes.length === 1) {
  29202. return orig;
  29203. }
  29204. else {
  29205. var len = orig.length;
  29206. var copy = [];
  29207. for (var i = 0; i < len; i++) {
  29208. copy.push(orig[i]);
  29209. }
  29210. return copy;
  29211. }
  29212. };
  29213. Geometry.prototype.getIndexBuffer = function () {
  29214. if (!this.isReady()) {
  29215. return null;
  29216. }
  29217. return this._indexBuffer;
  29218. };
  29219. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29220. var meshes = this._meshes;
  29221. var index = meshes.indexOf(mesh);
  29222. if (index === -1) {
  29223. return;
  29224. }
  29225. for (var kind in this._vertexBuffers) {
  29226. this._vertexBuffers[kind].dispose();
  29227. }
  29228. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  29229. this._indexBuffer = null;
  29230. }
  29231. meshes.splice(index, 1);
  29232. mesh._geometry = null;
  29233. if (meshes.length === 0 && shouldDispose) {
  29234. this.dispose();
  29235. }
  29236. };
  29237. Geometry.prototype.applyToMesh = function (mesh) {
  29238. if (mesh._geometry === this) {
  29239. return;
  29240. }
  29241. var previousGeometry = mesh._geometry;
  29242. if (previousGeometry) {
  29243. previousGeometry.releaseForMesh(mesh);
  29244. }
  29245. var meshes = this._meshes;
  29246. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29247. mesh._geometry = this;
  29248. this._scene.pushGeometry(this);
  29249. meshes.push(mesh);
  29250. if (this.isReady()) {
  29251. this._applyToMesh(mesh);
  29252. }
  29253. else {
  29254. mesh._boundingInfo = this._boundingInfo;
  29255. }
  29256. };
  29257. Geometry.prototype._applyToMesh = function (mesh) {
  29258. var numOfMeshes = this._meshes.length;
  29259. // vertexBuffers
  29260. for (var kind in this._vertexBuffers) {
  29261. if (numOfMeshes === 1) {
  29262. this._vertexBuffers[kind].create();
  29263. }
  29264. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  29265. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29266. mesh._resetPointsArrayCache();
  29267. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  29268. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29269. mesh._createGlobalSubMesh();
  29270. //bounding info was just created again, world matrix should be applied again.
  29271. mesh._updateBoundingInfo();
  29272. }
  29273. }
  29274. // indexBuffer
  29275. if (numOfMeshes === 1 && this._indices) {
  29276. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29277. }
  29278. if (this._indexBuffer) {
  29279. this._indexBuffer.references = numOfMeshes;
  29280. }
  29281. };
  29282. Geometry.prototype.notifyUpdate = function (kind) {
  29283. if (this.onGeometryUpdated) {
  29284. this.onGeometryUpdated(this, kind);
  29285. }
  29286. };
  29287. Geometry.prototype.load = function (scene, onLoaded) {
  29288. var _this = this;
  29289. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29290. return;
  29291. }
  29292. if (this.isReady()) {
  29293. if (onLoaded) {
  29294. onLoaded();
  29295. }
  29296. return;
  29297. }
  29298. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29299. scene._addPendingData(this);
  29300. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29301. _this._delayLoadingFunction(JSON.parse(data), _this);
  29302. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29303. _this._delayInfo = [];
  29304. scene._removePendingData(_this);
  29305. var meshes = _this._meshes;
  29306. var numOfMeshes = meshes.length;
  29307. for (var index = 0; index < numOfMeshes; index++) {
  29308. _this._applyToMesh(meshes[index]);
  29309. }
  29310. if (onLoaded) {
  29311. onLoaded();
  29312. }
  29313. }, function () { }, scene.database);
  29314. };
  29315. Geometry.prototype.isDisposed = function () {
  29316. return this._isDisposed;
  29317. };
  29318. Geometry.prototype.dispose = function () {
  29319. var meshes = this._meshes;
  29320. var numOfMeshes = meshes.length;
  29321. var index;
  29322. for (index = 0; index < numOfMeshes; index++) {
  29323. this.releaseForMesh(meshes[index]);
  29324. }
  29325. this._meshes = [];
  29326. for (var kind in this._vertexBuffers) {
  29327. this._vertexBuffers[kind].dispose();
  29328. }
  29329. this._vertexBuffers = [];
  29330. this._totalVertices = 0;
  29331. if (this._indexBuffer) {
  29332. this._engine._releaseBuffer(this._indexBuffer);
  29333. }
  29334. this._indexBuffer = null;
  29335. this._indices = [];
  29336. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29337. this.delayLoadingFile = null;
  29338. this._delayLoadingFunction = null;
  29339. this._delayInfo = [];
  29340. this._boundingInfo = null; // todo: .dispose()
  29341. this._scene.removeGeometry(this);
  29342. this._isDisposed = true;
  29343. };
  29344. Geometry.prototype.copy = function (id) {
  29345. var vertexData = new BABYLON.VertexData();
  29346. vertexData.indices = [];
  29347. var indices = this.getIndices();
  29348. for (var index = 0; index < indices.length; index++) {
  29349. vertexData.indices.push(indices[index]);
  29350. }
  29351. var updatable = false;
  29352. var stopChecking = false;
  29353. var kind;
  29354. for (kind in this._vertexBuffers) {
  29355. // using slice() to make a copy of the array and not just reference it
  29356. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  29357. if (!stopChecking) {
  29358. updatable = this.getVertexBuffer(kind).isUpdatable();
  29359. stopChecking = !updatable;
  29360. }
  29361. }
  29362. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29363. geometry.delayLoadState = this.delayLoadState;
  29364. geometry.delayLoadingFile = this.delayLoadingFile;
  29365. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29366. for (kind in this._delayInfo) {
  29367. geometry._delayInfo = geometry._delayInfo || [];
  29368. geometry._delayInfo.push(kind);
  29369. }
  29370. // Bounding info
  29371. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  29372. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29373. return geometry;
  29374. };
  29375. // Statics
  29376. Geometry.ExtractFromMesh = function (mesh, id) {
  29377. var geometry = mesh._geometry;
  29378. if (!geometry) {
  29379. return null;
  29380. }
  29381. return geometry.copy(id);
  29382. };
  29383. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29384. // be aware Math.random() could cause collisions
  29385. Geometry.RandomId = function () {
  29386. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  29387. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  29388. return v.toString(16);
  29389. });
  29390. };
  29391. return Geometry;
  29392. })();
  29393. BABYLON.Geometry = Geometry;
  29394. /////// Primitives //////////////////////////////////////////////
  29395. var Geometry;
  29396. (function (Geometry) {
  29397. var Primitives;
  29398. (function (Primitives) {
  29399. /// Abstract class
  29400. var _Primitive = (function (_super) {
  29401. __extends(_Primitive, _super);
  29402. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  29403. this._beingRegenerated = true;
  29404. this._canBeRegenerated = canBeRegenerated;
  29405. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  29406. this._beingRegenerated = false;
  29407. }
  29408. _Primitive.prototype.canBeRegenerated = function () {
  29409. return this._canBeRegenerated;
  29410. };
  29411. _Primitive.prototype.regenerate = function () {
  29412. if (!this._canBeRegenerated) {
  29413. return;
  29414. }
  29415. this._beingRegenerated = true;
  29416. this.setAllVerticesData(this._regenerateVertexData(), false);
  29417. this._beingRegenerated = false;
  29418. };
  29419. _Primitive.prototype.asNewGeometry = function (id) {
  29420. return _super.prototype.copy.call(this, id);
  29421. };
  29422. // overrides
  29423. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29424. if (!this._beingRegenerated) {
  29425. return;
  29426. }
  29427. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29428. };
  29429. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29430. if (!this._beingRegenerated) {
  29431. return;
  29432. }
  29433. _super.prototype.setVerticesData.call(this, kind, data, false);
  29434. };
  29435. // to override
  29436. // protected
  29437. _Primitive.prototype._regenerateVertexData = function () {
  29438. throw new Error("Abstract method");
  29439. };
  29440. _Primitive.prototype.copy = function (id) {
  29441. throw new Error("Must be overriden in sub-classes.");
  29442. };
  29443. return _Primitive;
  29444. })(Geometry);
  29445. Primitives._Primitive = _Primitive;
  29446. var Ribbon = (function (_super) {
  29447. __extends(Ribbon, _super);
  29448. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29449. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29450. this.pathArray = pathArray;
  29451. this.closeArray = closeArray;
  29452. this.closePath = closePath;
  29453. this.offset = offset;
  29454. this.side = side;
  29455. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29456. }
  29457. Ribbon.prototype._regenerateVertexData = function () {
  29458. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29459. };
  29460. Ribbon.prototype.copy = function (id) {
  29461. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29462. };
  29463. return Ribbon;
  29464. })(_Primitive);
  29465. Primitives.Ribbon = Ribbon;
  29466. var Box = (function (_super) {
  29467. __extends(Box, _super);
  29468. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29469. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29470. this.size = size;
  29471. this.side = side;
  29472. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29473. }
  29474. Box.prototype._regenerateVertexData = function () {
  29475. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29476. };
  29477. Box.prototype.copy = function (id) {
  29478. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29479. };
  29480. return Box;
  29481. })(_Primitive);
  29482. Primitives.Box = Box;
  29483. var Sphere = (function (_super) {
  29484. __extends(Sphere, _super);
  29485. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29486. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29487. this.segments = segments;
  29488. this.diameter = diameter;
  29489. this.side = side;
  29490. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29491. }
  29492. Sphere.prototype._regenerateVertexData = function () {
  29493. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29494. };
  29495. Sphere.prototype.copy = function (id) {
  29496. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29497. };
  29498. return Sphere;
  29499. })(_Primitive);
  29500. Primitives.Sphere = Sphere;
  29501. var Disc = (function (_super) {
  29502. __extends(Disc, _super);
  29503. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29504. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29505. this.radius = radius;
  29506. this.tessellation = tessellation;
  29507. this.side = side;
  29508. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29509. }
  29510. Disc.prototype._regenerateVertexData = function () {
  29511. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29512. };
  29513. Disc.prototype.copy = function (id) {
  29514. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29515. };
  29516. return Disc;
  29517. })(_Primitive);
  29518. Primitives.Disc = Disc;
  29519. var Cylinder = (function (_super) {
  29520. __extends(Cylinder, _super);
  29521. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29522. if (subdivisions === void 0) { subdivisions = 1; }
  29523. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29524. this.height = height;
  29525. this.diameterTop = diameterTop;
  29526. this.diameterBottom = diameterBottom;
  29527. this.tessellation = tessellation;
  29528. this.subdivisions = subdivisions;
  29529. this.side = side;
  29530. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29531. }
  29532. Cylinder.prototype._regenerateVertexData = function () {
  29533. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29534. };
  29535. Cylinder.prototype.copy = function (id) {
  29536. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29537. };
  29538. return Cylinder;
  29539. })(_Primitive);
  29540. Primitives.Cylinder = Cylinder;
  29541. var Torus = (function (_super) {
  29542. __extends(Torus, _super);
  29543. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29544. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29545. this.diameter = diameter;
  29546. this.thickness = thickness;
  29547. this.tessellation = tessellation;
  29548. this.side = side;
  29549. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29550. }
  29551. Torus.prototype._regenerateVertexData = function () {
  29552. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29553. };
  29554. Torus.prototype.copy = function (id) {
  29555. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29556. };
  29557. return Torus;
  29558. })(_Primitive);
  29559. Primitives.Torus = Torus;
  29560. var Ground = (function (_super) {
  29561. __extends(Ground, _super);
  29562. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29563. this.width = width;
  29564. this.height = height;
  29565. this.subdivisions = subdivisions;
  29566. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29567. }
  29568. Ground.prototype._regenerateVertexData = function () {
  29569. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29570. };
  29571. Ground.prototype.copy = function (id) {
  29572. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29573. };
  29574. return Ground;
  29575. })(_Primitive);
  29576. Primitives.Ground = Ground;
  29577. var TiledGround = (function (_super) {
  29578. __extends(TiledGround, _super);
  29579. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29580. this.xmin = xmin;
  29581. this.zmin = zmin;
  29582. this.xmax = xmax;
  29583. this.zmax = zmax;
  29584. this.subdivisions = subdivisions;
  29585. this.precision = precision;
  29586. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29587. }
  29588. TiledGround.prototype._regenerateVertexData = function () {
  29589. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29590. };
  29591. TiledGround.prototype.copy = function (id) {
  29592. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29593. };
  29594. return TiledGround;
  29595. })(_Primitive);
  29596. Primitives.TiledGround = TiledGround;
  29597. var Plane = (function (_super) {
  29598. __extends(Plane, _super);
  29599. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29600. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29601. this.size = size;
  29602. this.side = side;
  29603. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29604. }
  29605. Plane.prototype._regenerateVertexData = function () {
  29606. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29607. };
  29608. Plane.prototype.copy = function (id) {
  29609. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29610. };
  29611. return Plane;
  29612. })(_Primitive);
  29613. Primitives.Plane = Plane;
  29614. var TorusKnot = (function (_super) {
  29615. __extends(TorusKnot, _super);
  29616. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29617. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29618. this.radius = radius;
  29619. this.tube = tube;
  29620. this.radialSegments = radialSegments;
  29621. this.tubularSegments = tubularSegments;
  29622. this.p = p;
  29623. this.q = q;
  29624. this.side = side;
  29625. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29626. }
  29627. TorusKnot.prototype._regenerateVertexData = function () {
  29628. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  29629. };
  29630. TorusKnot.prototype.copy = function (id) {
  29631. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29632. };
  29633. return TorusKnot;
  29634. })(_Primitive);
  29635. Primitives.TorusKnot = TorusKnot;
  29636. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29637. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29638. })(BABYLON || (BABYLON = {}));
  29639. var BABYLON;
  29640. (function (BABYLON) {
  29641. var GroundMesh = (function (_super) {
  29642. __extends(GroundMesh, _super);
  29643. function GroundMesh(name, scene) {
  29644. _super.call(this, name, scene);
  29645. this.generateOctree = false;
  29646. this._worldInverse = new BABYLON.Matrix();
  29647. }
  29648. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29649. get: function () {
  29650. return this._subdivisions;
  29651. },
  29652. enumerable: true,
  29653. configurable: true
  29654. });
  29655. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29656. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29657. this._subdivisions = chunksCount;
  29658. this.subdivide(this._subdivisions);
  29659. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29660. };
  29661. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29662. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29663. this.getWorldMatrix().invertToRef(this._worldInverse);
  29664. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29665. var pickInfo = this.intersects(ray);
  29666. if (pickInfo.hit) {
  29667. return pickInfo.pickedPoint.y;
  29668. }
  29669. return 0;
  29670. };
  29671. return GroundMesh;
  29672. })(BABYLON.Mesh);
  29673. BABYLON.GroundMesh = GroundMesh;
  29674. })(BABYLON || (BABYLON = {}));
  29675. var BABYLON;
  29676. (function (BABYLON) {
  29677. var LinesMesh = (function (_super) {
  29678. __extends(LinesMesh, _super);
  29679. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29680. if (parent === void 0) { parent = null; }
  29681. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29682. this.color = new BABYLON.Color3(1, 1, 1);
  29683. this.alpha = 1;
  29684. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29685. attributes: ["position"],
  29686. uniforms: ["worldViewProjection", "color"],
  29687. needAlphaBlending: true
  29688. });
  29689. }
  29690. Object.defineProperty(LinesMesh.prototype, "material", {
  29691. get: function () {
  29692. return this._colorShader;
  29693. },
  29694. enumerable: true,
  29695. configurable: true
  29696. });
  29697. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29698. get: function () {
  29699. return false;
  29700. },
  29701. enumerable: true,
  29702. configurable: true
  29703. });
  29704. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29705. get: function () {
  29706. return false;
  29707. },
  29708. enumerable: true,
  29709. configurable: true
  29710. });
  29711. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29712. var engine = this.getScene().getEngine();
  29713. var indexToBind = this._geometry.getIndexBuffer();
  29714. // VBOs
  29715. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29716. // Color
  29717. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29718. };
  29719. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29720. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29721. return;
  29722. }
  29723. var engine = this.getScene().getEngine();
  29724. // Draw order
  29725. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29726. };
  29727. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29728. return null;
  29729. };
  29730. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29731. this._colorShader.dispose();
  29732. _super.prototype.dispose.call(this, doNotRecurse);
  29733. };
  29734. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29735. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29736. };
  29737. return LinesMesh;
  29738. })(BABYLON.Mesh);
  29739. BABYLON.LinesMesh = LinesMesh;
  29740. })(BABYLON || (BABYLON = {}));
  29741. var BABYLON;
  29742. (function (BABYLON) {
  29743. var OutlineRenderer = (function () {
  29744. function OutlineRenderer(scene) {
  29745. this._scene = scene;
  29746. }
  29747. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29748. var _this = this;
  29749. if (useOverlay === void 0) { useOverlay = false; }
  29750. var scene = this._scene;
  29751. var engine = this._scene.getEngine();
  29752. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29753. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29754. return;
  29755. }
  29756. var mesh = subMesh.getRenderingMesh();
  29757. var material = subMesh.getMaterial();
  29758. engine.enableEffect(this._effect);
  29759. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29760. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29761. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29762. // Bones
  29763. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29764. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29765. }
  29766. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29767. // Alpha test
  29768. if (material && material.needAlphaTesting()) {
  29769. var alphaTexture = material.getAlphaTestTexture();
  29770. this._effect.setTexture("diffuseSampler", alphaTexture);
  29771. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29772. }
  29773. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29774. };
  29775. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29776. var defines = [];
  29777. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29778. var mesh = subMesh.getMesh();
  29779. var material = subMesh.getMaterial();
  29780. // Alpha test
  29781. if (material && material.needAlphaTesting()) {
  29782. defines.push("#define ALPHATEST");
  29783. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29784. attribs.push(BABYLON.VertexBuffer.UVKind);
  29785. defines.push("#define UV1");
  29786. }
  29787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29788. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29789. defines.push("#define UV2");
  29790. }
  29791. }
  29792. // Bones
  29793. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29794. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29795. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29796. defines.push("#define BONES");
  29797. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29798. }
  29799. // Instances
  29800. if (useInstances) {
  29801. defines.push("#define INSTANCES");
  29802. attribs.push("world0");
  29803. attribs.push("world1");
  29804. attribs.push("world2");
  29805. attribs.push("world3");
  29806. }
  29807. // Get correct effect
  29808. var join = defines.join("\n");
  29809. if (this._cachedDefines !== join) {
  29810. this._cachedDefines = join;
  29811. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29812. }
  29813. return this._effect.isReady();
  29814. };
  29815. return OutlineRenderer;
  29816. })();
  29817. BABYLON.OutlineRenderer = OutlineRenderer;
  29818. })(BABYLON || (BABYLON = {}));
  29819. var BABYLON;
  29820. (function (BABYLON) {
  29821. var MeshAssetTask = (function () {
  29822. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29823. this.name = name;
  29824. this.meshesNames = meshesNames;
  29825. this.rootUrl = rootUrl;
  29826. this.sceneFilename = sceneFilename;
  29827. this.isCompleted = false;
  29828. }
  29829. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29830. var _this = this;
  29831. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29832. _this.loadedMeshes = meshes;
  29833. _this.loadedParticleSystems = particleSystems;
  29834. _this.loadedSkeletons = skeletons;
  29835. _this.isCompleted = true;
  29836. if (_this.onSuccess) {
  29837. _this.onSuccess(_this);
  29838. }
  29839. onSuccess();
  29840. }, null, function () {
  29841. if (_this.onError) {
  29842. _this.onError(_this);
  29843. }
  29844. onError();
  29845. });
  29846. };
  29847. return MeshAssetTask;
  29848. })();
  29849. BABYLON.MeshAssetTask = MeshAssetTask;
  29850. var TextFileAssetTask = (function () {
  29851. function TextFileAssetTask(name, url) {
  29852. this.name = name;
  29853. this.url = url;
  29854. this.isCompleted = false;
  29855. }
  29856. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29857. var _this = this;
  29858. BABYLON.Tools.LoadFile(this.url, function (data) {
  29859. _this.text = data;
  29860. _this.isCompleted = true;
  29861. if (_this.onSuccess) {
  29862. _this.onSuccess(_this);
  29863. }
  29864. onSuccess();
  29865. }, null, scene.database, false, function () {
  29866. if (_this.onError) {
  29867. _this.onError(_this);
  29868. }
  29869. onError();
  29870. });
  29871. };
  29872. return TextFileAssetTask;
  29873. })();
  29874. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29875. var BinaryFileAssetTask = (function () {
  29876. function BinaryFileAssetTask(name, url) {
  29877. this.name = name;
  29878. this.url = url;
  29879. this.isCompleted = false;
  29880. }
  29881. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29882. var _this = this;
  29883. BABYLON.Tools.LoadFile(this.url, function (data) {
  29884. _this.data = data;
  29885. _this.isCompleted = true;
  29886. if (_this.onSuccess) {
  29887. _this.onSuccess(_this);
  29888. }
  29889. onSuccess();
  29890. }, null, scene.database, true, function () {
  29891. if (_this.onError) {
  29892. _this.onError(_this);
  29893. }
  29894. onError();
  29895. });
  29896. };
  29897. return BinaryFileAssetTask;
  29898. })();
  29899. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29900. var ImageAssetTask = (function () {
  29901. function ImageAssetTask(name, url) {
  29902. this.name = name;
  29903. this.url = url;
  29904. this.isCompleted = false;
  29905. }
  29906. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29907. var _this = this;
  29908. var img = new Image();
  29909. img.onload = function () {
  29910. _this.image = img;
  29911. _this.isCompleted = true;
  29912. if (_this.onSuccess) {
  29913. _this.onSuccess(_this);
  29914. }
  29915. onSuccess();
  29916. };
  29917. img.onerror = function () {
  29918. if (_this.onError) {
  29919. _this.onError(_this);
  29920. }
  29921. onError();
  29922. };
  29923. img.src = this.url;
  29924. };
  29925. return ImageAssetTask;
  29926. })();
  29927. BABYLON.ImageAssetTask = ImageAssetTask;
  29928. var TextureAssetTask = (function () {
  29929. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29931. this.name = name;
  29932. this.url = url;
  29933. this.noMipmap = noMipmap;
  29934. this.invertY = invertY;
  29935. this.samplingMode = samplingMode;
  29936. this.isCompleted = false;
  29937. }
  29938. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29939. var _this = this;
  29940. var onload = function () {
  29941. _this.isCompleted = true;
  29942. if (_this.onSuccess) {
  29943. _this.onSuccess(_this);
  29944. }
  29945. onSuccess();
  29946. };
  29947. var onerror = function () {
  29948. if (_this.onError) {
  29949. _this.onError(_this);
  29950. }
  29951. onError();
  29952. };
  29953. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29954. };
  29955. return TextureAssetTask;
  29956. })();
  29957. BABYLON.TextureAssetTask = TextureAssetTask;
  29958. var AssetsManager = (function () {
  29959. function AssetsManager(scene) {
  29960. this._tasks = new Array();
  29961. this._waitingTasksCount = 0;
  29962. this.useDefaultLoadingScreen = true;
  29963. this._scene = scene;
  29964. }
  29965. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29966. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29967. this._tasks.push(task);
  29968. return task;
  29969. };
  29970. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29971. var task = new TextFileAssetTask(taskName, url);
  29972. this._tasks.push(task);
  29973. return task;
  29974. };
  29975. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29976. var task = new BinaryFileAssetTask(taskName, url);
  29977. this._tasks.push(task);
  29978. return task;
  29979. };
  29980. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29981. var task = new ImageAssetTask(taskName, url);
  29982. this._tasks.push(task);
  29983. return task;
  29984. };
  29985. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29987. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29988. this._tasks.push(task);
  29989. return task;
  29990. };
  29991. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29992. this._waitingTasksCount--;
  29993. if (this._waitingTasksCount === 0) {
  29994. if (this.onFinish) {
  29995. this.onFinish(this._tasks);
  29996. }
  29997. this._scene.getEngine().hideLoadingUI();
  29998. }
  29999. };
  30000. AssetsManager.prototype._runTask = function (task) {
  30001. var _this = this;
  30002. task.run(this._scene, function () {
  30003. if (_this.onTaskSuccess) {
  30004. _this.onTaskSuccess(task);
  30005. }
  30006. _this._decreaseWaitingTasksCount();
  30007. }, function () {
  30008. if (_this.onTaskError) {
  30009. _this.onTaskError(task);
  30010. }
  30011. _this._decreaseWaitingTasksCount();
  30012. });
  30013. };
  30014. AssetsManager.prototype.reset = function () {
  30015. this._tasks = new Array();
  30016. return this;
  30017. };
  30018. AssetsManager.prototype.load = function () {
  30019. this._waitingTasksCount = this._tasks.length;
  30020. if (this._waitingTasksCount === 0) {
  30021. if (this.onFinish) {
  30022. this.onFinish(this._tasks);
  30023. }
  30024. return this;
  30025. }
  30026. if (this.useDefaultLoadingScreen) {
  30027. this._scene.getEngine().displayLoadingUI();
  30028. }
  30029. for (var index = 0; index < this._tasks.length; index++) {
  30030. var task = this._tasks[index];
  30031. this._runTask(task);
  30032. }
  30033. return this;
  30034. };
  30035. return AssetsManager;
  30036. })();
  30037. BABYLON.AssetsManager = AssetsManager;
  30038. })(BABYLON || (BABYLON = {}));
  30039. var BABYLON;
  30040. (function (BABYLON) {
  30041. var VRDeviceOrientationFreeCamera = (function (_super) {
  30042. __extends(VRDeviceOrientationFreeCamera, _super);
  30043. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  30044. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30045. _super.call(this, name, position, scene);
  30046. this._alpha = 0;
  30047. this._beta = 0;
  30048. this._gamma = 0;
  30049. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30050. metrics.compensateDistortion = compensateDistortion;
  30051. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30052. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  30053. }
  30054. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  30055. this._alpha = +evt.alpha | 0;
  30056. this._beta = +evt.beta | 0;
  30057. this._gamma = +evt.gamma | 0;
  30058. if (this._gamma < 0) {
  30059. this._gamma = 90 + this._gamma;
  30060. }
  30061. else {
  30062. // Incline it in the correct angle.
  30063. this._gamma = 270 - this._gamma;
  30064. }
  30065. this.rotation.x = this._gamma / 180.0 * Math.PI;
  30066. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  30067. this.rotation.z = this._beta / 180.0 * Math.PI;
  30068. };
  30069. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30070. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30071. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  30072. };
  30073. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  30074. _super.prototype.detachControl.call(this, element);
  30075. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  30076. };
  30077. return VRDeviceOrientationFreeCamera;
  30078. })(BABYLON.FreeCamera);
  30079. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  30080. })(BABYLON || (BABYLON = {}));
  30081. var BABYLON;
  30082. (function (BABYLON) {
  30083. var WebVRFreeCamera = (function (_super) {
  30084. __extends(WebVRFreeCamera, _super);
  30085. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  30086. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30087. _super.call(this, name, position, scene);
  30088. this._hmdDevice = null;
  30089. this._sensorDevice = null;
  30090. this._cacheState = null;
  30091. this._cacheQuaternion = new BABYLON.Quaternion();
  30092. this._cacheRotation = BABYLON.Vector3.Zero();
  30093. this._vrEnabled = false;
  30094. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30095. metrics.compensateDistortion = compensateDistortion;
  30096. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30097. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  30098. }
  30099. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  30100. var size = devices.length;
  30101. var i = 0;
  30102. // Reset devices.
  30103. this._sensorDevice = null;
  30104. this._hmdDevice = null;
  30105. // Search for a HmdDevice.
  30106. while (i < size && this._hmdDevice === null) {
  30107. if (devices[i] instanceof HMDVRDevice) {
  30108. this._hmdDevice = devices[i];
  30109. }
  30110. i++;
  30111. }
  30112. i = 0;
  30113. while (i < size && this._sensorDevice === null) {
  30114. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  30115. this._sensorDevice = devices[i];
  30116. }
  30117. i++;
  30118. }
  30119. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  30120. };
  30121. WebVRFreeCamera.prototype._checkInputs = function () {
  30122. if (this._vrEnabled) {
  30123. this._cacheState = this._sensorDevice.getState();
  30124. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  30125. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  30126. this.rotation.x = -this._cacheRotation.z;
  30127. this.rotation.y = -this._cacheRotation.y;
  30128. this.rotation.z = this._cacheRotation.x;
  30129. }
  30130. _super.prototype._checkInputs.call(this);
  30131. };
  30132. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30133. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30134. if (navigator.getVRDevices) {
  30135. navigator.getVRDevices().then(this._getWebVRDevices);
  30136. }
  30137. else if (navigator.mozGetVRDevices) {
  30138. navigator.mozGetVRDevices(this._getWebVRDevices);
  30139. }
  30140. };
  30141. WebVRFreeCamera.prototype.detachControl = function (element) {
  30142. _super.prototype.detachControl.call(this, element);
  30143. this._vrEnabled = false;
  30144. };
  30145. return WebVRFreeCamera;
  30146. })(BABYLON.FreeCamera);
  30147. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  30148. })(BABYLON || (BABYLON = {}));
  30149. var BABYLON;
  30150. (function (BABYLON) {
  30151. // Standard optimizations
  30152. var SceneOptimization = (function () {
  30153. function SceneOptimization(priority) {
  30154. if (priority === void 0) { priority = 0; }
  30155. this.priority = priority;
  30156. this.apply = function (scene) {
  30157. return true; // Return true if everything that can be done was applied
  30158. };
  30159. }
  30160. return SceneOptimization;
  30161. })();
  30162. BABYLON.SceneOptimization = SceneOptimization;
  30163. var TextureOptimization = (function (_super) {
  30164. __extends(TextureOptimization, _super);
  30165. function TextureOptimization(priority, maximumSize) {
  30166. var _this = this;
  30167. if (priority === void 0) { priority = 0; }
  30168. if (maximumSize === void 0) { maximumSize = 1024; }
  30169. _super.call(this, priority);
  30170. this.priority = priority;
  30171. this.maximumSize = maximumSize;
  30172. this.apply = function (scene) {
  30173. var allDone = true;
  30174. for (var index = 0; index < scene.textures.length; index++) {
  30175. var texture = scene.textures[index];
  30176. if (!texture.canRescale) {
  30177. continue;
  30178. }
  30179. var currentSize = texture.getSize();
  30180. var maxDimension = Math.max(currentSize.width, currentSize.height);
  30181. if (maxDimension > _this.maximumSize) {
  30182. texture.scale(0.5);
  30183. allDone = false;
  30184. }
  30185. }
  30186. return allDone;
  30187. };
  30188. }
  30189. return TextureOptimization;
  30190. })(SceneOptimization);
  30191. BABYLON.TextureOptimization = TextureOptimization;
  30192. var HardwareScalingOptimization = (function (_super) {
  30193. __extends(HardwareScalingOptimization, _super);
  30194. function HardwareScalingOptimization(priority, maximumScale) {
  30195. var _this = this;
  30196. if (priority === void 0) { priority = 0; }
  30197. if (maximumScale === void 0) { maximumScale = 2; }
  30198. _super.call(this, priority);
  30199. this.priority = priority;
  30200. this.maximumScale = maximumScale;
  30201. this._currentScale = 1;
  30202. this.apply = function (scene) {
  30203. _this._currentScale++;
  30204. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  30205. return _this._currentScale >= _this.maximumScale;
  30206. };
  30207. }
  30208. return HardwareScalingOptimization;
  30209. })(SceneOptimization);
  30210. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  30211. var ShadowsOptimization = (function (_super) {
  30212. __extends(ShadowsOptimization, _super);
  30213. function ShadowsOptimization() {
  30214. _super.apply(this, arguments);
  30215. this.apply = function (scene) {
  30216. scene.shadowsEnabled = false;
  30217. return true;
  30218. };
  30219. }
  30220. return ShadowsOptimization;
  30221. })(SceneOptimization);
  30222. BABYLON.ShadowsOptimization = ShadowsOptimization;
  30223. var PostProcessesOptimization = (function (_super) {
  30224. __extends(PostProcessesOptimization, _super);
  30225. function PostProcessesOptimization() {
  30226. _super.apply(this, arguments);
  30227. this.apply = function (scene) {
  30228. scene.postProcessesEnabled = false;
  30229. return true;
  30230. };
  30231. }
  30232. return PostProcessesOptimization;
  30233. })(SceneOptimization);
  30234. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  30235. var LensFlaresOptimization = (function (_super) {
  30236. __extends(LensFlaresOptimization, _super);
  30237. function LensFlaresOptimization() {
  30238. _super.apply(this, arguments);
  30239. this.apply = function (scene) {
  30240. scene.lensFlaresEnabled = false;
  30241. return true;
  30242. };
  30243. }
  30244. return LensFlaresOptimization;
  30245. })(SceneOptimization);
  30246. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  30247. var ParticlesOptimization = (function (_super) {
  30248. __extends(ParticlesOptimization, _super);
  30249. function ParticlesOptimization() {
  30250. _super.apply(this, arguments);
  30251. this.apply = function (scene) {
  30252. scene.particlesEnabled = false;
  30253. return true;
  30254. };
  30255. }
  30256. return ParticlesOptimization;
  30257. })(SceneOptimization);
  30258. BABYLON.ParticlesOptimization = ParticlesOptimization;
  30259. var RenderTargetsOptimization = (function (_super) {
  30260. __extends(RenderTargetsOptimization, _super);
  30261. function RenderTargetsOptimization() {
  30262. _super.apply(this, arguments);
  30263. this.apply = function (scene) {
  30264. scene.renderTargetsEnabled = false;
  30265. return true;
  30266. };
  30267. }
  30268. return RenderTargetsOptimization;
  30269. })(SceneOptimization);
  30270. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  30271. var MergeMeshesOptimization = (function (_super) {
  30272. __extends(MergeMeshesOptimization, _super);
  30273. function MergeMeshesOptimization() {
  30274. var _this = this;
  30275. _super.apply(this, arguments);
  30276. this._canBeMerged = function (abstractMesh) {
  30277. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  30278. return false;
  30279. }
  30280. var mesh = abstractMesh;
  30281. if (!mesh.isVisible || !mesh.isEnabled()) {
  30282. return false;
  30283. }
  30284. if (mesh.instances.length > 0) {
  30285. return false;
  30286. }
  30287. if (mesh.skeleton || mesh.hasLODLevels) {
  30288. return false;
  30289. }
  30290. return true;
  30291. };
  30292. this.apply = function (scene, updateSelectionTree) {
  30293. var globalPool = scene.meshes.slice(0);
  30294. var globalLength = globalPool.length;
  30295. for (var index = 0; index < globalLength; index++) {
  30296. var currentPool = new Array();
  30297. var current = globalPool[index];
  30298. // Checks
  30299. if (!_this._canBeMerged(current)) {
  30300. continue;
  30301. }
  30302. currentPool.push(current);
  30303. // Find compatible meshes
  30304. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  30305. var otherMesh = globalPool[subIndex];
  30306. if (!_this._canBeMerged(otherMesh)) {
  30307. continue;
  30308. }
  30309. if (otherMesh.material !== current.material) {
  30310. continue;
  30311. }
  30312. if (otherMesh.checkCollisions !== current.checkCollisions) {
  30313. continue;
  30314. }
  30315. currentPool.push(otherMesh);
  30316. globalLength--;
  30317. globalPool.splice(subIndex, 1);
  30318. subIndex--;
  30319. }
  30320. if (currentPool.length < 2) {
  30321. continue;
  30322. }
  30323. // Merge meshes
  30324. BABYLON.Mesh.MergeMeshes(currentPool);
  30325. }
  30326. if (updateSelectionTree != undefined) {
  30327. if (updateSelectionTree) {
  30328. scene.createOrUpdateSelectionOctree();
  30329. }
  30330. }
  30331. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  30332. scene.createOrUpdateSelectionOctree();
  30333. }
  30334. return true;
  30335. };
  30336. }
  30337. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  30338. get: function () {
  30339. return MergeMeshesOptimization._UpdateSelectionTree;
  30340. },
  30341. set: function (value) {
  30342. MergeMeshesOptimization._UpdateSelectionTree = value;
  30343. },
  30344. enumerable: true,
  30345. configurable: true
  30346. });
  30347. MergeMeshesOptimization._UpdateSelectionTree = false;
  30348. return MergeMeshesOptimization;
  30349. })(SceneOptimization);
  30350. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  30351. // Options
  30352. var SceneOptimizerOptions = (function () {
  30353. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  30354. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  30355. if (trackerDuration === void 0) { trackerDuration = 2000; }
  30356. this.targetFrameRate = targetFrameRate;
  30357. this.trackerDuration = trackerDuration;
  30358. this.optimizations = new Array();
  30359. }
  30360. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  30361. var result = new SceneOptimizerOptions(targetFrameRate);
  30362. var priority = 0;
  30363. result.optimizations.push(new MergeMeshesOptimization(priority));
  30364. result.optimizations.push(new ShadowsOptimization(priority));
  30365. result.optimizations.push(new LensFlaresOptimization(priority));
  30366. // Next priority
  30367. priority++;
  30368. result.optimizations.push(new PostProcessesOptimization(priority));
  30369. result.optimizations.push(new ParticlesOptimization(priority));
  30370. // Next priority
  30371. priority++;
  30372. result.optimizations.push(new TextureOptimization(priority, 1024));
  30373. return result;
  30374. };
  30375. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  30376. var result = new SceneOptimizerOptions(targetFrameRate);
  30377. var priority = 0;
  30378. result.optimizations.push(new MergeMeshesOptimization(priority));
  30379. result.optimizations.push(new ShadowsOptimization(priority));
  30380. result.optimizations.push(new LensFlaresOptimization(priority));
  30381. // Next priority
  30382. priority++;
  30383. result.optimizations.push(new PostProcessesOptimization(priority));
  30384. result.optimizations.push(new ParticlesOptimization(priority));
  30385. // Next priority
  30386. priority++;
  30387. result.optimizations.push(new TextureOptimization(priority, 512));
  30388. // Next priority
  30389. priority++;
  30390. result.optimizations.push(new RenderTargetsOptimization(priority));
  30391. // Next priority
  30392. priority++;
  30393. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  30394. return result;
  30395. };
  30396. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  30397. var result = new SceneOptimizerOptions(targetFrameRate);
  30398. var priority = 0;
  30399. result.optimizations.push(new MergeMeshesOptimization(priority));
  30400. result.optimizations.push(new ShadowsOptimization(priority));
  30401. result.optimizations.push(new LensFlaresOptimization(priority));
  30402. // Next priority
  30403. priority++;
  30404. result.optimizations.push(new PostProcessesOptimization(priority));
  30405. result.optimizations.push(new ParticlesOptimization(priority));
  30406. // Next priority
  30407. priority++;
  30408. result.optimizations.push(new TextureOptimization(priority, 256));
  30409. // Next priority
  30410. priority++;
  30411. result.optimizations.push(new RenderTargetsOptimization(priority));
  30412. // Next priority
  30413. priority++;
  30414. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  30415. return result;
  30416. };
  30417. return SceneOptimizerOptions;
  30418. })();
  30419. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  30420. // Scene optimizer tool
  30421. var SceneOptimizer = (function () {
  30422. function SceneOptimizer() {
  30423. }
  30424. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  30425. // TODO: add an epsilon
  30426. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  30427. if (onSuccess) {
  30428. onSuccess();
  30429. }
  30430. return;
  30431. }
  30432. // Apply current level of optimizations
  30433. var allDone = true;
  30434. var noOptimizationApplied = true;
  30435. for (var index = 0; index < options.optimizations.length; index++) {
  30436. var optimization = options.optimizations[index];
  30437. if (optimization.priority === currentPriorityLevel) {
  30438. noOptimizationApplied = false;
  30439. allDone = allDone && optimization.apply(scene);
  30440. }
  30441. }
  30442. // If no optimization was applied, this is a failure :(
  30443. if (noOptimizationApplied) {
  30444. if (onFailure) {
  30445. onFailure();
  30446. }
  30447. return;
  30448. }
  30449. // If all optimizations were done, move to next level
  30450. if (allDone) {
  30451. currentPriorityLevel++;
  30452. }
  30453. // Let's the system running for a specific amount of time before checking FPS
  30454. scene.executeWhenReady(function () {
  30455. setTimeout(function () {
  30456. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  30457. }, options.trackerDuration);
  30458. });
  30459. };
  30460. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  30461. if (!options) {
  30462. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  30463. }
  30464. // Let's the system running for a specific amount of time before checking FPS
  30465. scene.executeWhenReady(function () {
  30466. setTimeout(function () {
  30467. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  30468. }, options.trackerDuration);
  30469. });
  30470. };
  30471. return SceneOptimizer;
  30472. })();
  30473. BABYLON.SceneOptimizer = SceneOptimizer;
  30474. })(BABYLON || (BABYLON = {}));
  30475. var BABYLON;
  30476. (function (BABYLON) {
  30477. var Internals;
  30478. (function (Internals) {
  30479. var MeshLODLevel = (function () {
  30480. function MeshLODLevel(distance, mesh) {
  30481. this.distance = distance;
  30482. this.mesh = mesh;
  30483. }
  30484. return MeshLODLevel;
  30485. })();
  30486. Internals.MeshLODLevel = MeshLODLevel;
  30487. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30488. })(BABYLON || (BABYLON = {}));
  30489. var BABYLON;
  30490. (function (BABYLON) {
  30491. var AudioEngine = (function () {
  30492. function AudioEngine() {
  30493. this._audioContext = null;
  30494. this._audioContextInitialized = false;
  30495. this.canUseWebAudio = false;
  30496. this.WarnedWebAudioUnsupported = false;
  30497. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  30498. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  30499. this.canUseWebAudio = true;
  30500. }
  30501. }
  30502. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  30503. get: function () {
  30504. if (!this._audioContextInitialized) {
  30505. this._initializeAudioContext();
  30506. }
  30507. return this._audioContext;
  30508. },
  30509. enumerable: true,
  30510. configurable: true
  30511. });
  30512. AudioEngine.prototype._initializeAudioContext = function () {
  30513. try {
  30514. if (this.canUseWebAudio) {
  30515. this._audioContext = new AudioContext();
  30516. // create a global volume gain node
  30517. this.masterGain = this._audioContext.createGain();
  30518. this.masterGain.gain.value = 1;
  30519. this.masterGain.connect(this._audioContext.destination);
  30520. this._audioContextInitialized = true;
  30521. }
  30522. }
  30523. catch (e) {
  30524. this.canUseWebAudio = false;
  30525. BABYLON.Tools.Error("Web Audio: " + e.message);
  30526. }
  30527. };
  30528. AudioEngine.prototype.dispose = function () {
  30529. if (this.canUseWebAudio && this._audioContextInitialized) {
  30530. if (this._connectedAnalyser) {
  30531. this._connectedAnalyser.stopDebugCanvas();
  30532. this._connectedAnalyser.dispose();
  30533. this.masterGain.disconnect();
  30534. this.masterGain.connect(this._audioContext.destination);
  30535. this._connectedAnalyser = null;
  30536. }
  30537. this.masterGain.gain.value = 1;
  30538. }
  30539. this.WarnedWebAudioUnsupported = false;
  30540. };
  30541. AudioEngine.prototype.getGlobalVolume = function () {
  30542. if (this.canUseWebAudio && this._audioContextInitialized) {
  30543. return this.masterGain.gain.value;
  30544. }
  30545. else {
  30546. return -1;
  30547. }
  30548. };
  30549. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  30550. if (this.canUseWebAudio && this._audioContextInitialized) {
  30551. this.masterGain.gain.value = newVolume;
  30552. }
  30553. };
  30554. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  30555. if (this._connectedAnalyser) {
  30556. this._connectedAnalyser.stopDebugCanvas();
  30557. }
  30558. if (this.canUseWebAudio && this._audioContextInitialized) {
  30559. this._connectedAnalyser = analyser;
  30560. this.masterGain.disconnect();
  30561. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  30562. }
  30563. };
  30564. return AudioEngine;
  30565. })();
  30566. BABYLON.AudioEngine = AudioEngine;
  30567. })(BABYLON || (BABYLON = {}));
  30568. var BABYLON;
  30569. (function (BABYLON) {
  30570. var Sound = (function () {
  30571. /**
  30572. * Create a sound and attach it to a scene
  30573. * @param name Name of your sound
  30574. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  30575. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  30576. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  30577. */
  30578. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  30579. var _this = this;
  30580. this.autoplay = false;
  30581. this.loop = false;
  30582. this.useCustomAttenuation = false;
  30583. this.spatialSound = false;
  30584. this.refDistance = 1;
  30585. this.rolloffFactor = 1;
  30586. this.maxDistance = 100;
  30587. this.distanceModel = "linear";
  30588. this._panningModel = "equalpower";
  30589. this._playbackRate = 1;
  30590. this._startTime = 0;
  30591. this._startOffset = 0;
  30592. this._position = BABYLON.Vector3.Zero();
  30593. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30594. this._volume = 1;
  30595. this._isLoaded = false;
  30596. this._isReadyToPlay = false;
  30597. this.isPlaying = false;
  30598. this.isPaused = false;
  30599. this._isDirectional = false;
  30600. // Used if you'd like to create a directional sound.
  30601. // If not set, the sound will be omnidirectional
  30602. this._coneInnerAngle = 360;
  30603. this._coneOuterAngle = 360;
  30604. this._coneOuterGain = 0;
  30605. this._isOutputConnected = false;
  30606. this.name = name;
  30607. this._scene = scene;
  30608. this._readyToPlayCallback = readyToPlayCallback;
  30609. // Default custom attenuation function is a linear attenuation
  30610. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30611. if (currentDistance < maxDistance) {
  30612. return currentVolume * (1 - currentDistance / maxDistance);
  30613. }
  30614. else {
  30615. return 0;
  30616. }
  30617. };
  30618. if (options) {
  30619. this.autoplay = options.autoplay || false;
  30620. this.loop = options.loop || false;
  30621. // if volume === 0, we need another way to check this option
  30622. if (options.volume !== undefined) {
  30623. this._volume = options.volume;
  30624. }
  30625. this.spatialSound = options.spatialSound || false;
  30626. this.maxDistance = options.maxDistance || 100;
  30627. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30628. this.rolloffFactor = options.rolloffFactor || 1;
  30629. this.refDistance = options.refDistance || 1;
  30630. this.distanceModel = options.distanceModel || "linear";
  30631. this._playbackRate = options.playbackRate || 1;
  30632. }
  30633. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30634. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30635. this._soundGain.gain.value = this._volume;
  30636. this._inputAudioNode = this._soundGain;
  30637. this._ouputAudioNode = this._soundGain;
  30638. if (this.spatialSound) {
  30639. this._createSpatialParameters();
  30640. }
  30641. this._scene.mainSoundTrack.AddSound(this);
  30642. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30643. if (urlOrArrayBuffer) {
  30644. // If it's an URL
  30645. if (typeof (urlOrArrayBuffer) === "string") {
  30646. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30647. }
  30648. else {
  30649. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30650. this._soundLoaded(urlOrArrayBuffer);
  30651. }
  30652. else {
  30653. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30654. }
  30655. }
  30656. }
  30657. }
  30658. else {
  30659. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30660. this._scene.mainSoundTrack.AddSound(this);
  30661. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30662. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30663. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30664. }
  30665. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30666. if (this._readyToPlayCallback) {
  30667. window.setTimeout(function () {
  30668. _this._readyToPlayCallback();
  30669. }, 1000);
  30670. }
  30671. }
  30672. }
  30673. Sound.prototype.dispose = function () {
  30674. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30675. if (this.isPlaying) {
  30676. this.stop();
  30677. }
  30678. this._isReadyToPlay = false;
  30679. if (this.soundTrackId === -1) {
  30680. this._scene.mainSoundTrack.RemoveSound(this);
  30681. }
  30682. else {
  30683. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30684. }
  30685. if (this._soundGain) {
  30686. this._soundGain.disconnect();
  30687. this._soundGain = null;
  30688. }
  30689. if (this._soundPanner) {
  30690. this._soundPanner.disconnect();
  30691. this._soundPanner = null;
  30692. }
  30693. if (this._soundSource) {
  30694. this._soundSource.disconnect();
  30695. this._soundSource = null;
  30696. }
  30697. this._audioBuffer = null;
  30698. if (this._connectedMesh) {
  30699. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30700. this._connectedMesh = null;
  30701. }
  30702. }
  30703. };
  30704. Sound.prototype._soundLoaded = function (audioData) {
  30705. var _this = this;
  30706. this._isLoaded = true;
  30707. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30708. _this._audioBuffer = buffer;
  30709. _this._isReadyToPlay = true;
  30710. if (_this.autoplay) {
  30711. _this.play();
  30712. }
  30713. if (_this._readyToPlayCallback) {
  30714. _this._readyToPlayCallback();
  30715. }
  30716. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30717. };
  30718. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30719. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30720. this._audioBuffer = audioBuffer;
  30721. this._isReadyToPlay = true;
  30722. }
  30723. };
  30724. Sound.prototype.updateOptions = function (options) {
  30725. if (options) {
  30726. this.loop = options.loop || this.loop;
  30727. this.maxDistance = options.maxDistance || this.maxDistance;
  30728. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30729. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30730. this.refDistance = options.refDistance || this.refDistance;
  30731. this.distanceModel = options.distanceModel || this.distanceModel;
  30732. this._playbackRate = options.playbackRate || this._playbackRate;
  30733. this._updateSpatialParameters();
  30734. if (this.isPlaying) {
  30735. this._soundSource.playbackRate.value = this._playbackRate;
  30736. }
  30737. }
  30738. };
  30739. Sound.prototype._createSpatialParameters = function () {
  30740. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30741. if (this._scene.headphone) {
  30742. this._panningModel = "HRTF";
  30743. }
  30744. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30745. this._updateSpatialParameters();
  30746. this._soundPanner.connect(this._ouputAudioNode);
  30747. this._inputAudioNode = this._soundPanner;
  30748. }
  30749. };
  30750. Sound.prototype._updateSpatialParameters = function () {
  30751. if (this.spatialSound) {
  30752. if (this.useCustomAttenuation) {
  30753. // Tricks to disable in a way embedded Web Audio attenuation
  30754. this._soundPanner.distanceModel = "linear";
  30755. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30756. this._soundPanner.refDistance = 1;
  30757. this._soundPanner.rolloffFactor = 1;
  30758. this._soundPanner.panningModel = this._panningModel;
  30759. }
  30760. else {
  30761. this._soundPanner.distanceModel = this.distanceModel;
  30762. this._soundPanner.maxDistance = this.maxDistance;
  30763. this._soundPanner.refDistance = this.refDistance;
  30764. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30765. this._soundPanner.panningModel = this._panningModel;
  30766. }
  30767. }
  30768. };
  30769. Sound.prototype.switchPanningModelToHRTF = function () {
  30770. this._panningModel = "HRTF";
  30771. this._switchPanningModel();
  30772. };
  30773. Sound.prototype.switchPanningModelToEqualPower = function () {
  30774. this._panningModel = "equalpower";
  30775. this._switchPanningModel();
  30776. };
  30777. Sound.prototype._switchPanningModel = function () {
  30778. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30779. this._soundPanner.panningModel = this._panningModel;
  30780. }
  30781. };
  30782. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30783. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30784. if (this._isOutputConnected) {
  30785. this._ouputAudioNode.disconnect();
  30786. }
  30787. this._ouputAudioNode.connect(soundTrackAudioNode);
  30788. this._isOutputConnected = true;
  30789. }
  30790. };
  30791. /**
  30792. * Transform this sound into a directional source
  30793. * @param coneInnerAngle Size of the inner cone in degree
  30794. * @param coneOuterAngle Size of the outer cone in degree
  30795. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30796. */
  30797. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30798. if (coneOuterAngle < coneInnerAngle) {
  30799. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30800. return;
  30801. }
  30802. this._coneInnerAngle = coneInnerAngle;
  30803. this._coneOuterAngle = coneOuterAngle;
  30804. this._coneOuterGain = coneOuterGain;
  30805. this._isDirectional = true;
  30806. if (this.isPlaying && this.loop) {
  30807. this.stop();
  30808. this.play();
  30809. }
  30810. };
  30811. Sound.prototype.setPosition = function (newPosition) {
  30812. this._position = newPosition;
  30813. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30814. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30815. }
  30816. };
  30817. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30818. this._localDirection = newLocalDirection;
  30819. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30820. this._updateDirection();
  30821. }
  30822. };
  30823. Sound.prototype._updateDirection = function () {
  30824. var mat = this._connectedMesh.getWorldMatrix();
  30825. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30826. direction.normalize();
  30827. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30828. };
  30829. Sound.prototype.updateDistanceFromListener = function () {
  30830. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30831. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30832. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30833. }
  30834. };
  30835. Sound.prototype.setAttenuationFunction = function (callback) {
  30836. this._customAttenuationFunction = callback;
  30837. };
  30838. /**
  30839. * Play the sound
  30840. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30841. */
  30842. Sound.prototype.play = function (time) {
  30843. var _this = this;
  30844. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30845. try {
  30846. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30847. if (!this._soundSource) {
  30848. if (this.spatialSound) {
  30849. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30850. if (this._isDirectional) {
  30851. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30852. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30853. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30854. if (this._connectedMesh) {
  30855. this._updateDirection();
  30856. }
  30857. else {
  30858. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30859. }
  30860. }
  30861. }
  30862. }
  30863. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30864. this._soundSource.buffer = this._audioBuffer;
  30865. this._soundSource.connect(this._inputAudioNode);
  30866. this._soundSource.loop = this.loop;
  30867. this._soundSource.playbackRate.value = this._playbackRate;
  30868. this._startTime = startTime;
  30869. this._soundSource.onended = function () { _this._onended(); };
  30870. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30871. this.isPlaying = true;
  30872. this.isPaused = false;
  30873. }
  30874. catch (ex) {
  30875. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30876. }
  30877. }
  30878. };
  30879. Sound.prototype._onended = function () {
  30880. this.isPlaying = false;
  30881. if (this.onended) {
  30882. this.onended();
  30883. }
  30884. };
  30885. /**
  30886. * Stop the sound
  30887. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30888. */
  30889. Sound.prototype.stop = function (time) {
  30890. if (this.isPlaying) {
  30891. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30892. this._soundSource.stop(stopTime);
  30893. this.isPlaying = false;
  30894. }
  30895. };
  30896. Sound.prototype.pause = function () {
  30897. if (this.isPlaying) {
  30898. this.stop(0);
  30899. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30900. this.isPaused = true;
  30901. }
  30902. };
  30903. Sound.prototype.setVolume = function (newVolume, time) {
  30904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30905. if (time) {
  30906. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30907. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30908. }
  30909. else {
  30910. this._soundGain.gain.value = newVolume;
  30911. }
  30912. }
  30913. this._volume = newVolume;
  30914. };
  30915. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30916. this._playbackRate = newPlaybackRate;
  30917. if (this.isPlaying) {
  30918. this._soundSource.playbackRate.value = this._playbackRate;
  30919. }
  30920. };
  30921. Sound.prototype.getVolume = function () {
  30922. return this._volume;
  30923. };
  30924. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30925. var _this = this;
  30926. this._connectedMesh = meshToConnectTo;
  30927. if (!this.spatialSound) {
  30928. this.spatialSound = true;
  30929. this._createSpatialParameters();
  30930. if (this.isPlaying && this.loop) {
  30931. this.stop();
  30932. this.play();
  30933. }
  30934. }
  30935. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30936. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30937. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30938. };
  30939. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30940. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30941. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30942. this._updateDirection();
  30943. }
  30944. };
  30945. return Sound;
  30946. })();
  30947. BABYLON.Sound = Sound;
  30948. })(BABYLON || (BABYLON = {}));
  30949. var BABYLON;
  30950. (function (BABYLON) {
  30951. var SoundTrack = (function () {
  30952. function SoundTrack(scene, options) {
  30953. this.id = -1;
  30954. this._isMainTrack = false;
  30955. this._scene = scene;
  30956. this._audioEngine = BABYLON.Engine.audioEngine;
  30957. this.soundCollection = new Array();
  30958. if (this._audioEngine.canUseWebAudio) {
  30959. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30960. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30961. if (options) {
  30962. if (options.volume) {
  30963. this._outputAudioNode.gain.value = options.volume;
  30964. }
  30965. if (options.mainTrack) {
  30966. this._isMainTrack = options.mainTrack;
  30967. }
  30968. }
  30969. }
  30970. if (!this._isMainTrack) {
  30971. this._scene.soundTracks.push(this);
  30972. this.id = this._scene.soundTracks.length - 1;
  30973. }
  30974. }
  30975. SoundTrack.prototype.dispose = function () {
  30976. if (this._audioEngine.canUseWebAudio) {
  30977. if (this._connectedAnalyser) {
  30978. this._connectedAnalyser.stopDebugCanvas();
  30979. }
  30980. while (this.soundCollection.length) {
  30981. this.soundCollection[0].dispose();
  30982. }
  30983. if (this._outputAudioNode) {
  30984. this._outputAudioNode.disconnect();
  30985. }
  30986. this._outputAudioNode = null;
  30987. }
  30988. };
  30989. SoundTrack.prototype.AddSound = function (sound) {
  30990. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30991. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30992. }
  30993. if (sound.soundTrackId) {
  30994. if (sound.soundTrackId === -1) {
  30995. this._scene.mainSoundTrack.RemoveSound(sound);
  30996. }
  30997. else {
  30998. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30999. }
  31000. }
  31001. this.soundCollection.push(sound);
  31002. sound.soundTrackId = this.id;
  31003. };
  31004. SoundTrack.prototype.RemoveSound = function (sound) {
  31005. var index = this.soundCollection.indexOf(sound);
  31006. if (index !== -1) {
  31007. this.soundCollection.splice(index, 1);
  31008. }
  31009. };
  31010. SoundTrack.prototype.setVolume = function (newVolume) {
  31011. if (this._audioEngine.canUseWebAudio) {
  31012. this._outputAudioNode.gain.value = newVolume;
  31013. }
  31014. };
  31015. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  31016. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31017. for (var i = 0; i < this.soundCollection.length; i++) {
  31018. this.soundCollection[i].switchPanningModelToHRTF();
  31019. }
  31020. }
  31021. };
  31022. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  31023. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31024. for (var i = 0; i < this.soundCollection.length; i++) {
  31025. this.soundCollection[i].switchPanningModelToEqualPower();
  31026. }
  31027. }
  31028. };
  31029. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  31030. if (this._connectedAnalyser) {
  31031. this._connectedAnalyser.stopDebugCanvas();
  31032. }
  31033. this._connectedAnalyser = analyser;
  31034. if (this._audioEngine.canUseWebAudio) {
  31035. this._outputAudioNode.disconnect();
  31036. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  31037. }
  31038. };
  31039. return SoundTrack;
  31040. })();
  31041. BABYLON.SoundTrack = SoundTrack;
  31042. })(BABYLON || (BABYLON = {}));
  31043. var BABYLON;
  31044. (function (BABYLON) {
  31045. var DebugLayer = (function () {
  31046. function DebugLayer(scene) {
  31047. var _this = this;
  31048. this._transformationMatrix = BABYLON.Matrix.Identity();
  31049. this._enabled = false;
  31050. this._labelsEnabled = false;
  31051. this._displayStatistics = true;
  31052. this._displayTree = false;
  31053. this._displayLogs = false;
  31054. this._identityMatrix = BABYLON.Matrix.Identity();
  31055. this.axisRatio = 0.02;
  31056. this.accentColor = "orange";
  31057. this._scene = scene;
  31058. this._syncPositions = function () {
  31059. var engine = _this._scene.getEngine();
  31060. var canvasRect = engine.getRenderingCanvasClientRect();
  31061. if (_this._showUI) {
  31062. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  31063. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  31064. _this._statsDiv.style.width = "400px";
  31065. _this._statsDiv.style.height = "auto";
  31066. _this._statsSubsetDiv.style.maxHeight = "240px";
  31067. _this._optionsDiv.style.left = "0px";
  31068. _this._optionsDiv.style.top = "10px";
  31069. _this._optionsDiv.style.width = "200px";
  31070. _this._optionsDiv.style.height = "auto";
  31071. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  31072. _this._logDiv.style.left = "0px";
  31073. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  31074. _this._logDiv.style.width = "600px";
  31075. _this._logDiv.style.height = "160px";
  31076. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  31077. _this._treeDiv.style.top = "10px";
  31078. _this._treeDiv.style.width = "300px";
  31079. _this._treeDiv.style.height = "auto";
  31080. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  31081. }
  31082. _this._globalDiv.style.left = canvasRect.left + "px";
  31083. _this._globalDiv.style.top = canvasRect.top + "px";
  31084. _this._drawingCanvas.style.left = "0px";
  31085. _this._drawingCanvas.style.top = "0px";
  31086. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  31087. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  31088. var devicePixelRatio = window.devicePixelRatio || 1;
  31089. var context = _this._drawingContext;
  31090. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  31091. context.mozBackingStorePixelRatio ||
  31092. context.msBackingStorePixelRatio ||
  31093. context.oBackingStorePixelRatio ||
  31094. context.backingStorePixelRatio || 1;
  31095. _this._ratio = devicePixelRatio / backingStoreRatio;
  31096. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  31097. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  31098. };
  31099. this._onCanvasClick = function (evt) {
  31100. _this._clickPosition = {
  31101. x: evt.clientX * _this._ratio,
  31102. y: evt.clientY * _this._ratio
  31103. };
  31104. };
  31105. this._syncUI = function () {
  31106. if (_this._showUI) {
  31107. if (_this._displayStatistics) {
  31108. _this._displayStats();
  31109. _this._statsDiv.style.display = "";
  31110. }
  31111. else {
  31112. _this._statsDiv.style.display = "none";
  31113. }
  31114. if (_this._displayLogs) {
  31115. _this._logDiv.style.display = "";
  31116. }
  31117. else {
  31118. _this._logDiv.style.display = "none";
  31119. }
  31120. if (_this._displayTree) {
  31121. _this._treeDiv.style.display = "";
  31122. if (_this._needToRefreshMeshesTree) {
  31123. _this._needToRefreshMeshesTree = false;
  31124. _this._refreshMeshesTreeContent();
  31125. }
  31126. }
  31127. else {
  31128. _this._treeDiv.style.display = "none";
  31129. }
  31130. }
  31131. };
  31132. this._syncData = function () {
  31133. if (_this._labelsEnabled || !_this._showUI) {
  31134. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  31135. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  31136. var engine = _this._scene.getEngine();
  31137. var viewport = _this._camera.viewport;
  31138. var globalViewport = viewport.toGlobal(engine);
  31139. // Meshes
  31140. var meshes = _this._camera.getActiveMeshes();
  31141. for (var index = 0; index < meshes.length; index++) {
  31142. var mesh = meshes.data[index];
  31143. var position = mesh.getBoundingInfo().boundingSphere.center;
  31144. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31145. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  31146. _this._renderAxis(projectedPosition, mesh, globalViewport);
  31147. }
  31148. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  31149. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  31150. }
  31151. }
  31152. // Cameras
  31153. var cameras = _this._scene.cameras;
  31154. for (index = 0; index < cameras.length; index++) {
  31155. var camera = cameras[index];
  31156. if (camera === _this._camera) {
  31157. continue;
  31158. }
  31159. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31160. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  31161. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  31162. _this._camera.detachControl(engine.getRenderingCanvas());
  31163. _this._camera = camera;
  31164. _this._camera.attachControl(engine.getRenderingCanvas());
  31165. }, function () { return "purple"; });
  31166. }
  31167. }
  31168. // Lights
  31169. var lights = _this._scene.lights;
  31170. for (index = 0; index < lights.length; index++) {
  31171. var light = lights[index];
  31172. if (light.position) {
  31173. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  31174. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  31175. _this._renderLabel(light.name, projectedPosition, -20, function () {
  31176. light.setEnabled(!light.isEnabled());
  31177. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  31178. }
  31179. }
  31180. }
  31181. }
  31182. _this._clickPosition = undefined;
  31183. };
  31184. }
  31185. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  31186. while (this._treeSubsetDiv.hasChildNodes()) {
  31187. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  31188. }
  31189. // Add meshes
  31190. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  31191. sortedArray.sort(function (a, b) {
  31192. if (a.name === b.name) {
  31193. return 0;
  31194. }
  31195. return (a.name > b.name) ? 1 : -1;
  31196. });
  31197. for (var index = 0; index < sortedArray.length; index++) {
  31198. var mesh = sortedArray[index];
  31199. if (!mesh.isEnabled()) {
  31200. continue;
  31201. }
  31202. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  31203. m.isVisible = element.checked;
  31204. }, mesh);
  31205. }
  31206. };
  31207. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  31208. this._drawingContext.beginPath();
  31209. this._drawingContext.moveTo(zero.x, zero.y);
  31210. this._drawingContext.lineTo(unit.x, unit.y);
  31211. this._drawingContext.strokeStyle = color;
  31212. this._drawingContext.lineWidth = 4;
  31213. this._drawingContext.stroke();
  31214. this._drawingContext.font = "normal 14px Segoe UI";
  31215. this._drawingContext.fillStyle = color;
  31216. this._drawingContext.fillText(label, unitText.x, unitText.y);
  31217. };
  31218. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  31219. var position = mesh.getBoundingInfo().boundingSphere.center;
  31220. var worldMatrix = mesh.getWorldMatrix();
  31221. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  31222. var unit = (unprojectedVector.subtract(position)).length();
  31223. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31224. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31225. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  31226. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31227. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31228. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  31229. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  31230. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  31231. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  31232. };
  31233. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  31234. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  31235. this._drawingContext.font = "normal 12px Segoe UI";
  31236. var textMetrics = this._drawingContext.measureText(text);
  31237. var centerX = projectedPosition.x - textMetrics.width / 2;
  31238. var centerY = projectedPosition.y;
  31239. var clientRect = this._drawingCanvas.getBoundingClientRect();
  31240. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  31241. onClick();
  31242. }
  31243. this._drawingContext.beginPath();
  31244. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  31245. this._drawingContext.fillStyle = getFillStyle();
  31246. this._drawingContext.globalAlpha = 0.5;
  31247. this._drawingContext.fill();
  31248. this._drawingContext.globalAlpha = 1.0;
  31249. this._drawingContext.strokeStyle = '#FFFFFF';
  31250. this._drawingContext.lineWidth = 1;
  31251. this._drawingContext.stroke();
  31252. this._drawingContext.fillStyle = "#FFFFFF";
  31253. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  31254. this._drawingContext.beginPath();
  31255. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  31256. this._drawingContext.fill();
  31257. }
  31258. };
  31259. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  31260. if (!this._clickPosition) {
  31261. return false;
  31262. }
  31263. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  31264. return false;
  31265. }
  31266. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  31267. return false;
  31268. }
  31269. return true;
  31270. };
  31271. DebugLayer.prototype.isVisible = function () {
  31272. return this._enabled;
  31273. };
  31274. DebugLayer.prototype.hide = function () {
  31275. if (!this._enabled) {
  31276. return;
  31277. }
  31278. this._enabled = false;
  31279. var engine = this._scene.getEngine();
  31280. this._scene.unregisterBeforeRender(this._syncData);
  31281. this._scene.unregisterAfterRender(this._syncUI);
  31282. document.body.removeChild(this._globalDiv);
  31283. window.removeEventListener("resize", this._syncPositions);
  31284. this._scene.forceShowBoundingBoxes = false;
  31285. this._scene.forceWireframe = false;
  31286. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  31287. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  31288. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  31289. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  31290. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  31291. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  31292. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  31293. BABYLON.StandardMaterial.LightmapEnabled = true;
  31294. this._scene.shadowsEnabled = true;
  31295. this._scene.particlesEnabled = true;
  31296. this._scene.postProcessesEnabled = true;
  31297. this._scene.collisionsEnabled = true;
  31298. this._scene.lightsEnabled = true;
  31299. this._scene.texturesEnabled = true;
  31300. this._scene.lensFlaresEnabled = true;
  31301. this._scene.proceduralTexturesEnabled = true;
  31302. this._scene.renderTargetsEnabled = true;
  31303. this._scene.probesEnabled = true;
  31304. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  31305. };
  31306. DebugLayer.prototype.show = function (showUI, camera) {
  31307. if (showUI === void 0) { showUI = true; }
  31308. if (camera === void 0) { camera = null; }
  31309. if (this._enabled) {
  31310. return;
  31311. }
  31312. this._enabled = true;
  31313. if (camera) {
  31314. this._camera = camera;
  31315. }
  31316. else {
  31317. this._camera = this._scene.activeCamera;
  31318. }
  31319. this._showUI = showUI;
  31320. var engine = this._scene.getEngine();
  31321. this._globalDiv = document.createElement("div");
  31322. document.body.appendChild(this._globalDiv);
  31323. this._generateDOMelements();
  31324. window.addEventListener("resize", this._syncPositions);
  31325. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  31326. this._syncPositions();
  31327. this._scene.registerBeforeRender(this._syncData);
  31328. this._scene.registerAfterRender(this._syncUI);
  31329. };
  31330. DebugLayer.prototype._clearLabels = function () {
  31331. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  31332. for (var index = 0; index < this._scene.meshes.length; index++) {
  31333. var mesh = this._scene.meshes[index];
  31334. mesh.renderOverlay = false;
  31335. }
  31336. };
  31337. DebugLayer.prototype._generateheader = function (root, text) {
  31338. var header = document.createElement("div");
  31339. header.innerHTML = text + "&nbsp;";
  31340. header.style.textAlign = "right";
  31341. header.style.width = "100%";
  31342. header.style.color = "white";
  31343. header.style.backgroundColor = "Black";
  31344. header.style.padding = "5px 5px 4px 0px";
  31345. header.style.marginLeft = "-5px";
  31346. header.style.fontWeight = "bold";
  31347. root.appendChild(header);
  31348. };
  31349. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  31350. var label = document.createElement("label");
  31351. label.innerHTML = title;
  31352. label.style.color = color;
  31353. root.appendChild(label);
  31354. root.appendChild(document.createElement("br"));
  31355. };
  31356. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  31357. if (tag === void 0) { tag = null; }
  31358. var label = document.createElement("label");
  31359. var boundingBoxesCheckbox = document.createElement("input");
  31360. boundingBoxesCheckbox.type = "checkbox";
  31361. boundingBoxesCheckbox.checked = initialState;
  31362. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  31363. task(evt.target, tag);
  31364. });
  31365. label.appendChild(boundingBoxesCheckbox);
  31366. var container = document.createElement("span");
  31367. var leftPart = document.createElement("span");
  31368. var rightPart = document.createElement("span");
  31369. rightPart.style.cssFloat = "right";
  31370. leftPart.innerHTML = leftTitle;
  31371. rightPart.innerHTML = rightTitle;
  31372. rightPart.style.fontSize = "12px";
  31373. rightPart.style.maxWidth = "200px";
  31374. container.appendChild(leftPart);
  31375. container.appendChild(rightPart);
  31376. label.appendChild(container);
  31377. root.appendChild(label);
  31378. root.appendChild(document.createElement("br"));
  31379. };
  31380. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  31381. if (tag === void 0) { tag = null; }
  31382. var label = document.createElement("label");
  31383. var checkBox = document.createElement("input");
  31384. checkBox.type = "checkbox";
  31385. checkBox.checked = initialState;
  31386. checkBox.addEventListener("change", function (evt) {
  31387. task(evt.target, tag);
  31388. });
  31389. label.appendChild(checkBox);
  31390. label.appendChild(document.createTextNode(title));
  31391. root.appendChild(label);
  31392. root.appendChild(document.createElement("br"));
  31393. };
  31394. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  31395. if (tag === void 0) { tag = null; }
  31396. var button = document.createElement("button");
  31397. button.innerHTML = title;
  31398. button.style.height = "24px";
  31399. button.style.color = "#444444";
  31400. button.style.border = "1px solid white";
  31401. button.className = "debugLayerButton";
  31402. button.addEventListener("click", function (evt) {
  31403. task(evt.target, tag);
  31404. });
  31405. root.appendChild(button);
  31406. root.appendChild(document.createElement("br"));
  31407. };
  31408. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  31409. if (tag === void 0) { tag = null; }
  31410. var label = document.createElement("label");
  31411. var boundingBoxesRadio = document.createElement("input");
  31412. boundingBoxesRadio.type = "radio";
  31413. boundingBoxesRadio.name = name;
  31414. boundingBoxesRadio.checked = initialState;
  31415. boundingBoxesRadio.addEventListener("change", function (evt) {
  31416. task(evt.target, tag);
  31417. });
  31418. label.appendChild(boundingBoxesRadio);
  31419. label.appendChild(document.createTextNode(title));
  31420. root.appendChild(label);
  31421. root.appendChild(document.createElement("br"));
  31422. };
  31423. DebugLayer.prototype._generateDOMelements = function () {
  31424. var _this = this;
  31425. this._globalDiv.id = "DebugLayer";
  31426. this._globalDiv.style.position = "absolute";
  31427. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  31428. this._globalDiv.style.fontSize = "14px";
  31429. this._globalDiv.style.color = "white";
  31430. // Drawing canvas
  31431. this._drawingCanvas = document.createElement("canvas");
  31432. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  31433. this._drawingCanvas.style.position = "absolute";
  31434. this._drawingCanvas.style.pointerEvents = "none";
  31435. this._drawingContext = this._drawingCanvas.getContext("2d");
  31436. this._globalDiv.appendChild(this._drawingCanvas);
  31437. if (this._showUI) {
  31438. var background = "rgba(128, 128, 128, 0.4)";
  31439. var border = "rgb(180, 180, 180) solid 1px";
  31440. // Stats
  31441. this._statsDiv = document.createElement("div");
  31442. this._statsDiv.id = "DebugLayerStats";
  31443. this._statsDiv.style.border = border;
  31444. this._statsDiv.style.position = "absolute";
  31445. this._statsDiv.style.background = background;
  31446. this._statsDiv.style.padding = "0px 0px 0px 5px";
  31447. this._generateheader(this._statsDiv, "STATISTICS");
  31448. this._statsSubsetDiv = document.createElement("div");
  31449. this._statsSubsetDiv.style.paddingTop = "5px";
  31450. this._statsSubsetDiv.style.paddingBottom = "5px";
  31451. this._statsSubsetDiv.style.overflowY = "auto";
  31452. this._statsDiv.appendChild(this._statsSubsetDiv);
  31453. // Tree
  31454. this._treeDiv = document.createElement("div");
  31455. this._treeDiv.id = "DebugLayerTree";
  31456. this._treeDiv.style.border = border;
  31457. this._treeDiv.style.position = "absolute";
  31458. this._treeDiv.style.background = background;
  31459. this._treeDiv.style.padding = "0px 0px 0px 5px";
  31460. this._treeDiv.style.display = "none";
  31461. this._generateheader(this._treeDiv, "MESHES TREE");
  31462. this._treeSubsetDiv = document.createElement("div");
  31463. this._treeSubsetDiv.style.paddingTop = "5px";
  31464. this._treeSubsetDiv.style.paddingRight = "5px";
  31465. this._treeSubsetDiv.style.overflowY = "auto";
  31466. this._treeSubsetDiv.style.maxHeight = "300px";
  31467. this._treeDiv.appendChild(this._treeSubsetDiv);
  31468. this._needToRefreshMeshesTree = true;
  31469. // Logs
  31470. this._logDiv = document.createElement("div");
  31471. this._logDiv.style.border = border;
  31472. this._logDiv.id = "DebugLayerLogs";
  31473. this._logDiv.style.position = "absolute";
  31474. this._logDiv.style.background = background;
  31475. this._logDiv.style.padding = "0px 0px 0px 5px";
  31476. this._logDiv.style.display = "none";
  31477. this._generateheader(this._logDiv, "LOGS");
  31478. this._logSubsetDiv = document.createElement("div");
  31479. this._logSubsetDiv.style.height = "127px";
  31480. this._logSubsetDiv.style.paddingTop = "5px";
  31481. this._logSubsetDiv.style.overflowY = "auto";
  31482. this._logSubsetDiv.style.fontSize = "12px";
  31483. this._logSubsetDiv.style.fontFamily = "consolas";
  31484. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31485. this._logDiv.appendChild(this._logSubsetDiv);
  31486. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31487. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31488. };
  31489. // Options
  31490. this._optionsDiv = document.createElement("div");
  31491. this._optionsDiv.id = "DebugLayerOptions";
  31492. this._optionsDiv.style.border = border;
  31493. this._optionsDiv.style.position = "absolute";
  31494. this._optionsDiv.style.background = background;
  31495. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31496. this._optionsDiv.style.overflowY = "auto";
  31497. this._generateheader(this._optionsDiv, "OPTIONS");
  31498. this._optionsSubsetDiv = document.createElement("div");
  31499. this._optionsSubsetDiv.style.paddingTop = "5px";
  31500. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31501. this._optionsSubsetDiv.style.overflowY = "auto";
  31502. this._optionsSubsetDiv.style.maxHeight = "200px";
  31503. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31504. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31505. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31506. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31507. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31508. _this._displayTree = element.checked;
  31509. _this._needToRefreshMeshesTree = true;
  31510. });
  31511. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31512. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31513. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31514. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31515. _this._labelsEnabled = element.checked;
  31516. if (!_this._labelsEnabled) {
  31517. _this._clearLabels();
  31518. }
  31519. });
  31520. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31521. if (element.checked) {
  31522. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31523. }
  31524. else {
  31525. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31526. }
  31527. });
  31528. ;
  31529. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31530. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31531. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31532. if (element.checked) {
  31533. _this._scene.forceWireframe = false;
  31534. _this._scene.forcePointsCloud = false;
  31535. }
  31536. });
  31537. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31538. if (element.checked) {
  31539. _this._scene.forceWireframe = true;
  31540. _this._scene.forcePointsCloud = false;
  31541. }
  31542. });
  31543. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31544. if (element.checked) {
  31545. _this._scene.forceWireframe = false;
  31546. _this._scene.forcePointsCloud = true;
  31547. }
  31548. });
  31549. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31550. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31551. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31552. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31553. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31554. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31555. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31556. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31557. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31558. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31559. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  31560. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31561. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31562. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31563. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31564. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31565. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31566. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31567. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31568. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31569. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  31570. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31571. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31572. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31573. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31574. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31575. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31576. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31577. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31578. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31579. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31580. if (element.checked) {
  31581. _this._scene.headphone = true;
  31582. }
  31583. });
  31584. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31585. if (element.checked) {
  31586. _this._scene.headphone = false;
  31587. }
  31588. });
  31589. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31590. _this._scene.audioEnabled = !element.checked;
  31591. });
  31592. }
  31593. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31594. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31595. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31596. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31597. this._globalDiv.appendChild(this._statsDiv);
  31598. this._globalDiv.appendChild(this._logDiv);
  31599. this._globalDiv.appendChild(this._optionsDiv);
  31600. this._globalDiv.appendChild(this._treeDiv);
  31601. }
  31602. };
  31603. DebugLayer.prototype._displayStats = function () {
  31604. var scene = this._scene;
  31605. var engine = scene.getEngine();
  31606. var glInfo = engine.getGlInfo();
  31607. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31608. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31609. + "<b>Count</b><br>"
  31610. + "Total meshes: " + scene.meshes.length + "<br>"
  31611. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31612. + "Total materials: " + scene.materials.length + "<br>"
  31613. + "Total textures: " + scene.textures.length + "<br>"
  31614. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31615. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31616. + "Active bones: " + scene.getActiveBones() + "<br>"
  31617. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31618. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31619. + "<b>Duration</b><br>"
  31620. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31621. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31622. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31623. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31624. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31625. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31626. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31627. + "</div>"
  31628. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31629. + "<b>Extensions</b><br>"
  31630. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31631. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31632. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31633. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31634. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31635. + "<b>Caps.</b><br>"
  31636. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31637. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31638. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31639. + "</div><br>"
  31640. + "<b>Info</b><br>"
  31641. + glInfo.version + "<br>"
  31642. + glInfo.renderer + "<br>";
  31643. if (this.customStatsFunction) {
  31644. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31645. }
  31646. };
  31647. return DebugLayer;
  31648. })();
  31649. BABYLON.DebugLayer = DebugLayer;
  31650. })(BABYLON || (BABYLON = {}));
  31651. var BABYLON;
  31652. (function (BABYLON) {
  31653. var RawTexture = (function (_super) {
  31654. __extends(RawTexture, _super);
  31655. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31656. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31657. if (invertY === void 0) { invertY = false; }
  31658. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31659. _super.call(this, null, scene, !generateMipMaps, invertY);
  31660. this.format = format;
  31661. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31662. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31663. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31664. }
  31665. RawTexture.prototype.update = function (data) {
  31666. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31667. };
  31668. // Statics
  31669. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31670. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31671. if (invertY === void 0) { invertY = false; }
  31672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31673. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31674. };
  31675. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31676. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31677. if (invertY === void 0) { invertY = false; }
  31678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31679. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31680. };
  31681. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31682. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31683. if (invertY === void 0) { invertY = false; }
  31684. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31685. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31686. };
  31687. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31688. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31689. if (invertY === void 0) { invertY = false; }
  31690. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31691. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31692. };
  31693. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31694. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31695. if (invertY === void 0) { invertY = false; }
  31696. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31697. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31698. };
  31699. return RawTexture;
  31700. })(BABYLON.Texture);
  31701. BABYLON.RawTexture = RawTexture;
  31702. })(BABYLON || (BABYLON = {}));
  31703. var BABYLON;
  31704. (function (BABYLON) {
  31705. var IndexedVector2 = (function (_super) {
  31706. __extends(IndexedVector2, _super);
  31707. function IndexedVector2(original, index) {
  31708. _super.call(this, original.x, original.y);
  31709. this.index = index;
  31710. }
  31711. return IndexedVector2;
  31712. })(BABYLON.Vector2);
  31713. var PolygonPoints = (function () {
  31714. function PolygonPoints() {
  31715. this.elements = new Array();
  31716. }
  31717. PolygonPoints.prototype.add = function (originalPoints) {
  31718. var _this = this;
  31719. var result = new Array();
  31720. originalPoints.forEach(function (point) {
  31721. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31722. var newPoint = new IndexedVector2(point, _this.elements.length);
  31723. result.push(newPoint);
  31724. _this.elements.push(newPoint);
  31725. }
  31726. });
  31727. return result;
  31728. };
  31729. PolygonPoints.prototype.computeBounds = function () {
  31730. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31731. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31732. this.elements.forEach(function (point) {
  31733. // x
  31734. if (point.x < lmin.x) {
  31735. lmin.x = point.x;
  31736. }
  31737. else if (point.x > lmax.x) {
  31738. lmax.x = point.x;
  31739. }
  31740. // y
  31741. if (point.y < lmin.y) {
  31742. lmin.y = point.y;
  31743. }
  31744. else if (point.y > lmax.y) {
  31745. lmax.y = point.y;
  31746. }
  31747. });
  31748. return {
  31749. min: lmin,
  31750. max: lmax,
  31751. width: lmax.x - lmin.x,
  31752. height: lmax.y - lmin.y
  31753. };
  31754. };
  31755. return PolygonPoints;
  31756. })();
  31757. var Polygon = (function () {
  31758. function Polygon() {
  31759. }
  31760. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31761. return [
  31762. new BABYLON.Vector2(xmin, ymin),
  31763. new BABYLON.Vector2(xmax, ymin),
  31764. new BABYLON.Vector2(xmax, ymax),
  31765. new BABYLON.Vector2(xmin, ymax)
  31766. ];
  31767. };
  31768. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31769. if (cx === void 0) { cx = 0; }
  31770. if (cy === void 0) { cy = 0; }
  31771. if (numberOfSides === void 0) { numberOfSides = 32; }
  31772. var result = new Array();
  31773. var angle = 0;
  31774. var increment = (Math.PI * 2) / numberOfSides;
  31775. for (var i = 0; i < numberOfSides; i++) {
  31776. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31777. angle -= increment;
  31778. }
  31779. return result;
  31780. };
  31781. Polygon.Parse = function (input) {
  31782. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31783. var i, result = [];
  31784. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31785. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31786. }
  31787. return result;
  31788. };
  31789. Polygon.StartingAt = function (x, y) {
  31790. return BABYLON.Path2.StartingAt(x, y);
  31791. };
  31792. return Polygon;
  31793. })();
  31794. BABYLON.Polygon = Polygon;
  31795. var PolygonMeshBuilder = (function () {
  31796. function PolygonMeshBuilder(name, contours, scene) {
  31797. this._points = new PolygonPoints();
  31798. this._outlinepoints = new PolygonPoints();
  31799. this._holes = [];
  31800. if (!("poly2tri" in window)) {
  31801. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31802. }
  31803. this._name = name;
  31804. this._scene = scene;
  31805. var points;
  31806. if (contours instanceof BABYLON.Path2) {
  31807. points = contours.getPoints();
  31808. }
  31809. else {
  31810. points = contours;
  31811. }
  31812. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31813. this._outlinepoints.add(points);
  31814. }
  31815. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31816. this._swctx.addHole(this._points.add(hole));
  31817. var holepoints = new PolygonPoints();
  31818. holepoints.add(hole);
  31819. this._holes.push(holepoints);
  31820. return this;
  31821. };
  31822. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31823. var _this = this;
  31824. if (updatable === void 0) { updatable = false; }
  31825. var result = new BABYLON.Mesh(this._name, this._scene);
  31826. var normals = [];
  31827. var positions = [];
  31828. var uvs = [];
  31829. var bounds = this._points.computeBounds();
  31830. this._points.elements.forEach(function (p) {
  31831. normals.push(0, 1.0, 0);
  31832. positions.push(p.x, 0, p.y);
  31833. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31834. });
  31835. var indices = [];
  31836. this._swctx.triangulate();
  31837. this._swctx.getTriangles().forEach(function (triangle) {
  31838. triangle.getPoints().forEach(function (point) {
  31839. indices.push(point.index);
  31840. });
  31841. });
  31842. if (depth > 0) {
  31843. var positionscount = (positions.length / 3); //get the current pointcount
  31844. this._points.elements.forEach(function (p) {
  31845. normals.push(0, -1.0, 0);
  31846. positions.push(p.x, -depth, p.y);
  31847. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31848. });
  31849. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31850. var p2;
  31851. var poscounter = 0;
  31852. this._swctx.getTriangles().forEach(function (triangle) {
  31853. triangle.getPoints().forEach(function (point) {
  31854. switch (poscounter) {
  31855. case 0:
  31856. p1 = point;
  31857. break;
  31858. case 1:
  31859. p2 = point;
  31860. break;
  31861. case 2:
  31862. indices.push(point.index + positionscount);
  31863. indices.push(p2.index + positionscount);
  31864. indices.push(p1.index + positionscount);
  31865. poscounter = -1;
  31866. break;
  31867. }
  31868. poscounter++;
  31869. //indices.push((<IndexedVector2>point).index + positionscount);
  31870. });
  31871. });
  31872. //Add the sides
  31873. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31874. this._holes.forEach(function (hole) {
  31875. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31876. });
  31877. }
  31878. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31879. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31880. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31881. result.setIndices(indices);
  31882. return result;
  31883. };
  31884. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31885. var StartIndex = positions.length / 3;
  31886. var ulength = 0;
  31887. for (var i = 0; i < points.elements.length; i++) {
  31888. var p = points.elements[i];
  31889. var p1;
  31890. if ((i + 1) > points.elements.length - 1) {
  31891. p1 = points.elements[0];
  31892. }
  31893. else {
  31894. p1 = points.elements[i + 1];
  31895. }
  31896. positions.push(p.x, 0, p.y);
  31897. positions.push(p.x, -depth, p.y);
  31898. positions.push(p1.x, 0, p1.y);
  31899. positions.push(p1.x, -depth, p1.y);
  31900. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31901. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31902. var v3 = v2.subtract(v1);
  31903. var v4 = new BABYLON.Vector3(0, 1, 0);
  31904. var vn = BABYLON.Vector3.Cross(v3, v4);
  31905. vn = vn.normalize();
  31906. uvs.push(ulength / bounds.width, 0);
  31907. uvs.push(ulength / bounds.width, 1);
  31908. ulength += v3.length();
  31909. uvs.push((ulength / bounds.width), 0);
  31910. uvs.push((ulength / bounds.width), 1);
  31911. if (!flip) {
  31912. normals.push(-vn.x, -vn.y, -vn.z);
  31913. normals.push(-vn.x, -vn.y, -vn.z);
  31914. normals.push(-vn.x, -vn.y, -vn.z);
  31915. normals.push(-vn.x, -vn.y, -vn.z);
  31916. indices.push(StartIndex);
  31917. indices.push(StartIndex + 1);
  31918. indices.push(StartIndex + 2);
  31919. indices.push(StartIndex + 1);
  31920. indices.push(StartIndex + 3);
  31921. indices.push(StartIndex + 2);
  31922. }
  31923. else {
  31924. normals.push(vn.x, vn.y, vn.z);
  31925. normals.push(vn.x, vn.y, vn.z);
  31926. normals.push(vn.x, vn.y, vn.z);
  31927. normals.push(vn.x, vn.y, vn.z);
  31928. indices.push(StartIndex);
  31929. indices.push(StartIndex + 2);
  31930. indices.push(StartIndex + 1);
  31931. indices.push(StartIndex + 1);
  31932. indices.push(StartIndex + 2);
  31933. indices.push(StartIndex + 3);
  31934. }
  31935. StartIndex += 4;
  31936. }
  31937. ;
  31938. };
  31939. return PolygonMeshBuilder;
  31940. })();
  31941. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31942. })(BABYLON || (BABYLON = {}));
  31943. var BABYLON;
  31944. (function (BABYLON) {
  31945. var SimplificationSettings = (function () {
  31946. function SimplificationSettings(quality, distance, optimizeMesh) {
  31947. this.quality = quality;
  31948. this.distance = distance;
  31949. this.optimizeMesh = optimizeMesh;
  31950. }
  31951. return SimplificationSettings;
  31952. })();
  31953. BABYLON.SimplificationSettings = SimplificationSettings;
  31954. var SimplificationQueue = (function () {
  31955. function SimplificationQueue() {
  31956. this.running = false;
  31957. this._simplificationArray = [];
  31958. }
  31959. SimplificationQueue.prototype.addTask = function (task) {
  31960. this._simplificationArray.push(task);
  31961. };
  31962. SimplificationQueue.prototype.executeNext = function () {
  31963. var task = this._simplificationArray.pop();
  31964. if (task) {
  31965. this.running = true;
  31966. this.runSimplification(task);
  31967. }
  31968. else {
  31969. this.running = false;
  31970. }
  31971. };
  31972. SimplificationQueue.prototype.runSimplification = function (task) {
  31973. var _this = this;
  31974. if (task.parallelProcessing) {
  31975. //parallel simplifier
  31976. task.settings.forEach(function (setting) {
  31977. var simplifier = _this.getSimplifier(task);
  31978. simplifier.simplify(setting, function (newMesh) {
  31979. task.mesh.addLODLevel(setting.distance, newMesh);
  31980. newMesh.isVisible = true;
  31981. //check if it is the last
  31982. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31983. //all done, run the success callback.
  31984. task.successCallback();
  31985. }
  31986. _this.executeNext();
  31987. });
  31988. });
  31989. }
  31990. else {
  31991. //single simplifier.
  31992. var simplifier = this.getSimplifier(task);
  31993. var runDecimation = function (setting, callback) {
  31994. simplifier.simplify(setting, function (newMesh) {
  31995. task.mesh.addLODLevel(setting.distance, newMesh);
  31996. newMesh.isVisible = true;
  31997. //run the next quality level
  31998. callback();
  31999. });
  32000. };
  32001. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  32002. runDecimation(task.settings[loop.index], function () {
  32003. loop.executeNext();
  32004. });
  32005. }, function () {
  32006. //execution ended, run the success callback.
  32007. if (task.successCallback) {
  32008. task.successCallback();
  32009. }
  32010. _this.executeNext();
  32011. });
  32012. }
  32013. };
  32014. SimplificationQueue.prototype.getSimplifier = function (task) {
  32015. switch (task.simplificationType) {
  32016. case SimplificationType.QUADRATIC:
  32017. default:
  32018. return new QuadraticErrorSimplification(task.mesh);
  32019. }
  32020. };
  32021. return SimplificationQueue;
  32022. })();
  32023. BABYLON.SimplificationQueue = SimplificationQueue;
  32024. /**
  32025. * The implemented types of simplification.
  32026. * At the moment only Quadratic Error Decimation is implemented.
  32027. */
  32028. (function (SimplificationType) {
  32029. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  32030. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  32031. var SimplificationType = BABYLON.SimplificationType;
  32032. var DecimationTriangle = (function () {
  32033. function DecimationTriangle(vertices) {
  32034. this.vertices = vertices;
  32035. this.error = new Array(4);
  32036. this.deleted = false;
  32037. this.isDirty = false;
  32038. this.deletePending = false;
  32039. this.borderFactor = 0;
  32040. }
  32041. return DecimationTriangle;
  32042. })();
  32043. BABYLON.DecimationTriangle = DecimationTriangle;
  32044. var DecimationVertex = (function () {
  32045. function DecimationVertex(position, id) {
  32046. this.position = position;
  32047. this.id = id;
  32048. this.isBorder = true;
  32049. this.q = new QuadraticMatrix();
  32050. this.triangleCount = 0;
  32051. this.triangleStart = 0;
  32052. this.originalOffsets = [];
  32053. }
  32054. DecimationVertex.prototype.updatePosition = function (newPosition) {
  32055. this.position.copyFrom(newPosition);
  32056. };
  32057. return DecimationVertex;
  32058. })();
  32059. BABYLON.DecimationVertex = DecimationVertex;
  32060. var QuadraticMatrix = (function () {
  32061. function QuadraticMatrix(data) {
  32062. this.data = new Array(10);
  32063. for (var i = 0; i < 10; ++i) {
  32064. if (data && data[i]) {
  32065. this.data[i] = data[i];
  32066. }
  32067. else {
  32068. this.data[i] = 0;
  32069. }
  32070. }
  32071. }
  32072. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  32073. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  32074. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  32075. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  32076. return det;
  32077. };
  32078. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  32079. for (var i = 0; i < 10; ++i) {
  32080. this.data[i] += matrix.data[i];
  32081. }
  32082. };
  32083. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  32084. for (var i = 0; i < 10; ++i) {
  32085. this.data[i] += data[i];
  32086. }
  32087. };
  32088. QuadraticMatrix.prototype.add = function (matrix) {
  32089. var m = new QuadraticMatrix();
  32090. for (var i = 0; i < 10; ++i) {
  32091. m.data[i] = this.data[i] + matrix.data[i];
  32092. }
  32093. return m;
  32094. };
  32095. QuadraticMatrix.FromData = function (a, b, c, d) {
  32096. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  32097. };
  32098. //returning an array to avoid garbage collection
  32099. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  32100. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  32101. };
  32102. return QuadraticMatrix;
  32103. })();
  32104. BABYLON.QuadraticMatrix = QuadraticMatrix;
  32105. var Reference = (function () {
  32106. function Reference(vertexId, triangleId) {
  32107. this.vertexId = vertexId;
  32108. this.triangleId = triangleId;
  32109. }
  32110. return Reference;
  32111. })();
  32112. BABYLON.Reference = Reference;
  32113. /**
  32114. * An implementation of the Quadratic Error simplification algorithm.
  32115. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  32116. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  32117. * @author RaananW
  32118. */
  32119. var QuadraticErrorSimplification = (function () {
  32120. function QuadraticErrorSimplification(_mesh) {
  32121. this._mesh = _mesh;
  32122. this.initialized = false;
  32123. this.syncIterations = 5000;
  32124. this.aggressiveness = 7;
  32125. this.decimationIterations = 100;
  32126. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  32127. }
  32128. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  32129. var _this = this;
  32130. this.initDecimatedMesh();
  32131. //iterating through the submeshes array, one after the other.
  32132. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  32133. _this.initWithMesh(loop.index, function () {
  32134. _this.runDecimation(settings, loop.index, function () {
  32135. loop.executeNext();
  32136. });
  32137. }, settings.optimizeMesh);
  32138. }, function () {
  32139. setTimeout(function () {
  32140. successCallback(_this._reconstructedMesh);
  32141. }, 0);
  32142. });
  32143. };
  32144. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  32145. var _this = this;
  32146. var gCount = 0;
  32147. triangle.vertices.forEach(function (vertex) {
  32148. var count = 0;
  32149. var vPos = vertex.position;
  32150. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  32151. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  32152. ++count;
  32153. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  32154. ++count;
  32155. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  32156. ++count;
  32157. if (count > 1) {
  32158. ++gCount;
  32159. }
  32160. ;
  32161. });
  32162. if (gCount > 1) {
  32163. console.log(triangle, gCount);
  32164. }
  32165. return gCount > 1;
  32166. };
  32167. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  32168. var _this = this;
  32169. var targetCount = ~~(this.triangles.length * settings.quality);
  32170. var deletedTriangles = 0;
  32171. var triangleCount = this.triangles.length;
  32172. var iterationFunction = function (iteration, callback) {
  32173. setTimeout(function () {
  32174. if (iteration % 5 === 0) {
  32175. _this.updateMesh(iteration === 0);
  32176. }
  32177. for (var i = 0; i < _this.triangles.length; ++i) {
  32178. _this.triangles[i].isDirty = false;
  32179. }
  32180. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  32181. var trianglesIterator = function (i) {
  32182. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  32183. var t = _this.triangles[tIdx];
  32184. if (!t)
  32185. return;
  32186. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  32187. return;
  32188. }
  32189. for (var j = 0; j < 3; ++j) {
  32190. if (t.error[j] < threshold) {
  32191. var deleted0 = [];
  32192. var deleted1 = [];
  32193. var v0 = t.vertices[j];
  32194. var v1 = t.vertices[(j + 1) % 3];
  32195. if (v0.isBorder !== v1.isBorder)
  32196. continue;
  32197. var p = BABYLON.Vector3.Zero();
  32198. var n = BABYLON.Vector3.Zero();
  32199. var uv = BABYLON.Vector2.Zero();
  32200. var color = new BABYLON.Color4(0, 0, 0, 1);
  32201. _this.calculateError(v0, v1, p, n, uv, color);
  32202. var delTr = [];
  32203. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  32204. continue;
  32205. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  32206. continue;
  32207. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  32208. continue;
  32209. var uniqueArray = [];
  32210. delTr.forEach(function (deletedT) {
  32211. if (uniqueArray.indexOf(deletedT) === -1) {
  32212. deletedT.deletePending = true;
  32213. uniqueArray.push(deletedT);
  32214. }
  32215. });
  32216. if (uniqueArray.length % 2 != 0) {
  32217. continue;
  32218. }
  32219. v0.q = v1.q.add(v0.q);
  32220. v0.updatePosition(p);
  32221. var tStart = _this.references.length;
  32222. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  32223. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  32224. var tCount = _this.references.length - tStart;
  32225. if (tCount <= v0.triangleCount) {
  32226. if (tCount) {
  32227. for (var c = 0; c < tCount; c++) {
  32228. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  32229. }
  32230. }
  32231. }
  32232. else {
  32233. v0.triangleStart = tStart;
  32234. }
  32235. v0.triangleCount = tCount;
  32236. break;
  32237. }
  32238. }
  32239. };
  32240. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  32241. }, 0);
  32242. };
  32243. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  32244. if (triangleCount - deletedTriangles <= targetCount)
  32245. loop.breakLoop();
  32246. else {
  32247. iterationFunction(loop.index, function () {
  32248. loop.executeNext();
  32249. });
  32250. }
  32251. }, function () {
  32252. setTimeout(function () {
  32253. //reconstruct this part of the mesh
  32254. _this.reconstructMesh(submeshIndex);
  32255. successCallback();
  32256. }, 0);
  32257. });
  32258. };
  32259. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  32260. var _this = this;
  32261. this.vertices = [];
  32262. this.triangles = [];
  32263. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32264. var indices = this._mesh.getIndices();
  32265. var submesh = this._mesh.subMeshes[submeshIndex];
  32266. var findInVertices = function (positionToSearch) {
  32267. if (optimizeMesh) {
  32268. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  32269. if (_this.vertices[ii].position.equals(positionToSearch)) {
  32270. return _this.vertices[ii];
  32271. }
  32272. }
  32273. }
  32274. return null;
  32275. };
  32276. var vertexReferences = [];
  32277. var vertexInit = function (i) {
  32278. var offset = i + submesh.verticesStart;
  32279. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  32280. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  32281. vertex.originalOffsets.push(offset);
  32282. if (vertex.id == _this.vertices.length) {
  32283. _this.vertices.push(vertex);
  32284. }
  32285. vertexReferences.push(vertex.id);
  32286. };
  32287. //var totalVertices = mesh.getTotalVertices();
  32288. var totalVertices = submesh.verticesCount;
  32289. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  32290. var indicesInit = function (i) {
  32291. var offset = (submesh.indexStart / 3) + i;
  32292. var pos = (offset * 3);
  32293. var i0 = indices[pos + 0];
  32294. var i1 = indices[pos + 1];
  32295. var i2 = indices[pos + 2];
  32296. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  32297. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  32298. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  32299. var triangle = new DecimationTriangle([v0, v1, v2]);
  32300. triangle.originalOffset = pos;
  32301. _this.triangles.push(triangle);
  32302. };
  32303. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  32304. _this.init(callback);
  32305. });
  32306. });
  32307. };
  32308. QuadraticErrorSimplification.prototype.init = function (callback) {
  32309. var _this = this;
  32310. var triangleInit1 = function (i) {
  32311. var t = _this.triangles[i];
  32312. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  32313. for (var j = 0; j < 3; j++) {
  32314. 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))));
  32315. }
  32316. };
  32317. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  32318. var triangleInit2 = function (i) {
  32319. var t = _this.triangles[i];
  32320. for (var j = 0; j < 3; ++j) {
  32321. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  32322. }
  32323. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32324. };
  32325. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  32326. _this.initialized = true;
  32327. callback();
  32328. });
  32329. });
  32330. };
  32331. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  32332. var newTriangles = [];
  32333. var i;
  32334. for (i = 0; i < this.vertices.length; ++i) {
  32335. this.vertices[i].triangleCount = 0;
  32336. }
  32337. var t;
  32338. var j;
  32339. for (i = 0; i < this.triangles.length; ++i) {
  32340. if (!this.triangles[i].deleted) {
  32341. t = this.triangles[i];
  32342. for (j = 0; j < 3; ++j) {
  32343. t.vertices[j].triangleCount = 1;
  32344. }
  32345. newTriangles.push(t);
  32346. }
  32347. }
  32348. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  32349. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  32350. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  32351. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  32352. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32353. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32354. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32355. var vertexCount = 0;
  32356. for (i = 0; i < this.vertices.length; ++i) {
  32357. var vertex = this.vertices[i];
  32358. vertex.id = vertexCount;
  32359. if (vertex.triangleCount) {
  32360. vertex.originalOffsets.forEach(function (originalOffset) {
  32361. newPositionData.push(vertex.position.x);
  32362. newPositionData.push(vertex.position.y);
  32363. newPositionData.push(vertex.position.z);
  32364. newNormalData.push(normalData[originalOffset * 3]);
  32365. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  32366. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  32367. if (uvs && uvs.length) {
  32368. newUVsData.push(uvs[(originalOffset * 2)]);
  32369. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  32370. }
  32371. else if (colorsData && colorsData.length) {
  32372. newColorsData.push(colorsData[(originalOffset * 4)]);
  32373. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  32374. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  32375. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  32376. }
  32377. ++vertexCount;
  32378. });
  32379. }
  32380. }
  32381. var startingIndex = this._reconstructedMesh.getTotalIndices();
  32382. var startingVertex = this._reconstructedMesh.getTotalVertices();
  32383. var submeshesArray = this._reconstructedMesh.subMeshes;
  32384. this._reconstructedMesh.subMeshes = [];
  32385. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  32386. var originalIndices = this._mesh.getIndices();
  32387. for (i = 0; i < newTriangles.length; ++i) {
  32388. var t = newTriangles[i];
  32389. //now get the new referencing point for each vertex
  32390. [0, 1, 2].forEach(function (idx) {
  32391. var id = originalIndices[t.originalOffset + idx];
  32392. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  32393. if (offset < 0)
  32394. offset = 0;
  32395. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  32396. });
  32397. }
  32398. //overwriting the old vertex buffers and indices.
  32399. this._reconstructedMesh.setIndices(newIndicesArray);
  32400. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  32401. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  32402. if (newUVsData.length > 0)
  32403. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  32404. if (newColorsData.length > 0)
  32405. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  32406. //create submesh
  32407. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  32408. if (submeshIndex > 0) {
  32409. this._reconstructedMesh.subMeshes = [];
  32410. submeshesArray.forEach(function (submesh) {
  32411. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  32412. });
  32413. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  32414. }
  32415. };
  32416. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  32417. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  32418. this._reconstructedMesh.material = this._mesh.material;
  32419. this._reconstructedMesh.parent = this._mesh.parent;
  32420. this._reconstructedMesh.isVisible = false;
  32421. };
  32422. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  32423. for (var i = 0; i < vertex1.triangleCount; ++i) {
  32424. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  32425. if (t.deleted)
  32426. continue;
  32427. var s = this.references[vertex1.triangleStart + i].vertexId;
  32428. var v1 = t.vertices[(s + 1) % 3];
  32429. var v2 = t.vertices[(s + 2) % 3];
  32430. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  32431. deletedArray[i] = true;
  32432. delTr.push(t);
  32433. continue;
  32434. }
  32435. var d1 = v1.position.subtract(point);
  32436. d1 = d1.normalize();
  32437. var d2 = v2.position.subtract(point);
  32438. d2 = d2.normalize();
  32439. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  32440. return true;
  32441. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  32442. deletedArray[i] = false;
  32443. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  32444. return true;
  32445. }
  32446. return false;
  32447. };
  32448. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32449. var newDeleted = deletedTriangles;
  32450. for (var i = 0; i < vertex.triangleCount; ++i) {
  32451. var ref = this.references[vertex.triangleStart + i];
  32452. var t = this.triangles[ref.triangleId];
  32453. if (t.deleted)
  32454. continue;
  32455. if (deletedArray[i] && t.deletePending) {
  32456. t.deleted = true;
  32457. newDeleted++;
  32458. continue;
  32459. }
  32460. t.vertices[ref.vertexId] = origVertex;
  32461. t.isDirty = true;
  32462. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32463. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32464. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32465. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32466. this.references.push(ref);
  32467. }
  32468. return newDeleted;
  32469. };
  32470. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32471. for (var i = 0; i < this.vertices.length; ++i) {
  32472. var vCount = [];
  32473. var vId = [];
  32474. var v = this.vertices[i];
  32475. var j;
  32476. for (j = 0; j < v.triangleCount; ++j) {
  32477. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32478. for (var ii = 0; ii < 3; ii++) {
  32479. var ofs = 0;
  32480. var vv = triangle.vertices[ii];
  32481. while (ofs < vCount.length) {
  32482. if (vId[ofs] === vv.id)
  32483. break;
  32484. ++ofs;
  32485. }
  32486. if (ofs === vCount.length) {
  32487. vCount.push(1);
  32488. vId.push(vv.id);
  32489. }
  32490. else {
  32491. vCount[ofs]++;
  32492. }
  32493. }
  32494. }
  32495. for (j = 0; j < vCount.length; ++j) {
  32496. if (vCount[j] === 1) {
  32497. this.vertices[vId[j]].isBorder = true;
  32498. }
  32499. else {
  32500. this.vertices[vId[j]].isBorder = false;
  32501. }
  32502. }
  32503. }
  32504. };
  32505. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32506. if (identifyBorders === void 0) { identifyBorders = false; }
  32507. var i;
  32508. if (!identifyBorders) {
  32509. var newTrianglesVector = [];
  32510. for (i = 0; i < this.triangles.length; ++i) {
  32511. if (!this.triangles[i].deleted) {
  32512. newTrianglesVector.push(this.triangles[i]);
  32513. }
  32514. }
  32515. this.triangles = newTrianglesVector;
  32516. }
  32517. for (i = 0; i < this.vertices.length; ++i) {
  32518. this.vertices[i].triangleCount = 0;
  32519. this.vertices[i].triangleStart = 0;
  32520. }
  32521. var t;
  32522. var j;
  32523. var v;
  32524. for (i = 0; i < this.triangles.length; ++i) {
  32525. t = this.triangles[i];
  32526. for (j = 0; j < 3; ++j) {
  32527. v = t.vertices[j];
  32528. v.triangleCount++;
  32529. }
  32530. }
  32531. var tStart = 0;
  32532. for (i = 0; i < this.vertices.length; ++i) {
  32533. this.vertices[i].triangleStart = tStart;
  32534. tStart += this.vertices[i].triangleCount;
  32535. this.vertices[i].triangleCount = 0;
  32536. }
  32537. var newReferences = new Array(this.triangles.length * 3);
  32538. for (i = 0; i < this.triangles.length; ++i) {
  32539. t = this.triangles[i];
  32540. for (j = 0; j < 3; ++j) {
  32541. v = t.vertices[j];
  32542. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32543. v.triangleCount++;
  32544. }
  32545. }
  32546. this.references = newReferences;
  32547. if (identifyBorders) {
  32548. this.identifyBorder();
  32549. }
  32550. };
  32551. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32552. var x = point.x;
  32553. var y = point.y;
  32554. var z = point.z;
  32555. 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
  32556. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32557. };
  32558. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32559. var q = vertex1.q.add(vertex2.q);
  32560. var border = vertex1.isBorder && vertex2.isBorder;
  32561. var error = 0;
  32562. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32563. if (qDet !== 0 && !border) {
  32564. if (!pointResult) {
  32565. pointResult = BABYLON.Vector3.Zero();
  32566. }
  32567. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32568. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32569. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32570. error = this.vertexError(q, pointResult);
  32571. }
  32572. else {
  32573. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32574. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32575. var error1 = this.vertexError(q, vertex1.position);
  32576. var error2 = this.vertexError(q, vertex2.position);
  32577. var error3 = this.vertexError(q, p3);
  32578. error = Math.min(error1, error2, error3);
  32579. if (error === error1) {
  32580. if (pointResult) {
  32581. pointResult.copyFrom(vertex1.position);
  32582. }
  32583. }
  32584. else if (error === error2) {
  32585. if (pointResult) {
  32586. pointResult.copyFrom(vertex2.position);
  32587. }
  32588. }
  32589. else {
  32590. if (pointResult) {
  32591. pointResult.copyFrom(p3);
  32592. }
  32593. }
  32594. }
  32595. return error;
  32596. };
  32597. return QuadraticErrorSimplification;
  32598. })();
  32599. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32600. })(BABYLON || (BABYLON = {}));
  32601. var BABYLON;
  32602. (function (BABYLON) {
  32603. var Analyser = (function () {
  32604. function Analyser(scene) {
  32605. this.SMOOTHING = 0.75;
  32606. this.FFT_SIZE = 512;
  32607. this.BARGRAPHAMPLITUDE = 256;
  32608. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32609. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32610. this._scene = scene;
  32611. this._audioEngine = BABYLON.Engine.audioEngine;
  32612. if (this._audioEngine.canUseWebAudio) {
  32613. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32614. this._webAudioAnalyser.minDecibels = -140;
  32615. this._webAudioAnalyser.maxDecibels = 0;
  32616. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32617. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32618. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32619. }
  32620. }
  32621. Analyser.prototype.getFrequencyBinCount = function () {
  32622. if (this._audioEngine.canUseWebAudio) {
  32623. return this._webAudioAnalyser.frequencyBinCount;
  32624. }
  32625. else {
  32626. return 0;
  32627. }
  32628. };
  32629. Analyser.prototype.getByteFrequencyData = function () {
  32630. if (this._audioEngine.canUseWebAudio) {
  32631. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32632. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32633. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32634. }
  32635. return this._byteFreqs;
  32636. };
  32637. Analyser.prototype.getByteTimeDomainData = function () {
  32638. if (this._audioEngine.canUseWebAudio) {
  32639. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32640. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32641. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32642. }
  32643. return this._byteTime;
  32644. };
  32645. Analyser.prototype.getFloatFrequencyData = function () {
  32646. if (this._audioEngine.canUseWebAudio) {
  32647. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32648. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32649. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32650. }
  32651. return this._floatFreqs;
  32652. };
  32653. Analyser.prototype.drawDebugCanvas = function () {
  32654. var _this = this;
  32655. if (this._audioEngine.canUseWebAudio) {
  32656. if (!this._debugCanvas) {
  32657. this._debugCanvas = document.createElement("canvas");
  32658. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32659. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32660. this._debugCanvas.style.position = "absolute";
  32661. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32662. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32663. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32664. document.body.appendChild(this._debugCanvas);
  32665. this._registerFunc = function () {
  32666. _this.drawDebugCanvas();
  32667. };
  32668. this._scene.registerBeforeRender(this._registerFunc);
  32669. }
  32670. if (this._registerFunc) {
  32671. var workingArray = this.getByteFrequencyData();
  32672. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32673. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32674. // Draw the frequency domain chart.
  32675. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32676. var value = workingArray[i];
  32677. var percent = value / this.BARGRAPHAMPLITUDE;
  32678. var height = this.DEBUGCANVASSIZE.height * percent;
  32679. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32680. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32681. var hue = i / this.getFrequencyBinCount() * 360;
  32682. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32683. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32684. }
  32685. }
  32686. }
  32687. };
  32688. Analyser.prototype.stopDebugCanvas = function () {
  32689. if (this._debugCanvas) {
  32690. this._scene.unregisterBeforeRender(this._registerFunc);
  32691. this._registerFunc = null;
  32692. document.body.removeChild(this._debugCanvas);
  32693. this._debugCanvas = null;
  32694. this._debugCanvasContext = null;
  32695. }
  32696. };
  32697. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32698. if (this._audioEngine.canUseWebAudio) {
  32699. inputAudioNode.connect(this._webAudioAnalyser);
  32700. this._webAudioAnalyser.connect(outputAudioNode);
  32701. }
  32702. };
  32703. Analyser.prototype.dispose = function () {
  32704. if (this._audioEngine.canUseWebAudio) {
  32705. this._webAudioAnalyser.disconnect();
  32706. }
  32707. };
  32708. return Analyser;
  32709. })();
  32710. BABYLON.Analyser = Analyser;
  32711. })(BABYLON || (BABYLON = {}));
  32712. var BABYLON;
  32713. (function (BABYLON) {
  32714. var DepthRenderer = (function () {
  32715. function DepthRenderer(scene, type) {
  32716. var _this = this;
  32717. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32718. this._viewMatrix = BABYLON.Matrix.Zero();
  32719. this._projectionMatrix = BABYLON.Matrix.Zero();
  32720. this._transformMatrix = BABYLON.Matrix.Zero();
  32721. this._worldViewProjection = BABYLON.Matrix.Zero();
  32722. this._scene = scene;
  32723. var engine = scene.getEngine();
  32724. // Render target
  32725. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32726. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32727. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32728. this._depthMap.refreshRate = 1;
  32729. this._depthMap.renderParticles = false;
  32730. this._depthMap.renderList = null;
  32731. // set default depth value to 1.0 (far away)
  32732. this._depthMap.onClear = function (engine) {
  32733. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32734. };
  32735. // Custom render function
  32736. var renderSubMesh = function (subMesh) {
  32737. var mesh = subMesh.getRenderingMesh();
  32738. var scene = _this._scene;
  32739. var engine = scene.getEngine();
  32740. // Culling
  32741. engine.setState(subMesh.getMaterial().backFaceCulling);
  32742. // Managing instances
  32743. var batch = mesh._getInstancesRenderList(subMesh._id);
  32744. if (batch.mustReturn) {
  32745. return;
  32746. }
  32747. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32748. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32749. engine.enableEffect(_this._effect);
  32750. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32751. var material = subMesh.getMaterial();
  32752. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32753. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32754. // Alpha test
  32755. if (material && material.needAlphaTesting()) {
  32756. var alphaTexture = material.getAlphaTestTexture();
  32757. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32758. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32759. }
  32760. // Bones
  32761. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32762. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32763. }
  32764. // Draw
  32765. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32766. }
  32767. };
  32768. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32769. var index;
  32770. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32771. renderSubMesh(opaqueSubMeshes.data[index]);
  32772. }
  32773. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32774. renderSubMesh(alphaTestSubMeshes.data[index]);
  32775. }
  32776. };
  32777. }
  32778. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32779. var defines = [];
  32780. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32781. var mesh = subMesh.getMesh();
  32782. var scene = mesh.getScene();
  32783. var material = subMesh.getMaterial();
  32784. // Alpha test
  32785. if (material && material.needAlphaTesting()) {
  32786. defines.push("#define ALPHATEST");
  32787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32788. attribs.push(BABYLON.VertexBuffer.UVKind);
  32789. defines.push("#define UV1");
  32790. }
  32791. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32792. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32793. defines.push("#define UV2");
  32794. }
  32795. }
  32796. // Bones
  32797. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32798. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32799. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32800. defines.push("#define BONES");
  32801. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32802. }
  32803. // Instances
  32804. if (useInstances) {
  32805. defines.push("#define INSTANCES");
  32806. attribs.push("world0");
  32807. attribs.push("world1");
  32808. attribs.push("world2");
  32809. attribs.push("world3");
  32810. }
  32811. // Get correct effect
  32812. var join = defines.join("\n");
  32813. if (this._cachedDefines !== join) {
  32814. this._cachedDefines = join;
  32815. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32816. }
  32817. return this._effect.isReady();
  32818. };
  32819. DepthRenderer.prototype.getDepthMap = function () {
  32820. return this._depthMap;
  32821. };
  32822. // Methods
  32823. DepthRenderer.prototype.dispose = function () {
  32824. this._depthMap.dispose();
  32825. };
  32826. return DepthRenderer;
  32827. })();
  32828. BABYLON.DepthRenderer = DepthRenderer;
  32829. })(BABYLON || (BABYLON = {}));
  32830. var BABYLON;
  32831. (function (BABYLON) {
  32832. var SSAORenderingPipeline = (function (_super) {
  32833. __extends(SSAORenderingPipeline, _super);
  32834. /**
  32835. * @constructor
  32836. * @param {string} name - The rendering pipeline name
  32837. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32838. * @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 }
  32839. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32840. */
  32841. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32842. var _this = this;
  32843. _super.call(this, scene.getEngine(), name);
  32844. // Members
  32845. /**
  32846. * The PassPostProcess id in the pipeline that contains the original scene color
  32847. * @type {string}
  32848. */
  32849. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32850. /**
  32851. * The SSAO PostProcess id in the pipeline
  32852. * @type {string}
  32853. */
  32854. this.SSAORenderEffect = "SSAORenderEffect";
  32855. /**
  32856. * The horizontal blur PostProcess id in the pipeline
  32857. * @type {string}
  32858. */
  32859. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32860. /**
  32861. * The vertical blur PostProcess id in the pipeline
  32862. * @type {string}
  32863. */
  32864. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32865. /**
  32866. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32867. * @type {string}
  32868. */
  32869. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32870. /**
  32871. * The output strength of the SSAO post-process. Default value is 1.0.
  32872. * @type {number}
  32873. */
  32874. this.totalStrength = 1.0;
  32875. /**
  32876. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32877. * @type {number}
  32878. */
  32879. this.radius = 0.0002;
  32880. /**
  32881. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32882. * Must not be equal to fallOff and superior to fallOff.
  32883. * Default value is 0.0075
  32884. * @type {number}
  32885. */
  32886. this.area = 0.0075;
  32887. /**
  32888. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32889. * Must not be equal to area and inferior to area.
  32890. * Default value is 0.0002
  32891. * @type {number}
  32892. */
  32893. this.fallOff = 0.0002;
  32894. this._firstUpdate = true;
  32895. this._scene = scene;
  32896. // Set up assets
  32897. this._createRandomTexture();
  32898. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32899. var ssaoRatio = ratio.ssaoRatio || ratio;
  32900. var combineRatio = ratio.combineRatio || ratio;
  32901. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32902. this._createSSAOPostProcess(ssaoRatio);
  32903. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32904. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32905. this._createSSAOCombinePostProcess(combineRatio);
  32906. // Set up pipeline
  32907. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32908. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32909. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32911. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32912. // Finish
  32913. scene.postProcessRenderPipelineManager.addPipeline(this);
  32914. if (cameras)
  32915. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32916. }
  32917. // Public Methods
  32918. /**
  32919. * Returns the horizontal blur PostProcess
  32920. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32921. */
  32922. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32923. return this._blurHPostProcess;
  32924. };
  32925. /**
  32926. * Returns the vertical blur PostProcess
  32927. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32928. */
  32929. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32930. return this._blurVPostProcess;
  32931. };
  32932. /**
  32933. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32934. */
  32935. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32936. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32937. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32938. this._originalColorPostProcess = undefined;
  32939. this._ssaoPostProcess = undefined;
  32940. this._blurHPostProcess = undefined;
  32941. this._blurVPostProcess = undefined;
  32942. this._ssaoCombinePostProcess = undefined;
  32943. this._randomTexture.dispose();
  32944. if (disableDepthRender)
  32945. this._scene.disableDepthRenderer();
  32946. };
  32947. // Private Methods
  32948. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32949. var _this = this;
  32950. var sampleSphere = [
  32951. 0.5381, 0.1856, -0.4319,
  32952. 0.1379, 0.2486, 0.4430,
  32953. 0.3371, 0.5679, -0.0057,
  32954. -0.6999, -0.0451, -0.0019,
  32955. 0.0689, -0.1598, -0.8547,
  32956. 0.0560, 0.0069, -0.1843,
  32957. -0.0146, 0.1402, 0.0762,
  32958. 0.0100, -0.1924, -0.0344,
  32959. -0.3577, -0.5301, -0.4358,
  32960. -0.3169, 0.1063, 0.0158,
  32961. 0.0103, -0.5869, 0.0046,
  32962. -0.0897, -0.4940, 0.3287,
  32963. 0.7119, -0.0154, -0.0918,
  32964. -0.0533, 0.0596, -0.5411,
  32965. 0.0352, -0.0631, 0.5460,
  32966. -0.4776, 0.2847, -0.0271
  32967. ];
  32968. var samplesFactor = 1.0 / 16.0;
  32969. 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);
  32970. this._ssaoPostProcess.onApply = function (effect) {
  32971. if (_this._firstUpdate) {
  32972. effect.setArray3("sampleSphere", sampleSphere);
  32973. effect.setFloat("samplesFactor", samplesFactor);
  32974. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32975. _this._firstUpdate = false;
  32976. }
  32977. effect.setFloat("totalStrength", _this.totalStrength);
  32978. effect.setFloat("radius", _this.radius);
  32979. effect.setFloat("area", _this.area);
  32980. effect.setFloat("fallOff", _this.fallOff);
  32981. effect.setTexture("textureSampler", _this._depthTexture);
  32982. effect.setTexture("randomSampler", _this._randomTexture);
  32983. };
  32984. };
  32985. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32986. var _this = this;
  32987. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32988. this._ssaoCombinePostProcess.onApply = function (effect) {
  32989. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32990. };
  32991. };
  32992. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32993. var size = 512;
  32994. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32995. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32996. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32997. var context = this._randomTexture.getContext();
  32998. var rand = function (min, max) {
  32999. return Math.random() * (max - min) + min;
  33000. };
  33001. for (var x = 0; x < size; x++) {
  33002. for (var y = 0; y < size; y++) {
  33003. var randVector = BABYLON.Vector3.Zero();
  33004. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  33005. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  33006. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  33007. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  33008. context.fillRect(x, y, 1, 1);
  33009. }
  33010. }
  33011. this._randomTexture.update(false);
  33012. };
  33013. return SSAORenderingPipeline;
  33014. })(BABYLON.PostProcessRenderPipeline);
  33015. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  33016. })(BABYLON || (BABYLON = {}));
  33017. var BABYLON;
  33018. (function (BABYLON) {
  33019. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  33020. var VolumetricLightScatteringPostProcess = (function (_super) {
  33021. __extends(VolumetricLightScatteringPostProcess, _super);
  33022. /**
  33023. * @constructor
  33024. * @param {string} name - The post-process name
  33025. * @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)
  33026. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  33027. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  33028. * @param {number} samples - The post-process quality, default 100
  33029. * @param {number} samplingMode - The post-process filtering mode
  33030. * @param {BABYLON.Engine} engine - The babylon engine
  33031. * @param {boolean} reusable - If the post-process is reusable
  33032. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  33033. */
  33034. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  33035. var _this = this;
  33036. if (samples === void 0) { samples = 100; }
  33037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33038. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  33039. this._screenCoordinates = BABYLON.Vector2.Zero();
  33040. /**
  33041. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  33042. * @type {boolean}
  33043. */
  33044. this.useCustomMeshPosition = false;
  33045. /**
  33046. * If the post-process should inverse the light scattering direction
  33047. * @type {boolean}
  33048. */
  33049. this.invert = true;
  33050. /**
  33051. * Set to true to use the diffuseColor instead of the diffuseTexture
  33052. * @type {boolean}
  33053. */
  33054. this.useDiffuseColor = false;
  33055. /**
  33056. * Array containing the excluded meshes not rendered in the internal pass
  33057. */
  33058. this.excludedMeshes = new Array();
  33059. /**
  33060. * Controls the overall intensity of the post-process
  33061. * @type {number}
  33062. */
  33063. this.exposure = 0.3;
  33064. /**
  33065. * Dissipates each sample's contribution in range [0, 1]
  33066. * @type {number}
  33067. */
  33068. this.decay = 0.96815;
  33069. /**
  33070. * Controls the overall intensity of each sample
  33071. * @type {number}
  33072. */
  33073. this.weight = 0.58767;
  33074. /**
  33075. * Controls the density of each sample
  33076. * @type {number}
  33077. */
  33078. this.density = 0.926;
  33079. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  33080. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  33081. // Configure mesh
  33082. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  33083. // Configure
  33084. this._createPass(scene, ratio.passRatio || ratio);
  33085. this.onApply = function (effect) {
  33086. _this._updateMeshScreenCoordinates(scene);
  33087. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  33088. effect.setFloat("exposure", _this.exposure);
  33089. effect.setFloat("decay", _this.decay);
  33090. effect.setFloat("weight", _this.weight);
  33091. effect.setFloat("density", _this.density);
  33092. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  33093. };
  33094. }
  33095. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  33096. var mesh = subMesh.getMesh();
  33097. var defines = [];
  33098. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33099. var material = subMesh.getMaterial();
  33100. var needUV = false;
  33101. // Render this.mesh as default
  33102. if (mesh === this.mesh) {
  33103. if (this.useDiffuseColor) {
  33104. defines.push("#define DIFFUSE_COLOR_RENDER");
  33105. }
  33106. else if (material) {
  33107. if (material.diffuseTexture !== undefined) {
  33108. defines.push("#define BASIC_RENDER");
  33109. }
  33110. else {
  33111. defines.push("#define DIFFUSE_COLOR_RENDER");
  33112. }
  33113. }
  33114. defines.push("#define NEED_UV");
  33115. needUV = true;
  33116. }
  33117. // Alpha test
  33118. if (material) {
  33119. if (material.needAlphaTesting()) {
  33120. defines.push("#define ALPHATEST");
  33121. }
  33122. if (material.opacityTexture !== undefined) {
  33123. defines.push("#define OPACITY");
  33124. if (material.opacityTexture.getAlphaFromRGB) {
  33125. defines.push("#define OPACITYRGB");
  33126. }
  33127. if (!needUV) {
  33128. defines.push("#define NEED_UV");
  33129. }
  33130. }
  33131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33132. attribs.push(BABYLON.VertexBuffer.UVKind);
  33133. defines.push("#define UV1");
  33134. }
  33135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33136. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33137. defines.push("#define UV2");
  33138. }
  33139. }
  33140. // Bones
  33141. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33142. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33143. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33144. defines.push("#define BONES");
  33145. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33146. }
  33147. // Instances
  33148. if (useInstances) {
  33149. defines.push("#define INSTANCES");
  33150. attribs.push("world0");
  33151. attribs.push("world1");
  33152. attribs.push("world2");
  33153. attribs.push("world3");
  33154. }
  33155. // Get correct effect
  33156. var join = defines.join("\n");
  33157. if (this._cachedDefines !== join) {
  33158. this._cachedDefines = join;
  33159. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  33160. }
  33161. return this._volumetricLightScatteringPass.isReady();
  33162. };
  33163. /**
  33164. * Sets the new light position for light scattering effect
  33165. * @param {BABYLON.Vector3} The new custom light position
  33166. */
  33167. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  33168. this._customMeshPosition = position;
  33169. };
  33170. /**
  33171. * Returns the light position for light scattering effect
  33172. * @return {BABYLON.Vector3} The custom light position
  33173. */
  33174. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  33175. return this._customMeshPosition;
  33176. };
  33177. /**
  33178. * Disposes the internal assets and detaches the post-process from the camera
  33179. */
  33180. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  33181. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  33182. if (rttIndex !== -1) {
  33183. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  33184. }
  33185. this._volumetricLightScatteringRTT.dispose();
  33186. _super.prototype.dispose.call(this, camera);
  33187. };
  33188. /**
  33189. * Returns the render target texture used by the post-process
  33190. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  33191. */
  33192. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  33193. return this._volumetricLightScatteringRTT;
  33194. };
  33195. // Private methods
  33196. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  33197. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  33198. return true;
  33199. }
  33200. return false;
  33201. };
  33202. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  33203. var _this = this;
  33204. var engine = scene.getEngine();
  33205. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  33206. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33207. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33208. this._volumetricLightScatteringRTT.renderList = null;
  33209. this._volumetricLightScatteringRTT.renderParticles = false;
  33210. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  33211. // Custom render function for submeshes
  33212. var renderSubMesh = function (subMesh) {
  33213. var mesh = subMesh.getRenderingMesh();
  33214. if (_this._meshExcluded(mesh)) {
  33215. return;
  33216. }
  33217. var scene = mesh.getScene();
  33218. var engine = scene.getEngine();
  33219. // Culling
  33220. engine.setState(subMesh.getMaterial().backFaceCulling);
  33221. // Managing instances
  33222. var batch = mesh._getInstancesRenderList(subMesh._id);
  33223. if (batch.mustReturn) {
  33224. return;
  33225. }
  33226. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33227. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33228. engine.enableEffect(_this._volumetricLightScatteringPass);
  33229. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  33230. var material = subMesh.getMaterial();
  33231. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  33232. // Alpha test
  33233. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  33234. var alphaTexture = material.getAlphaTestTexture();
  33235. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  33236. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  33237. }
  33238. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  33239. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  33240. if (alphaTexture) {
  33241. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33242. }
  33243. }
  33244. if (material.opacityTexture !== undefined) {
  33245. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  33246. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  33247. }
  33248. }
  33249. // Bones
  33250. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33251. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33252. }
  33253. // Draw
  33254. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  33255. }
  33256. };
  33257. // Render target texture callbacks
  33258. var savedSceneClearColor;
  33259. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  33260. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  33261. savedSceneClearColor = scene.clearColor;
  33262. scene.clearColor = sceneClearColor;
  33263. };
  33264. this._volumetricLightScatteringRTT.onAfterRender = function () {
  33265. scene.clearColor = savedSceneClearColor;
  33266. };
  33267. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33268. var engine = scene.getEngine();
  33269. var index;
  33270. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33271. renderSubMesh(opaqueSubMeshes.data[index]);
  33272. }
  33273. engine.setAlphaTesting(true);
  33274. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33275. renderSubMesh(alphaTestSubMeshes.data[index]);
  33276. }
  33277. engine.setAlphaTesting(false);
  33278. if (transparentSubMeshes.length) {
  33279. // Sort sub meshes
  33280. for (index = 0; index < transparentSubMeshes.length; index++) {
  33281. var submesh = transparentSubMeshes.data[index];
  33282. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  33283. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  33284. }
  33285. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  33286. sortedArray.sort(function (a, b) {
  33287. // Alpha index first
  33288. if (a._alphaIndex > b._alphaIndex) {
  33289. return 1;
  33290. }
  33291. if (a._alphaIndex < b._alphaIndex) {
  33292. return -1;
  33293. }
  33294. // Then distance to camera
  33295. if (a._distanceToCamera < b._distanceToCamera) {
  33296. return 1;
  33297. }
  33298. if (a._distanceToCamera > b._distanceToCamera) {
  33299. return -1;
  33300. }
  33301. return 0;
  33302. });
  33303. // Render sub meshes
  33304. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33305. for (index = 0; index < sortedArray.length; index++) {
  33306. renderSubMesh(sortedArray[index]);
  33307. }
  33308. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33309. }
  33310. };
  33311. };
  33312. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  33313. var transform = scene.getTransformMatrix();
  33314. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  33315. this._screenCoordinates.x = pos.x / this._viewPort.width;
  33316. this._screenCoordinates.y = pos.y / this._viewPort.height;
  33317. if (this.invert)
  33318. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  33319. };
  33320. // Static methods
  33321. /**
  33322. * Creates a default mesh for the Volumeric Light Scattering post-process
  33323. * @param {string} The mesh name
  33324. * @param {BABYLON.Scene} The scene where to create the mesh
  33325. * @return {BABYLON.Mesh} the default mesh
  33326. */
  33327. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  33328. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  33329. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  33330. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  33331. return mesh;
  33332. };
  33333. return VolumetricLightScatteringPostProcess;
  33334. })(BABYLON.PostProcess);
  33335. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  33336. })(BABYLON || (BABYLON = {}));
  33337. var BABYLON;
  33338. (function (BABYLON) {
  33339. var LensRenderingPipeline = (function (_super) {
  33340. __extends(LensRenderingPipeline, _super);
  33341. /**
  33342. * @constructor
  33343. *
  33344. * Effect parameters are as follow:
  33345. * {
  33346. * chromatic_aberration: number; // from 0 to x (1 for realism)
  33347. * edge_blur: number; // from 0 to x (1 for realism)
  33348. * distortion: number; // from 0 to x (1 for realism)
  33349. * grain_amount: number; // from 0 to 1
  33350. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  33351. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  33352. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  33353. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  33354. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  33355. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  33356. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  33357. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  33358. * }
  33359. * Note: if an effect parameter is unset, effect is disabled
  33360. *
  33361. * @param {string} name - The rendering pipeline name
  33362. * @param {object} parameters - An object containing all parameters (see above)
  33363. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33364. * @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)
  33365. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33366. */
  33367. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  33368. var _this = this;
  33369. if (ratio === void 0) { ratio = 1.0; }
  33370. _super.call(this, scene.getEngine(), name);
  33371. // Lens effects can be of the following:
  33372. // - chromatic aberration (slight shift of RGB colors)
  33373. // - blur on the edge of the lens
  33374. // - lens distortion
  33375. // - depth-of-field blur & highlights enhancing
  33376. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  33377. // - grain effect (noise or custom texture)
  33378. // Two additional texture samplers are needed:
  33379. // - depth map (for depth-of-field)
  33380. // - grain texture
  33381. /**
  33382. * The chromatic aberration PostProcess id in the pipeline
  33383. * @type {string}
  33384. */
  33385. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  33386. /**
  33387. * The highlights enhancing PostProcess id in the pipeline
  33388. * @type {string}
  33389. */
  33390. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  33391. /**
  33392. * The depth-of-field PostProcess id in the pipeline
  33393. * @type {string}
  33394. */
  33395. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  33396. this._scene = scene;
  33397. // Fetch texture samplers
  33398. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33399. if (parameters.grain_texture) {
  33400. this._grainTexture = parameters.grain_texture;
  33401. }
  33402. else {
  33403. this._createGrainTexture();
  33404. }
  33405. // save parameters
  33406. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  33407. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  33408. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  33409. this._distortion = parameters.distortion ? parameters.distortion : 0;
  33410. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  33411. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  33412. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  33413. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  33414. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  33415. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  33416. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  33417. // Create effects
  33418. this._createChromaticAberrationPostProcess(ratio);
  33419. this._createHighlightsPostProcess(ratio);
  33420. this._createDepthOfFieldPostProcess(ratio / 4);
  33421. // Set up pipeline
  33422. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  33423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  33424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  33425. if (this._highlightsGain == -1) {
  33426. this._disableEffect(this.HighlightsEnhancingEffect, null);
  33427. }
  33428. // Finish
  33429. scene.postProcessRenderPipelineManager.addPipeline(this);
  33430. if (cameras) {
  33431. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33432. }
  33433. }
  33434. // public methods (self explanatory)
  33435. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  33436. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  33437. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  33438. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  33439. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  33440. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  33441. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  33442. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  33443. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  33444. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  33445. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  33446. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  33447. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  33448. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  33449. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  33450. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  33451. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  33452. this._highlightsGain = amount;
  33453. };
  33454. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  33455. if (this._highlightsGain == -1) {
  33456. this._highlightsGain = 1.0;
  33457. }
  33458. this._highlightsThreshold = amount;
  33459. };
  33460. LensRenderingPipeline.prototype.disableHighlights = function () {
  33461. this._highlightsGain = -1;
  33462. };
  33463. /**
  33464. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  33465. */
  33466. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33467. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33468. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33469. this._chromaticAberrationPostProcess = undefined;
  33470. this._highlightsPostProcess = undefined;
  33471. this._depthOfFieldPostProcess = undefined;
  33472. this._grainTexture.dispose();
  33473. if (disableDepthRender)
  33474. this._scene.disableDepthRenderer();
  33475. };
  33476. // colors shifting and distortion
  33477. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  33478. var _this = this;
  33479. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  33480. [], // samplers
  33481. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33482. this._chromaticAberrationPostProcess.onApply = function (effect) {
  33483. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  33484. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33485. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33486. };
  33487. };
  33488. // highlights enhancing
  33489. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  33490. var _this = this;
  33491. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  33492. [], // samplers
  33493. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33494. this._highlightsPostProcess.onApply = function (effect) {
  33495. effect.setFloat('gain', _this._highlightsGain);
  33496. effect.setFloat('threshold', _this._highlightsThreshold);
  33497. effect.setBool('pentagon', _this._dofPentagon);
  33498. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  33499. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33500. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33501. };
  33502. };
  33503. // colors shifting and distortion
  33504. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  33505. var _this = this;
  33506. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  33507. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  33508. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  33509. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33510. this._depthOfFieldPostProcess.onApply = function (effect) {
  33511. effect.setTexture("depthSampler", _this._depthTexture);
  33512. effect.setTexture("grainSampler", _this._grainTexture);
  33513. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  33514. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  33515. effect.setFloat('grain_amount', _this._grainAmount);
  33516. effect.setBool('blur_noise', _this._blurNoise);
  33517. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33518. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33519. effect.setFloat('distortion', _this._distortion);
  33520. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33521. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33522. effect.setFloat('aperture', _this._dofAperture);
  33523. effect.setFloat('darken', _this._dofDarken);
  33524. effect.setFloat('edge_blur', _this._edgeBlur);
  33525. effect.setBool('highlights', (_this._highlightsGain != -1));
  33526. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33527. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33528. };
  33529. };
  33530. // creates a black and white random noise texture, 512x512
  33531. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33532. var size = 512;
  33533. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33534. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33535. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33536. var context = this._grainTexture.getContext();
  33537. var rand = function (min, max) {
  33538. return Math.random() * (max - min) + min;
  33539. };
  33540. var value;
  33541. for (var x = 0; x < size; x++) {
  33542. for (var y = 0; y < size; y++) {
  33543. value = Math.floor(rand(0.42, 0.58) * 255);
  33544. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33545. context.fillRect(x, y, 1, 1);
  33546. }
  33547. }
  33548. this._grainTexture.update(false);
  33549. };
  33550. return LensRenderingPipeline;
  33551. })(BABYLON.PostProcessRenderPipeline);
  33552. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33553. })(BABYLON || (BABYLON = {}));
  33554. //
  33555. // This post-process allows the modification of rendered colors by using
  33556. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33557. //
  33558. // The object needs to be provided an url to a texture containing the color
  33559. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33560. // Use an image editing software to tweak the LUT to match your needs.
  33561. //
  33562. // For an example of a color LUT, see here:
  33563. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33564. // For explanations on color grading, see here:
  33565. // http://udn.epicgames.com/Three/ColorGrading.html
  33566. //
  33567. var BABYLON;
  33568. (function (BABYLON) {
  33569. var ColorCorrectionPostProcess = (function (_super) {
  33570. __extends(ColorCorrectionPostProcess, _super);
  33571. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33572. var _this = this;
  33573. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33574. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33575. this._colorTableTexture.anisotropicFilteringLevel = 1;
  33576. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33577. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33578. this.onApply = function (effect) {
  33579. effect.setTexture("colorTable", _this._colorTableTexture);
  33580. };
  33581. }
  33582. return ColorCorrectionPostProcess;
  33583. })(BABYLON.PostProcess);
  33584. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  33585. })(BABYLON || (BABYLON = {}));
  33586. var BABYLON;
  33587. (function (BABYLON) {
  33588. var AnaglyphFreeCamera = (function (_super) {
  33589. __extends(AnaglyphFreeCamera, _super);
  33590. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  33591. _super.call(this, name, position, scene);
  33592. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33593. }
  33594. return AnaglyphFreeCamera;
  33595. })(BABYLON.FreeCamera);
  33596. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33597. var AnaglyphArcRotateCamera = (function (_super) {
  33598. __extends(AnaglyphArcRotateCamera, _super);
  33599. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33600. _super.call(this, name, alpha, beta, radius, target, scene);
  33601. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33602. }
  33603. return AnaglyphArcRotateCamera;
  33604. })(BABYLON.ArcRotateCamera);
  33605. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33606. var AnaglyphGamepadCamera = (function (_super) {
  33607. __extends(AnaglyphGamepadCamera, _super);
  33608. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33609. _super.call(this, name, position, scene);
  33610. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33611. }
  33612. return AnaglyphGamepadCamera;
  33613. })(BABYLON.GamepadCamera);
  33614. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33615. var StereoscopicFreeCamera = (function (_super) {
  33616. __extends(StereoscopicFreeCamera, _super);
  33617. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33618. _super.call(this, name, position, scene);
  33619. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33620. }
  33621. return StereoscopicFreeCamera;
  33622. })(BABYLON.FreeCamera);
  33623. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33624. var StereoscopicArcRotateCamera = (function (_super) {
  33625. __extends(StereoscopicArcRotateCamera, _super);
  33626. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33627. _super.call(this, name, alpha, beta, radius, target, scene);
  33628. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33629. }
  33630. return StereoscopicArcRotateCamera;
  33631. })(BABYLON.ArcRotateCamera);
  33632. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33633. var StereoscopicGamepadCamera = (function (_super) {
  33634. __extends(StereoscopicGamepadCamera, _super);
  33635. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33636. _super.call(this, name, position, scene);
  33637. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33638. }
  33639. return StereoscopicGamepadCamera;
  33640. })(BABYLON.GamepadCamera);
  33641. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33642. })(BABYLON || (BABYLON = {}));
  33643. var BABYLON;
  33644. (function (BABYLON) {
  33645. var HDRRenderingPipeline = (function (_super) {
  33646. __extends(HDRRenderingPipeline, _super);
  33647. /**
  33648. * @constructor
  33649. * @param {string} name - The rendering pipeline name
  33650. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33651. * @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)
  33652. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33653. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33654. */
  33655. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33656. var _this = this;
  33657. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33658. _super.call(this, scene.getEngine(), name);
  33659. /**
  33660. * Public members
  33661. */
  33662. // Gaussian Blur
  33663. /**
  33664. * Gaussian blur coefficient
  33665. * @type {number}
  33666. */
  33667. this.gaussCoeff = 0.3;
  33668. /**
  33669. * Gaussian blur mean
  33670. * @type {number}
  33671. */
  33672. this.gaussMean = 1.0;
  33673. /**
  33674. * Gaussian blur standard deviation
  33675. * @type {number}
  33676. */
  33677. this.gaussStandDev = 0.8;
  33678. // HDR
  33679. /**
  33680. * Exposure, controls the overall intensity of the pipeline
  33681. * @type {number}
  33682. */
  33683. this.exposure = 1.0;
  33684. /**
  33685. * Minimum luminance that the post-process can output. Luminance is >= 0
  33686. * @type {number}
  33687. */
  33688. this.minimumLuminance = 1.0;
  33689. /**
  33690. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33691. * @type {number}
  33692. */
  33693. this.maximumLuminance = 1e20;
  33694. /**
  33695. * Increase rate for luminance: eye adaptation speed to dark
  33696. * @type {number}
  33697. */
  33698. this.luminanceIncreaserate = 0.5;
  33699. /**
  33700. * Decrease rate for luminance: eye adaptation speed to bright
  33701. * @type {number}
  33702. */
  33703. this.luminanceDecreaseRate = 0.5;
  33704. // Bright pass
  33705. /**
  33706. * Minimum luminance needed to compute HDR
  33707. * @type {number}
  33708. */
  33709. this.brightThreshold = 0.8;
  33710. this._needUpdate = true;
  33711. this._scene = scene;
  33712. // Bright pass
  33713. this._createBrightPassPostProcess(scene, ratio);
  33714. // Down sample X4
  33715. this._createDownSampleX4PostProcess(scene, ratio);
  33716. // Create gaussian blur post-processes
  33717. this._createGaussianBlurPostProcess(scene, ratio);
  33718. // Texture adder
  33719. this._createTextureAdderPostProcess(scene, ratio);
  33720. // Luminance generator
  33721. this._createLuminanceGeneratorPostProcess(scene);
  33722. // HDR
  33723. this._createHDRPostProcess(scene, ratio);
  33724. // Pass postprocess
  33725. if (originalPostProcess === null) {
  33726. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33727. }
  33728. else {
  33729. this._originalPostProcess = originalPostProcess;
  33730. }
  33731. // Configure pipeline
  33732. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33733. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33734. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33735. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33736. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33737. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33738. var addDownSamplerPostProcess = function (id) {
  33739. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33740. };
  33741. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33742. addDownSamplerPostProcess(i);
  33743. }
  33744. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33745. // Finish
  33746. scene.postProcessRenderPipelineManager.addPipeline(this);
  33747. if (cameras !== null) {
  33748. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33749. }
  33750. this.update();
  33751. }
  33752. /**
  33753. * Tells the pipeline to update its post-processes
  33754. */
  33755. HDRRenderingPipeline.prototype.update = function () {
  33756. this._needUpdate = true;
  33757. };
  33758. /**
  33759. * Returns the current calculated luminance
  33760. */
  33761. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33762. return this._hdrCurrentLuminance;
  33763. };
  33764. /**
  33765. * Returns the currently drawn luminance
  33766. */
  33767. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33768. return this._hdrOutputLuminance;
  33769. };
  33770. /**
  33771. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33772. */
  33773. HDRRenderingPipeline.prototype.dispose = function () {
  33774. this._originalPostProcess = undefined;
  33775. this._brightPassPostProcess = undefined;
  33776. this._downSampleX4PostProcess = undefined;
  33777. this._guassianBlurHPostProcess = undefined;
  33778. this._guassianBlurVPostProcess = undefined;
  33779. this._textureAdderPostProcess = undefined;
  33780. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33781. this._downSamplePostProcesses[i] = undefined;
  33782. }
  33783. this._hdrPostProcess = undefined;
  33784. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33785. };
  33786. /**
  33787. * Creates the HDR post-process and computes the luminance adaptation
  33788. */
  33789. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33790. var _this = this;
  33791. var hdrLastLuminance = 0.0;
  33792. this._hdrOutputLuminance = -1.0;
  33793. this._hdrCurrentLuminance = 1.0;
  33794. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33795. this._hdrPostProcess.onApply = function (effect) {
  33796. if (_this._hdrOutputLuminance < 0.0) {
  33797. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33798. }
  33799. else {
  33800. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33801. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33802. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33803. }
  33804. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33805. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33806. }
  33807. else {
  33808. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33809. }
  33810. }
  33811. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33812. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33813. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33814. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33815. effect.setFloat("exposure", _this.exposure);
  33816. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33817. _this._needUpdate = false;
  33818. };
  33819. };
  33820. /**
  33821. * Texture Adder post-process
  33822. */
  33823. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33824. var _this = this;
  33825. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33826. this._textureAdderPostProcess.onApply = function (effect) {
  33827. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33828. };
  33829. };
  33830. /**
  33831. * Down sample X4 post-process
  33832. */
  33833. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33834. var _this = this;
  33835. var downSampleX4Offsets = new Array(32);
  33836. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33837. this._downSampleX4PostProcess.onApply = function (effect) {
  33838. if (_this._needUpdate) {
  33839. var id = 0;
  33840. for (var i = -2; i < 2; i++) {
  33841. for (var j = -2; j < 2; j++) {
  33842. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33843. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33844. id += 2;
  33845. }
  33846. }
  33847. }
  33848. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33849. };
  33850. };
  33851. /**
  33852. * Bright pass post-process
  33853. */
  33854. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33855. var _this = this;
  33856. var brightOffsets = new Array(8);
  33857. var brightPassCallback = function (effect) {
  33858. if (_this._needUpdate) {
  33859. var sU = (1.0 / _this._brightPassPostProcess.width);
  33860. var sV = (1.0 / _this._brightPassPostProcess.height);
  33861. brightOffsets[0] = -0.5 * sU;
  33862. brightOffsets[1] = 0.5 * sV;
  33863. brightOffsets[2] = 0.5 * sU;
  33864. brightOffsets[3] = 0.5 * sV;
  33865. brightOffsets[4] = -0.5 * sU;
  33866. brightOffsets[5] = -0.5 * sV;
  33867. brightOffsets[6] = 0.5 * sU;
  33868. brightOffsets[7] = -0.5 * sV;
  33869. }
  33870. effect.setArray2("dsOffsets", brightOffsets);
  33871. effect.setFloat("brightThreshold", _this.brightThreshold);
  33872. };
  33873. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33874. this._brightPassPostProcess.onApply = brightPassCallback;
  33875. };
  33876. /**
  33877. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33878. */
  33879. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33880. var _this = this;
  33881. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33882. var luminanceOffsets = new Array(8);
  33883. var downSampleOffsets = new Array(18);
  33884. var halfDestPixelSize;
  33885. this._downSamplePostProcesses = new Array(lumSteps);
  33886. // Utils for luminance
  33887. var luminanceUpdateSourceOffsets = function (width, height) {
  33888. var sU = (1.0 / width);
  33889. var sV = (1.0 / height);
  33890. luminanceOffsets[0] = -0.5 * sU;
  33891. luminanceOffsets[1] = 0.5 * sV;
  33892. luminanceOffsets[2] = 0.5 * sU;
  33893. luminanceOffsets[3] = 0.5 * sV;
  33894. luminanceOffsets[4] = -0.5 * sU;
  33895. luminanceOffsets[5] = -0.5 * sV;
  33896. luminanceOffsets[6] = 0.5 * sU;
  33897. luminanceOffsets[7] = -0.5 * sV;
  33898. };
  33899. var luminanceUpdateDestOffsets = function (width, height) {
  33900. var id = 0;
  33901. for (var x = -1; x < 2; x++) {
  33902. for (var y = -1; y < 2; y++) {
  33903. downSampleOffsets[id] = (x) / width;
  33904. downSampleOffsets[id + 1] = (y) / height;
  33905. id += 2;
  33906. }
  33907. }
  33908. };
  33909. // Luminance callback
  33910. var luminanceCallback = function (effect) {
  33911. if (_this._needUpdate) {
  33912. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33913. }
  33914. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33915. effect.setArray2("lumOffsets", luminanceOffsets);
  33916. };
  33917. // Down sample callbacks
  33918. var downSampleCallback = function (indice) {
  33919. var i = indice;
  33920. return function (effect) {
  33921. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33922. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33923. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33924. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33925. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33926. effect.setArray2("dsOffsets", downSampleOffsets);
  33927. };
  33928. };
  33929. var downSampleAfterRenderCallback = function (effect) {
  33930. // Unpack result
  33931. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33932. 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);
  33933. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33934. };
  33935. // Create luminance post-process
  33936. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33937. 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);
  33938. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33939. // Create down sample post-processes
  33940. for (var i = lumSteps - 2; i >= 0; i--) {
  33941. var length = Math.pow(3, i);
  33942. ratio = { width: length, height: length };
  33943. var defines = "#define DOWN_SAMPLE\n";
  33944. if (i === 0) {
  33945. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33946. }
  33947. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33948. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33949. if (i === 0) {
  33950. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33951. }
  33952. }
  33953. };
  33954. /**
  33955. * Gaussian blur post-processes. Horizontal and Vertical
  33956. */
  33957. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33958. var _this = this;
  33959. var blurOffsetsW = new Array(9);
  33960. var blurOffsetsH = new Array(9);
  33961. var blurWeights = new Array(9);
  33962. var uniforms = ["blurOffsets", "blurWeights"];
  33963. // Utils for gaussian blur
  33964. var calculateBlurOffsets = function (height) {
  33965. var lastOutputDimensions = {
  33966. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33967. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33968. };
  33969. for (var i = 0; i < 9; i++) {
  33970. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33971. if (height) {
  33972. blurOffsetsH[i] = value;
  33973. }
  33974. else {
  33975. blurOffsetsW[i] = value;
  33976. }
  33977. }
  33978. };
  33979. var calculateWeights = function () {
  33980. var x = 0.0;
  33981. for (var i = 0; i < 9; i++) {
  33982. x = (i - 4.0) / 4.0;
  33983. 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));
  33984. }
  33985. };
  33986. // Callback
  33987. var gaussianBlurCallback = function (height) {
  33988. return function (effect) {
  33989. if (_this._needUpdate) {
  33990. calculateWeights();
  33991. calculateBlurOffsets(height);
  33992. }
  33993. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33994. effect.setArray("blurWeights", blurWeights);
  33995. };
  33996. };
  33997. // Create horizontal gaussian blur post-processes
  33998. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33999. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  34000. // Create vertical gaussian blur post-process
  34001. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  34002. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  34003. };
  34004. // Luminance generator
  34005. HDRRenderingPipeline.LUM_STEPS = 6;
  34006. return HDRRenderingPipeline;
  34007. })(BABYLON.PostProcessRenderPipeline);
  34008. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  34009. })(BABYLON || (BABYLON = {}));
  34010. var BABYLON;
  34011. (function (BABYLON) {
  34012. var FaceAdjacencies = (function () {
  34013. function FaceAdjacencies() {
  34014. this.edges = new Array();
  34015. this.edgesConnectedCount = 0;
  34016. }
  34017. return FaceAdjacencies;
  34018. })();
  34019. var EdgesRenderer = (function () {
  34020. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  34021. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  34022. if (epsilon === void 0) { epsilon = 0.95; }
  34023. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  34024. this._linesPositions = new Array();
  34025. this._linesNormals = new Array();
  34026. this._linesIndices = new Array();
  34027. this._buffers = new Array();
  34028. this._checkVerticesInsteadOfIndices = false;
  34029. this._source = source;
  34030. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  34031. this._epsilon = epsilon;
  34032. this._prepareRessources();
  34033. this._generateEdgesLines();
  34034. }
  34035. EdgesRenderer.prototype._prepareRessources = function () {
  34036. if (this._lineShader) {
  34037. return;
  34038. }
  34039. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  34040. attributes: ["position", "normal"],
  34041. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  34042. });
  34043. this._lineShader.disableDepthWrite = true;
  34044. this._lineShader.backFaceCulling = false;
  34045. };
  34046. EdgesRenderer.prototype.dispose = function () {
  34047. this._vb0.dispose();
  34048. this._vb1.dispose();
  34049. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  34050. this._lineShader.dispose();
  34051. };
  34052. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  34053. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  34054. return 0;
  34055. }
  34056. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  34057. return 1;
  34058. }
  34059. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  34060. return 2;
  34061. }
  34062. return -1;
  34063. };
  34064. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  34065. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  34066. return 0;
  34067. }
  34068. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  34069. return 1;
  34070. }
  34071. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  34072. return 2;
  34073. }
  34074. return -1;
  34075. };
  34076. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  34077. var needToCreateLine;
  34078. if (edge === undefined) {
  34079. needToCreateLine = true;
  34080. }
  34081. else {
  34082. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  34083. needToCreateLine = dotProduct < this._epsilon;
  34084. }
  34085. if (needToCreateLine) {
  34086. var offset = this._linesPositions.length / 3;
  34087. var normal = p0.subtract(p1);
  34088. normal.normalize();
  34089. // Positions
  34090. this._linesPositions.push(p0.x);
  34091. this._linesPositions.push(p0.y);
  34092. this._linesPositions.push(p0.z);
  34093. this._linesPositions.push(p0.x);
  34094. this._linesPositions.push(p0.y);
  34095. this._linesPositions.push(p0.z);
  34096. this._linesPositions.push(p1.x);
  34097. this._linesPositions.push(p1.y);
  34098. this._linesPositions.push(p1.z);
  34099. this._linesPositions.push(p1.x);
  34100. this._linesPositions.push(p1.y);
  34101. this._linesPositions.push(p1.z);
  34102. // Normals
  34103. this._linesNormals.push(p1.x);
  34104. this._linesNormals.push(p1.y);
  34105. this._linesNormals.push(p1.z);
  34106. this._linesNormals.push(-1);
  34107. this._linesNormals.push(p1.x);
  34108. this._linesNormals.push(p1.y);
  34109. this._linesNormals.push(p1.z);
  34110. this._linesNormals.push(1);
  34111. this._linesNormals.push(p0.x);
  34112. this._linesNormals.push(p0.y);
  34113. this._linesNormals.push(p0.z);
  34114. this._linesNormals.push(-1);
  34115. this._linesNormals.push(p0.x);
  34116. this._linesNormals.push(p0.y);
  34117. this._linesNormals.push(p0.z);
  34118. this._linesNormals.push(1);
  34119. // Indices
  34120. this._linesIndices.push(offset);
  34121. this._linesIndices.push(offset + 1);
  34122. this._linesIndices.push(offset + 2);
  34123. this._linesIndices.push(offset);
  34124. this._linesIndices.push(offset + 2);
  34125. this._linesIndices.push(offset + 3);
  34126. }
  34127. };
  34128. EdgesRenderer.prototype._generateEdgesLines = function () {
  34129. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34130. var indices = this._source.getIndices();
  34131. // First let's find adjacencies
  34132. var adjacencies = new Array();
  34133. var faceNormals = new Array();
  34134. var index;
  34135. var faceAdjacencies;
  34136. // Prepare faces
  34137. for (index = 0; index < indices.length; index += 3) {
  34138. faceAdjacencies = new FaceAdjacencies();
  34139. var p0Index = indices[index];
  34140. var p1Index = indices[index + 1];
  34141. var p2Index = indices[index + 2];
  34142. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  34143. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  34144. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  34145. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  34146. faceNormal.normalize();
  34147. faceNormals.push(faceNormal);
  34148. adjacencies.push(faceAdjacencies);
  34149. }
  34150. // Scan
  34151. for (index = 0; index < adjacencies.length; index++) {
  34152. faceAdjacencies = adjacencies[index];
  34153. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  34154. var otherFaceAdjacencies = adjacencies[otherIndex];
  34155. if (faceAdjacencies.edgesConnectedCount === 3) {
  34156. break;
  34157. }
  34158. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  34159. continue;
  34160. }
  34161. var otherP0 = indices[otherIndex * 3];
  34162. var otherP1 = indices[otherIndex * 3 + 1];
  34163. var otherP2 = indices[otherIndex * 3 + 2];
  34164. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  34165. var otherEdgeIndex;
  34166. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  34167. continue;
  34168. }
  34169. switch (edgeIndex) {
  34170. case 0:
  34171. if (this._checkVerticesInsteadOfIndices) {
  34172. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34173. }
  34174. else {
  34175. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  34176. }
  34177. break;
  34178. case 1:
  34179. if (this._checkVerticesInsteadOfIndices) {
  34180. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34181. }
  34182. else {
  34183. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  34184. }
  34185. break;
  34186. case 2:
  34187. if (this._checkVerticesInsteadOfIndices) {
  34188. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34189. }
  34190. else {
  34191. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  34192. }
  34193. break;
  34194. }
  34195. if (otherEdgeIndex === -1) {
  34196. continue;
  34197. }
  34198. faceAdjacencies.edges[edgeIndex] = otherIndex;
  34199. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  34200. faceAdjacencies.edgesConnectedCount++;
  34201. otherFaceAdjacencies.edgesConnectedCount++;
  34202. if (faceAdjacencies.edgesConnectedCount === 3) {
  34203. break;
  34204. }
  34205. }
  34206. }
  34207. }
  34208. // Create lines
  34209. for (index = 0; index < adjacencies.length; index++) {
  34210. // 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
  34211. var current = adjacencies[index];
  34212. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  34213. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  34214. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  34215. }
  34216. // Merge into a single mesh
  34217. var engine = this._source.getScene().getEngine();
  34218. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  34219. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  34220. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  34221. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  34222. this._ib = engine.createIndexBuffer(this._linesIndices);
  34223. this._indicesCount = this._linesIndices.length;
  34224. };
  34225. EdgesRenderer.prototype.render = function () {
  34226. if (!this._lineShader.isReady()) {
  34227. return;
  34228. }
  34229. var scene = this._source.getScene();
  34230. var engine = scene.getEngine();
  34231. this._lineShader._preBind();
  34232. // VBOs
  34233. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  34234. scene.resetCachedMaterial();
  34235. this._lineShader.setColor4("color", this._source.edgesColor);
  34236. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  34237. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  34238. this._lineShader.bind(this._source.getWorldMatrix());
  34239. // Draw order
  34240. engine.draw(true, 0, this._indicesCount);
  34241. this._lineShader.unbind();
  34242. engine.setDepthWrite(true);
  34243. };
  34244. return EdgesRenderer;
  34245. })();
  34246. BABYLON.EdgesRenderer = EdgesRenderer;
  34247. })(BABYLON || (BABYLON = {}));
  34248. var BABYLON;
  34249. (function (BABYLON) {
  34250. (function (TonemappingOperator) {
  34251. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  34252. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  34253. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  34254. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  34255. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  34256. var TonemappingOperator = BABYLON.TonemappingOperator;
  34257. ;
  34258. var TonemapPostProcess = (function (_super) {
  34259. __extends(TonemapPostProcess, _super);
  34260. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  34261. var _this = this;
  34262. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34263. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34264. this._operator = operator;
  34265. this._exposureAdjustment = exposureAdjustment;
  34266. var params = ["_ExposureAdjustment"];
  34267. var defines = "#define ";
  34268. if (operator === TonemappingOperator.Hable)
  34269. defines += "HABLE_TONEMAPPING";
  34270. else if (operator === TonemappingOperator.Reinhard)
  34271. defines += "REINHARD_TONEMAPPING";
  34272. else if (operator === TonemappingOperator.HejiDawson)
  34273. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  34274. else if (operator === TonemappingOperator.Photographic)
  34275. defines += "PHOTOGRAPHIC_TONEMAPPING";
  34276. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  34277. this.onApply = function (effect) {
  34278. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  34279. };
  34280. }
  34281. return TonemapPostProcess;
  34282. })(BABYLON.PostProcess);
  34283. BABYLON.TonemapPostProcess = TonemapPostProcess;
  34284. })(BABYLON || (BABYLON = {}));
  34285. var BABYLON;
  34286. (function (BABYLON) {
  34287. var DefaultLoadingScreen = (function () {
  34288. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34289. var _this = this;
  34290. if (_loadingText === void 0) { _loadingText = ""; }
  34291. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34292. this._renderingCanvas = _renderingCanvas;
  34293. this._loadingText = _loadingText;
  34294. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34295. // Resize
  34296. this._resizeLoadingUI = function () {
  34297. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34298. _this._loadingDiv.style.position = "absolute";
  34299. _this._loadingDiv.style.left = canvasRect.left + "px";
  34300. _this._loadingDiv.style.top = canvasRect.top + "px";
  34301. _this._loadingDiv.style.width = canvasRect.width + "px";
  34302. _this._loadingDiv.style.height = canvasRect.height + "px";
  34303. };
  34304. }
  34305. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34306. var _this = this;
  34307. this._loadingDiv = document.createElement("div");
  34308. this._loadingDiv.style.opacity = "0";
  34309. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34310. // Loading text
  34311. this._loadingTextDiv = document.createElement("div");
  34312. this._loadingTextDiv.style.position = "absolute";
  34313. this._loadingTextDiv.style.left = "0";
  34314. this._loadingTextDiv.style.top = "50%";
  34315. this._loadingTextDiv.style.marginTop = "80px";
  34316. this._loadingTextDiv.style.width = "100%";
  34317. this._loadingTextDiv.style.height = "20px";
  34318. this._loadingTextDiv.style.fontFamily = "Arial";
  34319. this._loadingTextDiv.style.fontSize = "14px";
  34320. this._loadingTextDiv.style.color = "white";
  34321. this._loadingTextDiv.style.textAlign = "center";
  34322. this._loadingTextDiv.innerHTML = "Loading";
  34323. this._loadingDiv.appendChild(this._loadingTextDiv);
  34324. //set the predefined text
  34325. this._loadingTextDiv.innerHTML = this._loadingText;
  34326. // Loading img
  34327. var imgBack = new Image();
  34328. 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==";
  34329. imgBack.style.position = "absolute";
  34330. imgBack.style.left = "50%";
  34331. imgBack.style.top = "50%";
  34332. imgBack.style.marginLeft = "-50px";
  34333. imgBack.style.marginTop = "-50px";
  34334. imgBack.style.transition = "transform 1.0s ease";
  34335. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34336. var deg = 360;
  34337. var onTransitionEnd = function () {
  34338. deg += 360;
  34339. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34340. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34341. };
  34342. imgBack.addEventListener("transitionend", onTransitionEnd);
  34343. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34344. this._loadingDiv.appendChild(imgBack);
  34345. // front image
  34346. var imgFront = new Image();
  34347. 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=";
  34348. imgFront.style.position = "absolute";
  34349. imgFront.style.left = "50%";
  34350. imgFront.style.top = "50%";
  34351. imgFront.style.marginLeft = "-50px";
  34352. imgFront.style.marginTop = "-50px";
  34353. this._loadingDiv.appendChild(imgFront);
  34354. this._resizeLoadingUI();
  34355. window.addEventListener("resize", this._resizeLoadingUI);
  34356. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34357. document.body.appendChild(this._loadingDiv);
  34358. setTimeout(function () {
  34359. _this._loadingDiv.style.opacity = "1";
  34360. imgBack.style.transform = "rotateZ(360deg)";
  34361. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34362. }, 0);
  34363. };
  34364. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34365. var _this = this;
  34366. if (!this._loadingDiv) {
  34367. return;
  34368. }
  34369. var onTransitionEnd = function () {
  34370. if (!_this._loadingDiv) {
  34371. return;
  34372. }
  34373. document.body.removeChild(_this._loadingDiv);
  34374. window.removeEventListener("resize", _this._resizeLoadingUI);
  34375. _this._loadingDiv = null;
  34376. };
  34377. this._loadingDiv.style.opacity = "0";
  34378. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34379. };
  34380. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34381. set: function (text) {
  34382. this._loadingText = text;
  34383. if (this._loadingTextDiv) {
  34384. this._loadingTextDiv.innerHTML = this._loadingText;
  34385. }
  34386. },
  34387. enumerable: true,
  34388. configurable: true
  34389. });
  34390. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34391. get: function () {
  34392. return this._loadingDivBackgroundColor;
  34393. },
  34394. set: function (color) {
  34395. this._loadingDivBackgroundColor = color;
  34396. if (!this._loadingDiv) {
  34397. return;
  34398. }
  34399. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34400. },
  34401. enumerable: true,
  34402. configurable: true
  34403. });
  34404. return DefaultLoadingScreen;
  34405. })();
  34406. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34407. })(BABYLON || (BABYLON = {}));
  34408. var BABYLON;
  34409. (function (BABYLON) {
  34410. var maxSimultaneousLights = 4;
  34411. var PBRMaterialDefines = (function () {
  34412. function PBRMaterialDefines() {
  34413. this.ALBEDO = false;
  34414. this.CLIPPLANE = false;
  34415. this.ALPHATEST = false;
  34416. this.FOG = false;
  34417. this.NORMAL = false;
  34418. this.UV1 = false;
  34419. this.UV2 = false;
  34420. this.VERTEXCOLOR = false;
  34421. this.VERTEXALPHA = false;
  34422. this.BONES = false;
  34423. this.BONES4 = false;
  34424. this.BonesPerMesh = 0;
  34425. this.INSTANCES = false;
  34426. this.POINTSIZE = false;
  34427. this._keys = Object.keys(this);
  34428. }
  34429. PBRMaterialDefines.prototype.isEqual = function (other) {
  34430. for (var index = 0; index < this._keys.length; index++) {
  34431. var prop = this._keys[index];
  34432. if (this[prop] !== other[prop]) {
  34433. return false;
  34434. }
  34435. }
  34436. return true;
  34437. };
  34438. PBRMaterialDefines.prototype.cloneTo = function (other) {
  34439. for (var index = 0; index < this._keys.length; index++) {
  34440. var prop = this._keys[index];
  34441. other[prop] = this[prop];
  34442. }
  34443. };
  34444. PBRMaterialDefines.prototype.reset = function () {
  34445. for (var index = 0; index < this._keys.length; index++) {
  34446. var prop = this._keys[index];
  34447. if (prop === "BonesPerMesh") {
  34448. this[prop] = 0;
  34449. continue;
  34450. }
  34451. this[prop] = false;
  34452. }
  34453. };
  34454. PBRMaterialDefines.prototype.toString = function () {
  34455. var result = "";
  34456. for (var index = 0; index < this._keys.length; index++) {
  34457. var prop = this._keys[index];
  34458. if (prop === "BonesPerMesh" && this[prop] > 0) {
  34459. result += "#define BonesPerMesh " + this[prop] + "\n";
  34460. continue;
  34461. }
  34462. if (this[prop]) {
  34463. result += "#define " + prop + "\n";
  34464. }
  34465. }
  34466. return result;
  34467. };
  34468. return PBRMaterialDefines;
  34469. })();
  34470. var PBRMaterial = (function (_super) {
  34471. __extends(PBRMaterial, _super);
  34472. function PBRMaterial(name, scene) {
  34473. _super.call(this, name, scene);
  34474. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34475. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34476. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34477. this._scaledDiffuse = new BABYLON.Color3();
  34478. this._scaledSpecular = new BABYLON.Color3();
  34479. this._defines = new PBRMaterialDefines();
  34480. this._cachedDefines = new PBRMaterialDefines();
  34481. this._cachedDefines.BonesPerMesh = -1;
  34482. }
  34483. PBRMaterial.prototype.needAlphaBlending = function () {
  34484. return this.alpha < 1.0;
  34485. };
  34486. PBRMaterial.prototype.needAlphaTesting = function () {
  34487. return false;
  34488. };
  34489. PBRMaterial.prototype.getAlphaTestTexture = function () {
  34490. return null;
  34491. };
  34492. // Methods
  34493. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  34494. if (this.checkReadyOnlyOnce) {
  34495. if (this._wasPreviouslyReady) {
  34496. return true;
  34497. }
  34498. }
  34499. var scene = this.getScene();
  34500. if (!this.checkReadyOnEveryCall) {
  34501. if (this._renderId === scene.getRenderId()) {
  34502. return true;
  34503. }
  34504. }
  34505. var engine = scene.getEngine();
  34506. var needNormals = false;
  34507. var needUVs = false;
  34508. this._defines.reset();
  34509. // Textures
  34510. if (scene.texturesEnabled) {
  34511. }
  34512. // Effect
  34513. if (scene.clipPlane) {
  34514. this._defines.CLIPPLANE = true;
  34515. }
  34516. if (engine.getAlphaTesting()) {
  34517. this._defines.ALPHATEST = true;
  34518. }
  34519. // Point size
  34520. if (this.pointsCloud || scene.forcePointsCloud) {
  34521. this._defines.POINTSIZE = true;
  34522. }
  34523. // Fog
  34524. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34525. this._defines.FOG = true;
  34526. }
  34527. // Lights
  34528. // Attribs
  34529. if (mesh) {
  34530. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34531. this._defines.NORMAL = true;
  34532. }
  34533. if (needUVs) {
  34534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34535. this._defines.UV1 = true;
  34536. }
  34537. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34538. this._defines.UV2 = true;
  34539. }
  34540. }
  34541. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34542. this._defines.VERTEXCOLOR = true;
  34543. if (mesh.hasVertexAlpha) {
  34544. this._defines.VERTEXALPHA = true;
  34545. }
  34546. }
  34547. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34548. this._defines.BONES = true;
  34549. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  34550. this._defines.BONES4 = true;
  34551. }
  34552. // Instances
  34553. if (useInstances) {
  34554. this._defines.INSTANCES = true;
  34555. }
  34556. }
  34557. // Get correct effect
  34558. if (!this._defines.isEqual(this._cachedDefines)) {
  34559. this._defines.cloneTo(this._cachedDefines);
  34560. scene.resetCachedMaterial();
  34561. // Fallbacks
  34562. var fallbacks = new BABYLON.EffectFallbacks();
  34563. if (this._defines.FOG) {
  34564. fallbacks.addFallback(1, "FOG");
  34565. }
  34566. if (this._defines.BONES4) {
  34567. fallbacks.addFallback(0, "BONES4");
  34568. }
  34569. //Attributes
  34570. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34571. if (this._defines.NORMAL) {
  34572. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34573. }
  34574. if (this._defines.UV1) {
  34575. attribs.push(BABYLON.VertexBuffer.UVKind);
  34576. }
  34577. if (this._defines.UV2) {
  34578. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34579. }
  34580. if (this._defines.VERTEXCOLOR) {
  34581. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34582. }
  34583. if (this._defines.BONES) {
  34584. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34585. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34586. }
  34587. if (this._defines.INSTANCES) {
  34588. attribs.push("world0");
  34589. attribs.push("world1");
  34590. attribs.push("world2");
  34591. attribs.push("world3");
  34592. }
  34593. // Legacy browser patch
  34594. var join = this._defines.toString();
  34595. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  34596. "vFogInfos", "vFogColor", "pointSize",
  34597. "mBones",
  34598. "vClipPlane",
  34599. ], [], join, fallbacks, this.onCompiled, this.onError);
  34600. }
  34601. if (!this._effect.isReady()) {
  34602. return false;
  34603. }
  34604. this._renderId = scene.getRenderId();
  34605. this._wasPreviouslyReady = true;
  34606. return true;
  34607. };
  34608. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34609. this._effect.setMatrix("world", world);
  34610. };
  34611. PBRMaterial.prototype.bind = function (world, mesh) {
  34612. var scene = this.getScene();
  34613. // Matrices
  34614. this.bindOnlyWorldMatrix(world);
  34615. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34616. // Bones
  34617. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34618. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34619. }
  34620. if (scene.getCachedMaterial() !== this) {
  34621. // Clip plane
  34622. if (scene.clipPlane) {
  34623. var clipPlane = scene.clipPlane;
  34624. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34625. }
  34626. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  34627. }
  34628. // Point size
  34629. if (this.pointsCloud) {
  34630. this._effect.setFloat("pointSize", this.pointSize);
  34631. }
  34632. // Colors
  34633. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  34634. // View
  34635. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34636. this._effect.setMatrix("view", scene.getViewMatrix());
  34637. }
  34638. // Fog
  34639. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34640. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34641. this._effect.setColor3("vFogColor", scene.fogColor);
  34642. }
  34643. _super.prototype.bind.call(this, world, mesh);
  34644. };
  34645. PBRMaterial.prototype.getAnimatables = function () {
  34646. var results = [];
  34647. return results;
  34648. };
  34649. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  34650. _super.prototype.dispose.call(this, forceDisposeEffect);
  34651. };
  34652. PBRMaterial.prototype.clone = function (name) {
  34653. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  34654. // Base material
  34655. this.copyTo(newPBRMaterial);
  34656. // PBRMaterial material
  34657. newPBRMaterial.albedoColor = this.albedoColor.clone();
  34658. return newPBRMaterial;
  34659. };
  34660. return PBRMaterial;
  34661. })(BABYLON.Material);
  34662. BABYLON.PBRMaterial = PBRMaterial;
  34663. })(BABYLON || (BABYLON = {}));
  34664. var BABYLON;
  34665. (function (BABYLON) {
  34666. var ReflectionProbe = (function () {
  34667. //http://localhost:61437/Playground/index%20-%20debug.html#KA93U#7
  34668. function ReflectionProbe(name, size, scene, generateMipMaps) {
  34669. var _this = this;
  34670. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34671. this.name = name;
  34672. this._viewMatrix = BABYLON.Matrix.Identity();
  34673. this._target = BABYLON.Vector3.Zero();
  34674. this._add = BABYLON.Vector3.Zero();
  34675. this.position = BABYLON.Vector3.Zero();
  34676. this._scene = scene;
  34677. this._scene.reflectionProbes.push(this);
  34678. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  34679. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  34680. switch (faceIndex) {
  34681. case 0:
  34682. _this._add.copyFromFloats(1, 0, 0);
  34683. break;
  34684. case 1:
  34685. _this._add.copyFromFloats(-1, 0, 0);
  34686. break;
  34687. case 2:
  34688. _this._add.copyFromFloats(0, -1, 0);
  34689. break;
  34690. case 3:
  34691. _this._add.copyFromFloats(0, 1, 0);
  34692. break;
  34693. case 4:
  34694. _this._add.copyFromFloats(0, 0, 1);
  34695. break;
  34696. case 5:
  34697. _this._add.copyFromFloats(0, 0, -1);
  34698. break;
  34699. }
  34700. if (_this._attachedMesh) {
  34701. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  34702. }
  34703. _this.position.addToRef(_this._add, _this._target);
  34704. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  34705. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  34706. };
  34707. this._renderTargetTexture.onAfterUnbind = function () {
  34708. scene.updateTransformMatrix(true);
  34709. };
  34710. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  34711. }
  34712. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  34713. get: function () {
  34714. return this._renderTargetTexture.refreshRate;
  34715. },
  34716. set: function (value) {
  34717. this._renderTargetTexture.refreshRate = value;
  34718. },
  34719. enumerable: true,
  34720. configurable: true
  34721. });
  34722. ReflectionProbe.prototype.getScene = function () {
  34723. return this._scene;
  34724. };
  34725. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  34726. get: function () {
  34727. return this._renderTargetTexture;
  34728. },
  34729. enumerable: true,
  34730. configurable: true
  34731. });
  34732. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  34733. get: function () {
  34734. return this._renderTargetTexture.renderList;
  34735. },
  34736. enumerable: true,
  34737. configurable: true
  34738. });
  34739. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  34740. this._attachedMesh = mesh;
  34741. };
  34742. ReflectionProbe.prototype.dispose = function () {
  34743. var index = this._scene.reflectionProbes.indexOf(this);
  34744. if (index !== -1) {
  34745. // Remove from the scene if found
  34746. this._scene.reflectionProbes.splice(index, 1);
  34747. }
  34748. };
  34749. return ReflectionProbe;
  34750. })();
  34751. BABYLON.ReflectionProbe = ReflectionProbe;
  34752. })(BABYLON || (BABYLON = {}));
  34753. 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#ifdef INVERTCUBICMAP\r\n\t\tcoords.y = 1.0 - coords.y;\r\n#endif\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 += lightmapColor;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcolor.rgb *= lightmapColor;\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}","pbrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\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#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\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\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), 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}","pbrVertexShader":"#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#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 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\nvoid main(void) {\r\n\tmat4 finalWorld;\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\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// 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}","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}"};
  34754. 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.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[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=e.subMeshes,r=i.length;if(!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;r>s;s++){var l=i[s];r>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){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,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&&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=i.Zero();return i.RotationAxisToRef(t,o,n),n},i.RotationAxisToRef=function(t,i,o){var n=Math.sin(-i),r=Math.cos(-i),s=1-r;t.normalize(),o.m[0]=t.x*t.x*s+r,o.m[1]=t.x*t.y*s-t.z*n,o.m[2]=t.x*t.z*s+t.y*n,o.m[3]=0,o.m[4]=t.y*t.x*s+t.z*n,o.m[5]=t.y*t.y*s+r,o.m[6]=t.y*t.z*s-t.x*n,o.m[7]=0,o.m[8]=t.z*t.x*s-t.y*n,o.m[9]=t.z*t.y*s+t.x*n,o.m[10]=t.z*t.z*s+r,o.m[11]=0,o.m[15]=1},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={}));";
  34755. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  34756. module.exports = BABYLON;
  34757. };