babylon.max.js 1.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225
  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.compensateDistorsion = 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. if (Array.isArray(options)) {
  16112. shape = options;
  16113. radius = radiusOrScene || 1;
  16114. tessellation = tessellation || 64;
  16115. }
  16116. else {
  16117. scene = radiusOrScene;
  16118. shape = options.shape;
  16119. radius = options.radius || 1;
  16120. tessellation = options.tessellation || 64;
  16121. updatable = options.updatable;
  16122. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  16123. }
  16124. var pi2 = Math.PI * 2;
  16125. var shapeLathe = new Array();
  16126. // first rotatable point
  16127. var i = 0;
  16128. while (shape[i].x === 0) {
  16129. i++;
  16130. }
  16131. var pt = shape[i];
  16132. for (i = 0; i < shape.length; i++) {
  16133. shapeLathe.push(shape[i].subtract(pt));
  16134. }
  16135. // circle path
  16136. var step = pi2 / tessellation;
  16137. var rotated;
  16138. var path = new Array();
  16139. ;
  16140. for (i = 0; i < tessellation; i++) {
  16141. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16142. path.push(rotated);
  16143. }
  16144. path.push(path[0]);
  16145. // extrusion
  16146. var scaleFunction = function () { return 1; };
  16147. var rotateFunction = function () { return 0; };
  16148. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  16149. return lathe;
  16150. };
  16151. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  16152. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16153. if (typeof options === 'number') {
  16154. var size = options;
  16155. options = {
  16156. size: size,
  16157. width: size,
  16158. height: size,
  16159. sideOrientation: sideOrientation
  16160. };
  16161. }
  16162. var plane = new Mesh(name, scene);
  16163. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16164. vertexData.applyToMesh(plane, updatable || options.updatable);
  16165. return plane;
  16166. };
  16167. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  16168. if (heightOrScene instanceof BABYLON.Scene) {
  16169. scene = heightOrScene;
  16170. updatable = options.updatable;
  16171. }
  16172. else {
  16173. var width = options;
  16174. options = {
  16175. width: width,
  16176. height: heightOrScene,
  16177. subdivisions: subdivisions
  16178. };
  16179. }
  16180. var ground = new BABYLON.GroundMesh(name, scene);
  16181. ground._setReady(false);
  16182. ground._subdivisions = options.subdivisions || 1;
  16183. var vertexData = BABYLON.VertexData.CreateGround(options);
  16184. vertexData.applyToMesh(ground, updatable || options.updatable);
  16185. ground._setReady(true);
  16186. return ground;
  16187. };
  16188. Mesh.CreateTiledGround = function (name, options, zminOrScene, xmax, zmax, subdivisions, precision, scene, updatable) {
  16189. var xmin;
  16190. var zmin;
  16191. if (typeof options === 'number') {
  16192. xmin = options || -1;
  16193. zmin = zminOrScene || -1;
  16194. xmax = xmax || 1;
  16195. zmax = zmax || 1;
  16196. subdivisions = subdivisions || { w: 6, h: 6 };
  16197. precision = precision || { w: 2, h: 2 };
  16198. }
  16199. else {
  16200. scene = zminOrScene;
  16201. xmin = options.xmin || -1;
  16202. zmin = options.zmin || -1;
  16203. xmax = options.xmax || 1;
  16204. zmax = options.zmax || 1;
  16205. subdivisions = options.subdivisions || { w: 6, h: 6 };
  16206. precision = options.precision || { w: 2, h: 2 };
  16207. }
  16208. var tiledGround = new Mesh(name, scene);
  16209. var vertexData = BABYLON.VertexData.CreateTiledGround({ xmin: xmin, zmin: zmin, xmax: xmax, zmax: zmax, subdivisions: subdivisions, precision: precision });
  16210. vertexData.applyToMesh(tiledGround, updatable);
  16211. return tiledGround;
  16212. };
  16213. Mesh.CreateGroundFromHeightMap = function (name, url, widthOrOptions, heightorScene, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16214. var width;
  16215. var height;
  16216. if (typeof widthOrOptions === "number") {
  16217. width = widthOrOptions;
  16218. height = heightorScene;
  16219. }
  16220. else {
  16221. width = widthOrOptions.width || 10;
  16222. height = widthOrOptions.height || 10;
  16223. subdivisions = widthOrOptions.subdivisions || 1;
  16224. minHeight = widthOrOptions.minHeight;
  16225. maxHeight = widthOrOptions.maxHeight || 10;
  16226. updatable = widthOrOptions.updatable;
  16227. onReady = widthOrOptions.onReady;
  16228. scene = heightorScene;
  16229. }
  16230. var ground = new BABYLON.GroundMesh(name, scene);
  16231. ground._subdivisions = subdivisions;
  16232. ground._setReady(false);
  16233. var onload = function (img) {
  16234. // Getting height map data
  16235. var canvas = document.createElement("canvas");
  16236. var context = canvas.getContext("2d");
  16237. var bufferWidth = img.width;
  16238. var bufferHeight = img.height;
  16239. canvas.width = bufferWidth;
  16240. canvas.height = bufferHeight;
  16241. context.drawImage(img, 0, 0);
  16242. // Create VertexData from map data
  16243. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16244. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16245. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16246. width: width, height: height,
  16247. subdivisions: subdivisions,
  16248. minHeight: minHeight, maxHeight: maxHeight,
  16249. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16250. });
  16251. vertexData.applyToMesh(ground, updatable);
  16252. ground._setReady(true);
  16253. //execute ready callback, if set
  16254. if (onReady) {
  16255. onReady(ground);
  16256. }
  16257. };
  16258. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16259. return ground;
  16260. };
  16261. Mesh.CreateTube = function (name, options, radiusOrScene, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16262. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16263. if (instance === void 0) { instance = null; }
  16264. var path;
  16265. var radius;
  16266. if (Array.isArray(options)) {
  16267. path = options;
  16268. radius = radiusOrScene;
  16269. }
  16270. else {
  16271. scene = radiusOrScene;
  16272. path = options.path;
  16273. radius = options.radius || 1;
  16274. tessellation = options.tessellation || 64;
  16275. radiusFunction = options.radiusFunction;
  16276. cap = options.cap || Mesh.NO_CAP,
  16277. updatable = options.updatable;
  16278. sideOrientation = options.sideOrientation || Mesh.DEFAULTSIDE,
  16279. instance = options.instance;
  16280. }
  16281. // tube geometry
  16282. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  16283. var tangents = path3D.getTangents();
  16284. var normals = path3D.getNormals();
  16285. var distances = path3D.getDistances();
  16286. var pi2 = Math.PI * 2;
  16287. var step = pi2 / tessellation;
  16288. var returnRadius = function (i, distance) { return radius; };
  16289. var radiusFunctionFinal = radiusFunction || returnRadius;
  16290. var circlePath;
  16291. var rad;
  16292. var normal;
  16293. var rotated;
  16294. var rotationMatrix = BABYLON.Matrix.Zero();
  16295. var index = (cap === Mesh._NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  16296. for (var i = 0; i < path.length; i++) {
  16297. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16298. circlePath = Array(); // current circle array
  16299. normal = normals[i]; // current normal
  16300. for (var t = 0; t < tessellation; t++) {
  16301. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16302. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16303. circlePath.push(rotated);
  16304. }
  16305. circlePaths[index] = circlePath;
  16306. index++;
  16307. }
  16308. // cap
  16309. var capPath = function (nbPoints, pathIndex) {
  16310. var pointCap = Array();
  16311. for (var i = 0; i < nbPoints; i++) {
  16312. pointCap.push(path[pathIndex]);
  16313. }
  16314. return pointCap;
  16315. };
  16316. switch (cap) {
  16317. case Mesh.NO_CAP:
  16318. break;
  16319. case Mesh.CAP_START:
  16320. circlePaths[0] = capPath(tessellation, 0);
  16321. circlePaths[1] = circlePaths[2].slice(0);
  16322. break;
  16323. case Mesh.CAP_END:
  16324. circlePaths[index] = circlePaths[index - 1].slice(0);
  16325. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16326. break;
  16327. case Mesh.CAP_ALL:
  16328. circlePaths[0] = capPath(tessellation, 0);
  16329. circlePaths[1] = circlePaths[2].slice(0);
  16330. circlePaths[index] = circlePaths[index - 1].slice(0);
  16331. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16332. break;
  16333. default:
  16334. break;
  16335. }
  16336. return circlePaths;
  16337. };
  16338. var path3D;
  16339. var pathArray;
  16340. if (instance) {
  16341. path3D = (instance.path3D).update(path);
  16342. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap);
  16343. instance = Mesh.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16344. instance.path3D = path3D;
  16345. instance.pathArray = pathArray;
  16346. return instance;
  16347. }
  16348. // tube creation
  16349. path3D = new BABYLON.Path3D(path);
  16350. var newPathArray = new Array();
  16351. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16352. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  16353. var tube = Mesh.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16354. tube.pathArray = pathArray;
  16355. tube.path3D = path3D;
  16356. tube.tessellation = tessellation;
  16357. tube.cap = cap;
  16358. return tube;
  16359. };
  16360. Mesh.CreateDecal = function (name, sourceMesh, positionOrOptions, normal, size, angle) {
  16361. if (angle === void 0) { angle = 0; }
  16362. var indices = sourceMesh.getIndices();
  16363. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16364. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16365. var position;
  16366. if (positionOrOptions instanceof BABYLON.Vector3) {
  16367. position = positionOrOptions;
  16368. }
  16369. else {
  16370. position = positionOrOptions.position || BABYLON.Vector3.Zero();
  16371. normal = positionOrOptions.normal || BABYLON.Vector3.Up();
  16372. size = positionOrOptions.size || new BABYLON.Vector3(1, 1, 1);
  16373. angle = positionOrOptions.angle;
  16374. }
  16375. // Getting correct rotation
  16376. if (!normal) {
  16377. var target = new BABYLON.Vector3(0, 0, 1);
  16378. var camera = sourceMesh.getScene().activeCamera;
  16379. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16380. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16381. }
  16382. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16383. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16384. var pitch = Math.atan2(normal.y, len);
  16385. // Matrix
  16386. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16387. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16388. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16389. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16390. var vertexData = new BABYLON.VertexData();
  16391. vertexData.indices = [];
  16392. vertexData.positions = [];
  16393. vertexData.normals = [];
  16394. vertexData.uvs = [];
  16395. var currentVertexDataIndex = 0;
  16396. var extractDecalVector3 = function (indexId) {
  16397. var vertexId = indices[indexId];
  16398. var result = new BABYLON.PositionNormalVertex();
  16399. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16400. // Send vector to decal local world
  16401. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16402. // Get normal
  16403. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16404. return result;
  16405. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16406. var clip = function (vertices, axis) {
  16407. if (vertices.length === 0) {
  16408. return vertices;
  16409. }
  16410. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16411. var clipVertices = function (v0, v1) {
  16412. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16413. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16414. };
  16415. var result = new Array();
  16416. for (var index = 0; index < vertices.length; index += 3) {
  16417. var v1Out;
  16418. var v2Out;
  16419. var v3Out;
  16420. var total = 0;
  16421. var nV1, nV2, nV3, nV4;
  16422. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16423. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16424. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16425. v1Out = d1 > 0;
  16426. v2Out = d2 > 0;
  16427. v3Out = d3 > 0;
  16428. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16429. switch (total) {
  16430. case 0:
  16431. result.push(vertices[index]);
  16432. result.push(vertices[index + 1]);
  16433. result.push(vertices[index + 2]);
  16434. break;
  16435. case 1:
  16436. if (v1Out) {
  16437. nV1 = vertices[index + 1];
  16438. nV2 = vertices[index + 2];
  16439. nV3 = clipVertices(vertices[index], nV1);
  16440. nV4 = clipVertices(vertices[index], nV2);
  16441. }
  16442. if (v2Out) {
  16443. nV1 = vertices[index];
  16444. nV2 = vertices[index + 2];
  16445. nV3 = clipVertices(vertices[index + 1], nV1);
  16446. nV4 = clipVertices(vertices[index + 1], nV2);
  16447. result.push(nV3);
  16448. result.push(nV2.clone());
  16449. result.push(nV1.clone());
  16450. result.push(nV2.clone());
  16451. result.push(nV3.clone());
  16452. result.push(nV4);
  16453. break;
  16454. }
  16455. if (v3Out) {
  16456. nV1 = vertices[index];
  16457. nV2 = vertices[index + 1];
  16458. nV3 = clipVertices(vertices[index + 2], nV1);
  16459. nV4 = clipVertices(vertices[index + 2], nV2);
  16460. }
  16461. result.push(nV1.clone());
  16462. result.push(nV2.clone());
  16463. result.push(nV3);
  16464. result.push(nV4);
  16465. result.push(nV3.clone());
  16466. result.push(nV2.clone());
  16467. break;
  16468. case 2:
  16469. if (!v1Out) {
  16470. nV1 = vertices[index].clone();
  16471. nV2 = clipVertices(nV1, vertices[index + 1]);
  16472. nV3 = clipVertices(nV1, vertices[index + 2]);
  16473. result.push(nV1);
  16474. result.push(nV2);
  16475. result.push(nV3);
  16476. }
  16477. if (!v2Out) {
  16478. nV1 = vertices[index + 1].clone();
  16479. nV2 = clipVertices(nV1, vertices[index + 2]);
  16480. nV3 = clipVertices(nV1, vertices[index]);
  16481. result.push(nV1);
  16482. result.push(nV2);
  16483. result.push(nV3);
  16484. }
  16485. if (!v3Out) {
  16486. nV1 = vertices[index + 2].clone();
  16487. nV2 = clipVertices(nV1, vertices[index]);
  16488. nV3 = clipVertices(nV1, vertices[index + 1]);
  16489. result.push(nV1);
  16490. result.push(nV2);
  16491. result.push(nV3);
  16492. }
  16493. break;
  16494. case 3:
  16495. break;
  16496. }
  16497. }
  16498. return result;
  16499. };
  16500. for (var index = 0; index < indices.length; index += 3) {
  16501. var faceVertices = new Array();
  16502. faceVertices.push(extractDecalVector3(index));
  16503. faceVertices.push(extractDecalVector3(index + 1));
  16504. faceVertices.push(extractDecalVector3(index + 2));
  16505. // Clip
  16506. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16507. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16508. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16509. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16510. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16511. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16512. if (faceVertices.length === 0) {
  16513. continue;
  16514. }
  16515. // Add UVs and get back to world
  16516. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16517. var vertex = faceVertices[vIndex];
  16518. vertexData.indices.push(currentVertexDataIndex);
  16519. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16520. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16521. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16522. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16523. currentVertexDataIndex++;
  16524. }
  16525. }
  16526. // Return mesh
  16527. var decal = new Mesh(name, sourceMesh.getScene());
  16528. vertexData.applyToMesh(decal);
  16529. decal.position = position.clone();
  16530. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16531. return decal;
  16532. };
  16533. // Skeletons
  16534. /**
  16535. * Update the vertex buffers by applying transformation from the bones
  16536. * @param {skeleton} skeleton to apply
  16537. */
  16538. Mesh.prototype.applySkeleton = function (skeleton) {
  16539. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16540. return this;
  16541. }
  16542. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16543. return this;
  16544. }
  16545. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16546. return this;
  16547. }
  16548. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16549. return this;
  16550. }
  16551. var source;
  16552. if (!this._sourcePositions) {
  16553. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16554. this._sourcePositions = new Float32Array(source);
  16555. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16556. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16557. }
  16558. }
  16559. if (!this._sourceNormals) {
  16560. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16561. this._sourceNormals = new Float32Array(source);
  16562. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16563. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16564. }
  16565. }
  16566. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16567. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16568. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16569. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16570. var skeletonMatrices = skeleton.getTransformMatrices();
  16571. var tempVector3 = BABYLON.Vector3.Zero();
  16572. var finalMatrix = new BABYLON.Matrix();
  16573. var tempMatrix = new BABYLON.Matrix();
  16574. for (var index = 0; index < positionsData.length; index += 3) {
  16575. var index4 = (index / 3) * 4;
  16576. var matricesWeight0 = matricesWeightsData[index4];
  16577. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16578. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16579. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16580. if (matricesWeight0 > 0) {
  16581. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16582. finalMatrix.addToSelf(tempMatrix);
  16583. }
  16584. if (matricesWeight1 > 0) {
  16585. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16586. finalMatrix.addToSelf(tempMatrix);
  16587. }
  16588. if (matricesWeight2 > 0) {
  16589. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16590. finalMatrix.addToSelf(tempMatrix);
  16591. }
  16592. if (matricesWeight3 > 0) {
  16593. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16594. finalMatrix.addToSelf(tempMatrix);
  16595. }
  16596. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16597. tempVector3.toArray(positionsData, index);
  16598. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16599. tempVector3.toArray(normalsData, index);
  16600. finalMatrix.reset();
  16601. }
  16602. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16603. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16604. return this;
  16605. };
  16606. // Tools
  16607. Mesh.MinMax = function (meshes) {
  16608. var minVector = null;
  16609. var maxVector = null;
  16610. for (var i in meshes) {
  16611. var mesh = meshes[i];
  16612. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16613. if (!minVector) {
  16614. minVector = boundingBox.minimumWorld;
  16615. maxVector = boundingBox.maximumWorld;
  16616. continue;
  16617. }
  16618. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16619. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16620. }
  16621. return {
  16622. min: minVector,
  16623. max: maxVector
  16624. };
  16625. };
  16626. Mesh.Center = function (meshesOrMinMaxVector) {
  16627. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16628. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16629. };
  16630. /**
  16631. * Merge the array of meshes into a single mesh for performance reasons.
  16632. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16633. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16634. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16635. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16636. */
  16637. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16638. if (disposeSource === void 0) { disposeSource = true; }
  16639. var index;
  16640. if (!allow32BitsIndices) {
  16641. var totalVertices = 0;
  16642. // Counting vertices
  16643. for (index = 0; index < meshes.length; index++) {
  16644. if (meshes[index]) {
  16645. totalVertices += meshes[index].getTotalVertices();
  16646. if (totalVertices > 65536) {
  16647. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16648. return null;
  16649. }
  16650. }
  16651. }
  16652. }
  16653. // Merge
  16654. var vertexData;
  16655. var otherVertexData;
  16656. var source;
  16657. for (index = 0; index < meshes.length; index++) {
  16658. if (meshes[index]) {
  16659. meshes[index].computeWorldMatrix(true);
  16660. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16661. otherVertexData.transform(meshes[index].getWorldMatrix());
  16662. if (vertexData) {
  16663. vertexData.merge(otherVertexData);
  16664. }
  16665. else {
  16666. vertexData = otherVertexData;
  16667. source = meshes[index];
  16668. }
  16669. }
  16670. }
  16671. if (!meshSubclass) {
  16672. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16673. }
  16674. vertexData.applyToMesh(meshSubclass);
  16675. // Setting properties
  16676. meshSubclass.material = source.material;
  16677. meshSubclass.checkCollisions = source.checkCollisions;
  16678. // Cleaning
  16679. if (disposeSource) {
  16680. for (index = 0; index < meshes.length; index++) {
  16681. if (meshes[index]) {
  16682. meshes[index].dispose();
  16683. }
  16684. }
  16685. }
  16686. return meshSubclass;
  16687. };
  16688. // Consts
  16689. Mesh._FRONTSIDE = 0;
  16690. Mesh._BACKSIDE = 1;
  16691. Mesh._DOUBLESIDE = 2;
  16692. Mesh._DEFAULTSIDE = 0;
  16693. Mesh._NO_CAP = 0;
  16694. Mesh._CAP_START = 1;
  16695. Mesh._CAP_END = 2;
  16696. Mesh._CAP_ALL = 3;
  16697. return Mesh;
  16698. })(BABYLON.AbstractMesh);
  16699. BABYLON.Mesh = Mesh;
  16700. })(BABYLON || (BABYLON = {}));
  16701. var BABYLON;
  16702. (function (BABYLON) {
  16703. var SubMesh = (function () {
  16704. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16705. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16706. this.materialIndex = materialIndex;
  16707. this.verticesStart = verticesStart;
  16708. this.verticesCount = verticesCount;
  16709. this.indexStart = indexStart;
  16710. this.indexCount = indexCount;
  16711. this._renderId = 0;
  16712. this._mesh = mesh;
  16713. this._renderingMesh = renderingMesh || mesh;
  16714. mesh.subMeshes.push(this);
  16715. this._trianglePlanes = [];
  16716. this._id = mesh.subMeshes.length - 1;
  16717. if (createBoundingBox) {
  16718. this.refreshBoundingInfo();
  16719. mesh.computeWorldMatrix(true);
  16720. }
  16721. }
  16722. SubMesh.prototype.getBoundingInfo = function () {
  16723. return this._boundingInfo;
  16724. };
  16725. SubMesh.prototype.getMesh = function () {
  16726. return this._mesh;
  16727. };
  16728. SubMesh.prototype.getRenderingMesh = function () {
  16729. return this._renderingMesh;
  16730. };
  16731. SubMesh.prototype.getMaterial = function () {
  16732. var rootMaterial = this._renderingMesh.material;
  16733. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16734. var multiMaterial = rootMaterial;
  16735. return multiMaterial.getSubMaterial(this.materialIndex);
  16736. }
  16737. if (!rootMaterial) {
  16738. return this._mesh.getScene().defaultMaterial;
  16739. }
  16740. return rootMaterial;
  16741. };
  16742. // Methods
  16743. SubMesh.prototype.refreshBoundingInfo = function () {
  16744. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16745. if (!data) {
  16746. this._boundingInfo = this._mesh._boundingInfo;
  16747. return;
  16748. }
  16749. var indices = this._renderingMesh.getIndices();
  16750. var extend;
  16751. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16752. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16753. }
  16754. else {
  16755. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16756. }
  16757. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16758. };
  16759. SubMesh.prototype._checkCollision = function (collider) {
  16760. return this._boundingInfo._checkCollision(collider);
  16761. };
  16762. SubMesh.prototype.updateBoundingInfo = function (world) {
  16763. if (!this._boundingInfo) {
  16764. this.refreshBoundingInfo();
  16765. }
  16766. this._boundingInfo._update(world);
  16767. };
  16768. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16769. return this._boundingInfo.isInFrustum(frustumPlanes);
  16770. };
  16771. SubMesh.prototype.render = function (enableAlphaMode) {
  16772. this._renderingMesh.render(this, enableAlphaMode);
  16773. };
  16774. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16775. if (!this._linesIndexBuffer) {
  16776. var linesIndices = [];
  16777. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16778. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16779. }
  16780. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16781. this.linesIndexCount = linesIndices.length;
  16782. }
  16783. return this._linesIndexBuffer;
  16784. };
  16785. SubMesh.prototype.canIntersects = function (ray) {
  16786. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16787. };
  16788. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16789. var intersectInfo = null;
  16790. // Triangles test
  16791. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16792. var p0 = positions[indices[index]];
  16793. var p1 = positions[indices[index + 1]];
  16794. var p2 = positions[indices[index + 2]];
  16795. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16796. if (currentIntersectInfo) {
  16797. if (currentIntersectInfo.distance < 0) {
  16798. continue;
  16799. }
  16800. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16801. intersectInfo = currentIntersectInfo;
  16802. intersectInfo.faceId = index / 3;
  16803. if (fastCheck) {
  16804. break;
  16805. }
  16806. }
  16807. }
  16808. }
  16809. return intersectInfo;
  16810. };
  16811. // Clone
  16812. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16813. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16814. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16815. return result;
  16816. };
  16817. // Dispose
  16818. SubMesh.prototype.dispose = function () {
  16819. if (this._linesIndexBuffer) {
  16820. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16821. this._linesIndexBuffer = null;
  16822. }
  16823. // Remove from mesh
  16824. var index = this._mesh.subMeshes.indexOf(this);
  16825. this._mesh.subMeshes.splice(index, 1);
  16826. };
  16827. // Statics
  16828. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16829. var minVertexIndex = Number.MAX_VALUE;
  16830. var maxVertexIndex = -Number.MAX_VALUE;
  16831. renderingMesh = renderingMesh || mesh;
  16832. var indices = renderingMesh.getIndices();
  16833. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16834. var vertexIndex = indices[index];
  16835. if (vertexIndex < minVertexIndex)
  16836. minVertexIndex = vertexIndex;
  16837. if (vertexIndex > maxVertexIndex)
  16838. maxVertexIndex = vertexIndex;
  16839. }
  16840. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16841. };
  16842. return SubMesh;
  16843. })();
  16844. BABYLON.SubMesh = SubMesh;
  16845. })(BABYLON || (BABYLON = {}));
  16846. var BABYLON;
  16847. (function (BABYLON) {
  16848. var BaseTexture = (function () {
  16849. function BaseTexture(scene) {
  16850. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16851. this.hasAlpha = false;
  16852. this.getAlphaFromRGB = false;
  16853. this.level = 1;
  16854. this.isCube = false;
  16855. this.isRenderTarget = false;
  16856. this.animations = new Array();
  16857. this.coordinatesIndex = 0;
  16858. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16859. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16860. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16861. this.anisotropicFilteringLevel = 4;
  16862. this._scene = scene;
  16863. this._scene.textures.push(this);
  16864. }
  16865. BaseTexture.prototype.getScene = function () {
  16866. return this._scene;
  16867. };
  16868. BaseTexture.prototype.getTextureMatrix = function () {
  16869. return null;
  16870. };
  16871. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16872. return null;
  16873. };
  16874. BaseTexture.prototype.getInternalTexture = function () {
  16875. return this._texture;
  16876. };
  16877. BaseTexture.prototype.isReady = function () {
  16878. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16879. return true;
  16880. }
  16881. if (this._texture) {
  16882. return this._texture.isReady;
  16883. }
  16884. return false;
  16885. };
  16886. BaseTexture.prototype.getSize = function () {
  16887. if (this._texture._width) {
  16888. return { width: this._texture._width, height: this._texture._height };
  16889. }
  16890. if (this._texture._size) {
  16891. return { width: this._texture._size, height: this._texture._size };
  16892. }
  16893. return { width: 0, height: 0 };
  16894. };
  16895. BaseTexture.prototype.getBaseSize = function () {
  16896. if (!this.isReady())
  16897. return { width: 0, height: 0 };
  16898. if (this._texture._size) {
  16899. return { width: this._texture._size, height: this._texture._size };
  16900. }
  16901. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16902. };
  16903. BaseTexture.prototype.scale = function (ratio) {
  16904. };
  16905. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16906. get: function () {
  16907. return false;
  16908. },
  16909. enumerable: true,
  16910. configurable: true
  16911. });
  16912. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16913. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16914. for (var index = 0; index < texturesCache.length; index++) {
  16915. var texturesCacheEntry = texturesCache[index];
  16916. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16917. texturesCache.splice(index, 1);
  16918. return;
  16919. }
  16920. }
  16921. };
  16922. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16923. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16924. for (var index = 0; index < texturesCache.length; index++) {
  16925. var texturesCacheEntry = texturesCache[index];
  16926. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16927. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16928. texturesCacheEntry.references++;
  16929. return texturesCacheEntry;
  16930. }
  16931. }
  16932. }
  16933. return null;
  16934. };
  16935. BaseTexture.prototype.delayLoad = function () {
  16936. };
  16937. BaseTexture.prototype.clone = function () {
  16938. return null;
  16939. };
  16940. BaseTexture.prototype.releaseInternalTexture = function () {
  16941. if (this._texture) {
  16942. this._scene.getEngine().releaseInternalTexture(this._texture);
  16943. delete this._texture;
  16944. }
  16945. };
  16946. BaseTexture.prototype.dispose = function () {
  16947. // Remove from scene
  16948. var index = this._scene.textures.indexOf(this);
  16949. if (index >= 0) {
  16950. this._scene.textures.splice(index, 1);
  16951. }
  16952. if (this._texture === undefined) {
  16953. return;
  16954. }
  16955. // Callback
  16956. if (this.onDispose) {
  16957. this.onDispose();
  16958. }
  16959. };
  16960. return BaseTexture;
  16961. })();
  16962. BABYLON.BaseTexture = BaseTexture;
  16963. })(BABYLON || (BABYLON = {}));
  16964. var BABYLON;
  16965. (function (BABYLON) {
  16966. var Texture = (function (_super) {
  16967. __extends(Texture, _super);
  16968. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16969. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16970. if (onLoad === void 0) { onLoad = null; }
  16971. if (onError === void 0) { onError = null; }
  16972. if (buffer === void 0) { buffer = null; }
  16973. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16974. _super.call(this, scene);
  16975. this.uOffset = 0;
  16976. this.vOffset = 0;
  16977. this.uScale = 1.0;
  16978. this.vScale = 1.0;
  16979. this.uAng = 0;
  16980. this.vAng = 0;
  16981. this.wAng = 0;
  16982. this.name = url;
  16983. this.url = url;
  16984. this._noMipmap = noMipmap;
  16985. this._invertY = invertY;
  16986. this._samplingMode = samplingMode;
  16987. this._buffer = buffer;
  16988. this._deleteBuffer = deleteBuffer;
  16989. if (!url) {
  16990. return;
  16991. }
  16992. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16993. if (!this._texture) {
  16994. if (!scene.useDelayedTextureLoading) {
  16995. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16996. if (deleteBuffer) {
  16997. delete this._buffer;
  16998. }
  16999. }
  17000. else {
  17001. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17002. }
  17003. }
  17004. else {
  17005. BABYLON.Tools.SetImmediate(function () {
  17006. if (onLoad) {
  17007. onLoad();
  17008. }
  17009. });
  17010. }
  17011. }
  17012. Texture.prototype.delayLoad = function () {
  17013. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17014. return;
  17015. }
  17016. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17017. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17018. if (!this._texture) {
  17019. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17020. if (this._deleteBuffer) {
  17021. delete this._buffer;
  17022. }
  17023. }
  17024. };
  17025. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17026. if (!this._texture) {
  17027. return;
  17028. }
  17029. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17030. };
  17031. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17032. x *= this.uScale;
  17033. y *= this.vScale;
  17034. x -= 0.5 * this.uScale;
  17035. y -= 0.5 * this.vScale;
  17036. z -= 0.5;
  17037. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17038. t.x += 0.5 * this.uScale + this.uOffset;
  17039. t.y += 0.5 * this.vScale + this.vOffset;
  17040. t.z += 0.5;
  17041. };
  17042. Texture.prototype.getTextureMatrix = function () {
  17043. if (this.uOffset === this._cachedUOffset &&
  17044. this.vOffset === this._cachedVOffset &&
  17045. this.uScale === this._cachedUScale &&
  17046. this.vScale === this._cachedVScale &&
  17047. this.uAng === this._cachedUAng &&
  17048. this.vAng === this._cachedVAng &&
  17049. this.wAng === this._cachedWAng) {
  17050. return this._cachedTextureMatrix;
  17051. }
  17052. this._cachedUOffset = this.uOffset;
  17053. this._cachedVOffset = this.vOffset;
  17054. this._cachedUScale = this.uScale;
  17055. this._cachedVScale = this.vScale;
  17056. this._cachedUAng = this.uAng;
  17057. this._cachedVAng = this.vAng;
  17058. this._cachedWAng = this.wAng;
  17059. if (!this._cachedTextureMatrix) {
  17060. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17061. this._rowGenerationMatrix = new BABYLON.Matrix();
  17062. this._t0 = BABYLON.Vector3.Zero();
  17063. this._t1 = BABYLON.Vector3.Zero();
  17064. this._t2 = BABYLON.Vector3.Zero();
  17065. }
  17066. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17067. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17068. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17069. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17070. this._t1.subtractInPlace(this._t0);
  17071. this._t2.subtractInPlace(this._t0);
  17072. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17073. this._cachedTextureMatrix.m[0] = this._t1.x;
  17074. this._cachedTextureMatrix.m[1] = this._t1.y;
  17075. this._cachedTextureMatrix.m[2] = this._t1.z;
  17076. this._cachedTextureMatrix.m[4] = this._t2.x;
  17077. this._cachedTextureMatrix.m[5] = this._t2.y;
  17078. this._cachedTextureMatrix.m[6] = this._t2.z;
  17079. this._cachedTextureMatrix.m[8] = this._t0.x;
  17080. this._cachedTextureMatrix.m[9] = this._t0.y;
  17081. this._cachedTextureMatrix.m[10] = this._t0.z;
  17082. return this._cachedTextureMatrix;
  17083. };
  17084. Texture.prototype.getReflectionTextureMatrix = function () {
  17085. if (this.uOffset === this._cachedUOffset &&
  17086. this.vOffset === this._cachedVOffset &&
  17087. this.uScale === this._cachedUScale &&
  17088. this.vScale === this._cachedVScale &&
  17089. this.coordinatesMode === this._cachedCoordinatesMode) {
  17090. return this._cachedTextureMatrix;
  17091. }
  17092. if (!this._cachedTextureMatrix) {
  17093. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17094. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17095. }
  17096. this._cachedCoordinatesMode = this.coordinatesMode;
  17097. switch (this.coordinatesMode) {
  17098. case Texture.SPHERICAL_MODE:
  17099. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17100. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  17101. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  17102. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  17103. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  17104. break;
  17105. case Texture.PLANAR_MODE:
  17106. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17107. this._cachedTextureMatrix[0] = this.uScale;
  17108. this._cachedTextureMatrix[5] = this.vScale;
  17109. this._cachedTextureMatrix[12] = this.uOffset;
  17110. this._cachedTextureMatrix[13] = this.vOffset;
  17111. break;
  17112. case Texture.PROJECTION_MODE:
  17113. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17114. this._projectionModeMatrix.m[0] = 0.5;
  17115. this._projectionModeMatrix.m[5] = -0.5;
  17116. this._projectionModeMatrix.m[10] = 0.0;
  17117. this._projectionModeMatrix.m[12] = 0.5;
  17118. this._projectionModeMatrix.m[13] = 0.5;
  17119. this._projectionModeMatrix.m[14] = 1.0;
  17120. this._projectionModeMatrix.m[15] = 1.0;
  17121. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17122. break;
  17123. default:
  17124. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17125. break;
  17126. }
  17127. return this._cachedTextureMatrix;
  17128. };
  17129. Texture.prototype.clone = function () {
  17130. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17131. // Base texture
  17132. newTexture.hasAlpha = this.hasAlpha;
  17133. newTexture.level = this.level;
  17134. newTexture.wrapU = this.wrapU;
  17135. newTexture.wrapV = this.wrapV;
  17136. newTexture.coordinatesIndex = this.coordinatesIndex;
  17137. newTexture.coordinatesMode = this.coordinatesMode;
  17138. // Texture
  17139. newTexture.uOffset = this.uOffset;
  17140. newTexture.vOffset = this.vOffset;
  17141. newTexture.uScale = this.uScale;
  17142. newTexture.vScale = this.vScale;
  17143. newTexture.uAng = this.uAng;
  17144. newTexture.vAng = this.vAng;
  17145. newTexture.wAng = this.wAng;
  17146. return newTexture;
  17147. };
  17148. // Statics
  17149. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17150. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17151. if (onLoad === void 0) { onLoad = null; }
  17152. if (onError === void 0) { onError = null; }
  17153. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17154. };
  17155. // Constants
  17156. Texture.NEAREST_SAMPLINGMODE = 1;
  17157. Texture.BILINEAR_SAMPLINGMODE = 2;
  17158. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17159. Texture.EXPLICIT_MODE = 0;
  17160. Texture.SPHERICAL_MODE = 1;
  17161. Texture.PLANAR_MODE = 2;
  17162. Texture.CUBIC_MODE = 3;
  17163. Texture.PROJECTION_MODE = 4;
  17164. Texture.SKYBOX_MODE = 5;
  17165. Texture.INVCUBIC_MODE = 6;
  17166. Texture.CLAMP_ADDRESSMODE = 0;
  17167. Texture.WRAP_ADDRESSMODE = 1;
  17168. Texture.MIRROR_ADDRESSMODE = 2;
  17169. return Texture;
  17170. })(BABYLON.BaseTexture);
  17171. BABYLON.Texture = Texture;
  17172. })(BABYLON || (BABYLON = {}));
  17173. var BABYLON;
  17174. (function (BABYLON) {
  17175. var CubeTexture = (function (_super) {
  17176. __extends(CubeTexture, _super);
  17177. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17178. _super.call(this, scene);
  17179. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17180. this.name = rootUrl;
  17181. this.url = rootUrl;
  17182. this._noMipmap = noMipmap;
  17183. this.hasAlpha = false;
  17184. if (!rootUrl) {
  17185. return;
  17186. }
  17187. this._texture = this._getFromCache(rootUrl, noMipmap);
  17188. if (!extensions) {
  17189. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17190. }
  17191. this._extensions = extensions;
  17192. if (!this._texture) {
  17193. if (!scene.useDelayedTextureLoading) {
  17194. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17195. }
  17196. else {
  17197. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17198. }
  17199. }
  17200. this.isCube = true;
  17201. this._textureMatrix = BABYLON.Matrix.Identity();
  17202. }
  17203. CubeTexture.prototype.clone = function () {
  17204. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17205. // Base texture
  17206. newTexture.level = this.level;
  17207. newTexture.wrapU = this.wrapU;
  17208. newTexture.wrapV = this.wrapV;
  17209. newTexture.coordinatesIndex = this.coordinatesIndex;
  17210. newTexture.coordinatesMode = this.coordinatesMode;
  17211. return newTexture;
  17212. };
  17213. // Methods
  17214. CubeTexture.prototype.delayLoad = function () {
  17215. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17216. return;
  17217. }
  17218. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17219. this._texture = this._getFromCache(this.url, this._noMipmap);
  17220. if (!this._texture) {
  17221. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17222. }
  17223. };
  17224. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17225. return this._textureMatrix;
  17226. };
  17227. return CubeTexture;
  17228. })(BABYLON.BaseTexture);
  17229. BABYLON.CubeTexture = CubeTexture;
  17230. })(BABYLON || (BABYLON = {}));
  17231. var BABYLON;
  17232. (function (BABYLON) {
  17233. var RenderTargetTexture = (function (_super) {
  17234. __extends(RenderTargetTexture, _super);
  17235. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17236. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17237. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17238. if (isCube === void 0) { isCube = false; }
  17239. _super.call(this, null, scene, !generateMipMaps);
  17240. this.isCube = isCube;
  17241. this.renderList = new Array();
  17242. this.renderParticles = true;
  17243. this.renderSprites = false;
  17244. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17245. this._currentRefreshId = -1;
  17246. this._refreshRate = 1;
  17247. this.name = name;
  17248. this.isRenderTarget = true;
  17249. this._size = size;
  17250. this._generateMipMaps = generateMipMaps;
  17251. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17252. if (isCube) {
  17253. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17254. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17255. this._textureMatrix = BABYLON.Matrix.Identity();
  17256. }
  17257. else {
  17258. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17259. }
  17260. // Rendering groups
  17261. this._renderingManager = new BABYLON.RenderingManager(scene);
  17262. }
  17263. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONCE", {
  17264. get: function () {
  17265. return RenderTargetTexture._REFRESHRATE_RENDERONCE;
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYFRAME", {
  17271. get: function () {
  17272. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME;
  17273. },
  17274. enumerable: true,
  17275. configurable: true
  17276. });
  17277. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYTWOFRAME", {
  17278. get: function () {
  17279. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME;
  17280. },
  17281. enumerable: true,
  17282. configurable: true
  17283. });
  17284. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17285. this._currentRefreshId = -1;
  17286. };
  17287. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17288. get: function () {
  17289. return this._refreshRate;
  17290. },
  17291. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17292. set: function (value) {
  17293. this._refreshRate = value;
  17294. this.resetRefreshCounter();
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. RenderTargetTexture.prototype._shouldRender = function () {
  17300. if (this._currentRefreshId === -1) {
  17301. this._currentRefreshId = 1;
  17302. return true;
  17303. }
  17304. if (this.refreshRate === this._currentRefreshId) {
  17305. this._currentRefreshId = 1;
  17306. return true;
  17307. }
  17308. this._currentRefreshId++;
  17309. return false;
  17310. };
  17311. RenderTargetTexture.prototype.isReady = function () {
  17312. if (!this.getScene().renderTargetsEnabled) {
  17313. return false;
  17314. }
  17315. return _super.prototype.isReady.call(this);
  17316. };
  17317. RenderTargetTexture.prototype.getRenderSize = function () {
  17318. return this._size;
  17319. };
  17320. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17321. get: function () {
  17322. return true;
  17323. },
  17324. enumerable: true,
  17325. configurable: true
  17326. });
  17327. RenderTargetTexture.prototype.scale = function (ratio) {
  17328. var newSize = this._size * ratio;
  17329. this.resize(newSize, this._generateMipMaps);
  17330. };
  17331. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17332. if (this.isCube) {
  17333. return this._textureMatrix;
  17334. }
  17335. return _super.prototype.getReflectionTextureMatrix.call(this);
  17336. };
  17337. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17338. this.releaseInternalTexture();
  17339. if (this.isCube) {
  17340. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17341. }
  17342. else {
  17343. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17344. }
  17345. };
  17346. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17347. var scene = this.getScene();
  17348. if (this._waitingRenderList) {
  17349. this.renderList = [];
  17350. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17351. var id = this._waitingRenderList[index];
  17352. this.renderList.push(scene.getMeshByID(id));
  17353. }
  17354. delete this._waitingRenderList;
  17355. }
  17356. if (this.renderList && this.renderList.length === 0) {
  17357. return;
  17358. }
  17359. // Prepare renderingManager
  17360. this._renderingManager.reset();
  17361. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17362. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17363. var mesh = currentRenderList[meshIndex];
  17364. if (mesh) {
  17365. if (!mesh.isReady()) {
  17366. // Reset _currentRefreshId
  17367. this.resetRefreshCounter();
  17368. continue;
  17369. }
  17370. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17371. mesh._activate(scene.getRenderId());
  17372. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17373. var subMesh = mesh.subMeshes[subIndex];
  17374. scene._activeIndices += subMesh.indexCount;
  17375. this._renderingManager.dispatch(subMesh);
  17376. }
  17377. }
  17378. }
  17379. }
  17380. if (this.isCube) {
  17381. for (var face = 0; face < 6; face++) {
  17382. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17383. }
  17384. }
  17385. else {
  17386. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17387. }
  17388. if (this.onAfterUnbind) {
  17389. this.onAfterUnbind();
  17390. }
  17391. scene.resetCachedMaterial();
  17392. };
  17393. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17394. var scene = this.getScene();
  17395. var engine = scene.getEngine();
  17396. // Bind
  17397. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17398. if (this.isCube) {
  17399. engine.bindFramebuffer(this._texture, faceIndex);
  17400. }
  17401. else {
  17402. engine.bindFramebuffer(this._texture);
  17403. }
  17404. }
  17405. if (this.onBeforeRender) {
  17406. this.onBeforeRender(faceIndex);
  17407. }
  17408. // Clear
  17409. if (this.onClear) {
  17410. this.onClear(engine);
  17411. }
  17412. else {
  17413. engine.clear(scene.clearColor, true, true);
  17414. }
  17415. if (!this._doNotChangeAspectRatio) {
  17416. scene.updateTransformMatrix(true);
  17417. }
  17418. // Render
  17419. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17420. if (useCameraPostProcess) {
  17421. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17422. }
  17423. if (!this._doNotChangeAspectRatio) {
  17424. scene.updateTransformMatrix(true);
  17425. }
  17426. if (this.onAfterRender) {
  17427. this.onAfterRender(faceIndex);
  17428. }
  17429. // Dump ?
  17430. if (dumpForDebug) {
  17431. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17432. }
  17433. // Unbind
  17434. if (!this.isCube || faceIndex === 5) {
  17435. if (this.isCube) {
  17436. if (faceIndex === 5) {
  17437. engine.generateMipMapsForCubemap(this._texture);
  17438. }
  17439. }
  17440. engine.unBindFramebuffer(this._texture, true);
  17441. }
  17442. };
  17443. RenderTargetTexture.prototype.clone = function () {
  17444. var textureSize = this.getSize();
  17445. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17446. // Base texture
  17447. newTexture.hasAlpha = this.hasAlpha;
  17448. newTexture.level = this.level;
  17449. // RenderTarget Texture
  17450. newTexture.coordinatesMode = this.coordinatesMode;
  17451. newTexture.renderList = this.renderList.slice(0);
  17452. return newTexture;
  17453. };
  17454. RenderTargetTexture._REFRESHRATE_RENDERONCE = 0;
  17455. RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME = 1;
  17456. RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME = 2;
  17457. return RenderTargetTexture;
  17458. })(BABYLON.Texture);
  17459. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17460. })(BABYLON || (BABYLON = {}));
  17461. var BABYLON;
  17462. (function (BABYLON) {
  17463. var ProceduralTexture = (function (_super) {
  17464. __extends(ProceduralTexture, _super);
  17465. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17466. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17467. _super.call(this, null, scene, !generateMipMaps);
  17468. this.isEnabled = true;
  17469. this._currentRefreshId = -1;
  17470. this._refreshRate = 1;
  17471. this._vertexDeclaration = [2];
  17472. this._vertexStrideSize = 2 * 4;
  17473. this._uniforms = new Array();
  17474. this._samplers = new Array();
  17475. this._textures = new Array();
  17476. this._floats = new Array();
  17477. this._floatsArrays = {};
  17478. this._colors3 = new Array();
  17479. this._colors4 = new Array();
  17480. this._vectors2 = new Array();
  17481. this._vectors3 = new Array();
  17482. this._matrices = new Array();
  17483. this._fallbackTextureUsed = false;
  17484. scene._proceduralTextures.push(this);
  17485. this.name = name;
  17486. this.isRenderTarget = true;
  17487. this._size = size;
  17488. this._generateMipMaps = generateMipMaps;
  17489. this.setFragment(fragment);
  17490. this._fallbackTexture = fallbackTexture;
  17491. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17492. // VBO
  17493. var vertices = [];
  17494. vertices.push(1, 1);
  17495. vertices.push(-1, 1);
  17496. vertices.push(-1, -1);
  17497. vertices.push(1, -1);
  17498. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17499. // Indices
  17500. var indices = [];
  17501. indices.push(0);
  17502. indices.push(1);
  17503. indices.push(2);
  17504. indices.push(0);
  17505. indices.push(2);
  17506. indices.push(3);
  17507. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17508. }
  17509. ProceduralTexture.prototype.reset = function () {
  17510. if (this._effect === undefined) {
  17511. return;
  17512. }
  17513. var engine = this.getScene().getEngine();
  17514. engine._releaseEffect(this._effect);
  17515. };
  17516. ProceduralTexture.prototype.isReady = function () {
  17517. var _this = this;
  17518. var engine = this.getScene().getEngine();
  17519. var shaders;
  17520. if (!this._fragment) {
  17521. return false;
  17522. }
  17523. if (this._fallbackTextureUsed) {
  17524. return true;
  17525. }
  17526. if (this._fragment.fragmentElement !== undefined) {
  17527. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17528. }
  17529. else {
  17530. shaders = { vertex: "procedural", fragment: this._fragment };
  17531. }
  17532. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17533. _this.releaseInternalTexture();
  17534. if (_this._fallbackTexture) {
  17535. _this._texture = _this._fallbackTexture._texture;
  17536. _this._texture.references++;
  17537. }
  17538. _this._fallbackTextureUsed = true;
  17539. });
  17540. return this._effect.isReady();
  17541. };
  17542. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17543. this._currentRefreshId = -1;
  17544. };
  17545. ProceduralTexture.prototype.setFragment = function (fragment) {
  17546. this._fragment = fragment;
  17547. };
  17548. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17549. get: function () {
  17550. return this._refreshRate;
  17551. },
  17552. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17553. set: function (value) {
  17554. this._refreshRate = value;
  17555. this.resetRefreshCounter();
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. ProceduralTexture.prototype._shouldRender = function () {
  17561. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17562. return false;
  17563. }
  17564. if (this._fallbackTextureUsed) {
  17565. return false;
  17566. }
  17567. if (this._currentRefreshId === -1) {
  17568. this._currentRefreshId = 1;
  17569. return true;
  17570. }
  17571. if (this.refreshRate === this._currentRefreshId) {
  17572. this._currentRefreshId = 1;
  17573. return true;
  17574. }
  17575. this._currentRefreshId++;
  17576. return false;
  17577. };
  17578. ProceduralTexture.prototype.getRenderSize = function () {
  17579. return this._size;
  17580. };
  17581. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17582. if (this._fallbackTextureUsed) {
  17583. return;
  17584. }
  17585. this.releaseInternalTexture();
  17586. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17587. };
  17588. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17589. if (this._uniforms.indexOf(uniformName) === -1) {
  17590. this._uniforms.push(uniformName);
  17591. }
  17592. };
  17593. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17594. if (this._samplers.indexOf(name) === -1) {
  17595. this._samplers.push(name);
  17596. }
  17597. this._textures[name] = texture;
  17598. return this;
  17599. };
  17600. ProceduralTexture.prototype.setFloat = function (name, value) {
  17601. this._checkUniform(name);
  17602. this._floats[name] = value;
  17603. return this;
  17604. };
  17605. ProceduralTexture.prototype.setFloats = function (name, value) {
  17606. this._checkUniform(name);
  17607. this._floatsArrays[name] = value;
  17608. return this;
  17609. };
  17610. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17611. this._checkUniform(name);
  17612. this._colors3[name] = value;
  17613. return this;
  17614. };
  17615. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17616. this._checkUniform(name);
  17617. this._colors4[name] = value;
  17618. return this;
  17619. };
  17620. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17621. this._checkUniform(name);
  17622. this._vectors2[name] = value;
  17623. return this;
  17624. };
  17625. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17626. this._checkUniform(name);
  17627. this._vectors3[name] = value;
  17628. return this;
  17629. };
  17630. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17631. this._checkUniform(name);
  17632. this._matrices[name] = value;
  17633. return this;
  17634. };
  17635. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17636. var scene = this.getScene();
  17637. var engine = scene.getEngine();
  17638. engine.bindFramebuffer(this._texture);
  17639. // Clear
  17640. engine.clear(scene.clearColor, true, true);
  17641. // Render
  17642. engine.enableEffect(this._effect);
  17643. engine.setState(false);
  17644. // Texture
  17645. for (var name in this._textures) {
  17646. this._effect.setTexture(name, this._textures[name]);
  17647. }
  17648. // Float
  17649. for (name in this._floats) {
  17650. this._effect.setFloat(name, this._floats[name]);
  17651. }
  17652. // Floats
  17653. for (name in this._floatsArrays) {
  17654. this._effect.setArray(name, this._floatsArrays[name]);
  17655. }
  17656. // Color3
  17657. for (name in this._colors3) {
  17658. this._effect.setColor3(name, this._colors3[name]);
  17659. }
  17660. // Color4
  17661. for (name in this._colors4) {
  17662. var color = this._colors4[name];
  17663. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17664. }
  17665. // Vector2
  17666. for (name in this._vectors2) {
  17667. this._effect.setVector2(name, this._vectors2[name]);
  17668. }
  17669. // Vector3
  17670. for (name in this._vectors3) {
  17671. this._effect.setVector3(name, this._vectors3[name]);
  17672. }
  17673. // Matrix
  17674. for (name in this._matrices) {
  17675. this._effect.setMatrix(name, this._matrices[name]);
  17676. }
  17677. // VBOs
  17678. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17679. // Draw order
  17680. engine.draw(true, 0, 6);
  17681. // Unbind
  17682. engine.unBindFramebuffer(this._texture);
  17683. };
  17684. ProceduralTexture.prototype.clone = function () {
  17685. var textureSize = this.getSize();
  17686. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17687. // Base texture
  17688. newTexture.hasAlpha = this.hasAlpha;
  17689. newTexture.level = this.level;
  17690. // RenderTarget Texture
  17691. newTexture.coordinatesMode = this.coordinatesMode;
  17692. return newTexture;
  17693. };
  17694. ProceduralTexture.prototype.dispose = function () {
  17695. var index = this.getScene()._proceduralTextures.indexOf(this);
  17696. if (index >= 0) {
  17697. this.getScene()._proceduralTextures.splice(index, 1);
  17698. }
  17699. _super.prototype.dispose.call(this);
  17700. };
  17701. return ProceduralTexture;
  17702. })(BABYLON.Texture);
  17703. BABYLON.ProceduralTexture = ProceduralTexture;
  17704. })(BABYLON || (BABYLON = {}));
  17705. var BABYLON;
  17706. (function (BABYLON) {
  17707. var MirrorTexture = (function (_super) {
  17708. __extends(MirrorTexture, _super);
  17709. function MirrorTexture(name, size, scene, generateMipMaps) {
  17710. var _this = this;
  17711. _super.call(this, name, size, scene, generateMipMaps, true);
  17712. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17713. this._transformMatrix = BABYLON.Matrix.Zero();
  17714. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17715. this.onBeforeRender = function () {
  17716. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17717. _this._savedViewMatrix = scene.getViewMatrix();
  17718. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17719. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17720. scene.clipPlane = _this.mirrorPlane;
  17721. scene.getEngine().cullBackFaces = false;
  17722. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17723. };
  17724. this.onAfterRender = function () {
  17725. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17726. scene.getEngine().cullBackFaces = true;
  17727. scene._mirroredCameraPosition = null;
  17728. delete scene.clipPlane;
  17729. };
  17730. }
  17731. MirrorTexture.prototype.clone = function () {
  17732. var textureSize = this.getSize();
  17733. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17734. // Base texture
  17735. newTexture.hasAlpha = this.hasAlpha;
  17736. newTexture.level = this.level;
  17737. // Mirror Texture
  17738. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17739. newTexture.renderList = this.renderList.slice(0);
  17740. return newTexture;
  17741. };
  17742. return MirrorTexture;
  17743. })(BABYLON.RenderTargetTexture);
  17744. BABYLON.MirrorTexture = MirrorTexture;
  17745. })(BABYLON || (BABYLON = {}));
  17746. var BABYLON;
  17747. (function (BABYLON) {
  17748. var DynamicTexture = (function (_super) {
  17749. __extends(DynamicTexture, _super);
  17750. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17752. _super.call(this, null, scene, !generateMipMaps);
  17753. this.name = name;
  17754. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17755. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17756. this._generateMipMaps = generateMipMaps;
  17757. if (options.getContext) {
  17758. this._canvas = options;
  17759. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17760. }
  17761. else {
  17762. this._canvas = document.createElement("canvas");
  17763. if (options.width) {
  17764. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17765. }
  17766. else {
  17767. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17768. }
  17769. }
  17770. var textureSize = this.getSize();
  17771. this._canvas.width = textureSize.width;
  17772. this._canvas.height = textureSize.height;
  17773. this._context = this._canvas.getContext("2d");
  17774. }
  17775. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17776. get: function () {
  17777. return true;
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. DynamicTexture.prototype.scale = function (ratio) {
  17783. var textureSize = this.getSize();
  17784. textureSize.width *= ratio;
  17785. textureSize.height *= ratio;
  17786. this._canvas.width = textureSize.width;
  17787. this._canvas.height = textureSize.height;
  17788. this.releaseInternalTexture();
  17789. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17790. };
  17791. DynamicTexture.prototype.getContext = function () {
  17792. return this._context;
  17793. };
  17794. DynamicTexture.prototype.clear = function () {
  17795. var size = this.getSize();
  17796. this._context.fillRect(0, 0, size.width, size.height);
  17797. };
  17798. DynamicTexture.prototype.update = function (invertY) {
  17799. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17800. };
  17801. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17802. if (update === void 0) { update = true; }
  17803. var size = this.getSize();
  17804. if (clearColor) {
  17805. this._context.fillStyle = clearColor;
  17806. this._context.fillRect(0, 0, size.width, size.height);
  17807. }
  17808. this._context.font = font;
  17809. if (x === null) {
  17810. var textSize = this._context.measureText(text);
  17811. x = (size.width - textSize.width) / 2;
  17812. }
  17813. this._context.fillStyle = color;
  17814. this._context.fillText(text, x, y);
  17815. if (update) {
  17816. this.update(invertY);
  17817. }
  17818. };
  17819. DynamicTexture.prototype.clone = function () {
  17820. var textureSize = this.getSize();
  17821. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17822. // Base texture
  17823. newTexture.hasAlpha = this.hasAlpha;
  17824. newTexture.level = this.level;
  17825. // Dynamic Texture
  17826. newTexture.wrapU = this.wrapU;
  17827. newTexture.wrapV = this.wrapV;
  17828. return newTexture;
  17829. };
  17830. return DynamicTexture;
  17831. })(BABYLON.Texture);
  17832. BABYLON.DynamicTexture = DynamicTexture;
  17833. })(BABYLON || (BABYLON = {}));
  17834. var BABYLON;
  17835. (function (BABYLON) {
  17836. var VideoTexture = (function (_super) {
  17837. __extends(VideoTexture, _super);
  17838. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17839. var _this = this;
  17840. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17841. if (invertY === void 0) { invertY = false; }
  17842. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17843. _super.call(this, null, scene, !generateMipMaps, invertY);
  17844. this._autoLaunch = true;
  17845. this.name = name;
  17846. this.video = document.createElement("video");
  17847. this.video.autoplay = false;
  17848. this.video.loop = true;
  17849. this.video.addEventListener("canplaythrough", function () {
  17850. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17851. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17852. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17853. }
  17854. else {
  17855. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17856. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17857. generateMipMaps = false;
  17858. }
  17859. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17860. _this._texture.isReady = true;
  17861. });
  17862. urls.forEach(function (url) {
  17863. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17864. var source = document.createElement("source");
  17865. source.src = url;
  17866. _this.video.appendChild(source);
  17867. });
  17868. this._lastUpdate = BABYLON.Tools.Now;
  17869. }
  17870. VideoTexture.prototype.update = function () {
  17871. if (this._autoLaunch) {
  17872. this._autoLaunch = false;
  17873. this.video.play();
  17874. }
  17875. var now = BABYLON.Tools.Now;
  17876. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17877. return false;
  17878. }
  17879. this._lastUpdate = now;
  17880. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17881. return true;
  17882. };
  17883. return VideoTexture;
  17884. })(BABYLON.Texture);
  17885. BABYLON.VideoTexture = VideoTexture;
  17886. })(BABYLON || (BABYLON = {}));
  17887. var BABYLON;
  17888. (function (BABYLON) {
  17889. var CustomProceduralTexture = (function (_super) {
  17890. __extends(CustomProceduralTexture, _super);
  17891. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17892. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17893. this._animate = true;
  17894. this._time = 0;
  17895. this._texturePath = texturePath;
  17896. //Try to load json
  17897. this.loadJson(texturePath);
  17898. this.refreshRate = 1;
  17899. }
  17900. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17901. var _this = this;
  17902. var that = this;
  17903. function noConfigFile() {
  17904. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17905. try {
  17906. that.setFragment(that._texturePath);
  17907. }
  17908. catch (ex) {
  17909. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17910. }
  17911. }
  17912. var configFileUrl = jsonUrl + "/config.json";
  17913. var xhr = new XMLHttpRequest();
  17914. xhr.open("GET", configFileUrl, true);
  17915. xhr.addEventListener("load", function () {
  17916. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17917. try {
  17918. _this._config = JSON.parse(xhr.response);
  17919. _this.updateShaderUniforms();
  17920. _this.updateTextures();
  17921. _this.setFragment(_this._texturePath + "/custom");
  17922. _this._animate = _this._config.animate;
  17923. _this.refreshRate = _this._config.refreshrate;
  17924. }
  17925. catch (ex) {
  17926. noConfigFile();
  17927. }
  17928. }
  17929. else {
  17930. noConfigFile();
  17931. }
  17932. }, false);
  17933. xhr.addEventListener("error", function () {
  17934. noConfigFile();
  17935. }, false);
  17936. try {
  17937. xhr.send();
  17938. }
  17939. catch (ex) {
  17940. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17941. }
  17942. };
  17943. CustomProceduralTexture.prototype.isReady = function () {
  17944. if (!_super.prototype.isReady.call(this)) {
  17945. return false;
  17946. }
  17947. for (var name in this._textures) {
  17948. var texture = this._textures[name];
  17949. if (!texture.isReady()) {
  17950. return false;
  17951. }
  17952. }
  17953. return true;
  17954. };
  17955. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17956. if (this._animate) {
  17957. this._time += this.getScene().getAnimationRatio() * 0.03;
  17958. this.updateShaderUniforms();
  17959. }
  17960. _super.prototype.render.call(this, useCameraPostProcess);
  17961. };
  17962. CustomProceduralTexture.prototype.updateTextures = function () {
  17963. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17964. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17965. }
  17966. };
  17967. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17968. if (this._config) {
  17969. for (var j = 0; j < this._config.uniforms.length; j++) {
  17970. var uniform = this._config.uniforms[j];
  17971. switch (uniform.type) {
  17972. case "float":
  17973. this.setFloat(uniform.name, uniform.value);
  17974. break;
  17975. case "color3":
  17976. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17977. break;
  17978. case "color4":
  17979. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17980. break;
  17981. case "vector2":
  17982. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17983. break;
  17984. case "vector3":
  17985. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17986. break;
  17987. }
  17988. }
  17989. }
  17990. this.setFloat("time", this._time);
  17991. };
  17992. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17993. get: function () {
  17994. return this._animate;
  17995. },
  17996. set: function (value) {
  17997. this._animate = value;
  17998. },
  17999. enumerable: true,
  18000. configurable: true
  18001. });
  18002. return CustomProceduralTexture;
  18003. })(BABYLON.ProceduralTexture);
  18004. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18005. })(BABYLON || (BABYLON = {}));
  18006. var BABYLON;
  18007. (function (BABYLON) {
  18008. var WoodProceduralTexture = (function (_super) {
  18009. __extends(WoodProceduralTexture, _super);
  18010. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18011. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  18012. this._ampScale = 100.0;
  18013. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  18014. this.updateShaderUniforms();
  18015. this.refreshRate = 0;
  18016. }
  18017. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  18018. this.setFloat("ampScale", this._ampScale);
  18019. this.setColor3("woodColor", this._woodColor);
  18020. };
  18021. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  18022. get: function () {
  18023. return this._ampScale;
  18024. },
  18025. set: function (value) {
  18026. this._ampScale = value;
  18027. this.updateShaderUniforms();
  18028. },
  18029. enumerable: true,
  18030. configurable: true
  18031. });
  18032. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  18033. get: function () {
  18034. return this._woodColor;
  18035. },
  18036. set: function (value) {
  18037. this._woodColor = value;
  18038. this.updateShaderUniforms();
  18039. },
  18040. enumerable: true,
  18041. configurable: true
  18042. });
  18043. return WoodProceduralTexture;
  18044. })(BABYLON.ProceduralTexture);
  18045. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  18046. var FireProceduralTexture = (function (_super) {
  18047. __extends(FireProceduralTexture, _super);
  18048. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18049. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  18050. this._time = 0.0;
  18051. this._speed = new BABYLON.Vector2(0.5, 0.3);
  18052. this._autoGenerateTime = true;
  18053. this._alphaThreshold = 0.5;
  18054. this._fireColors = FireProceduralTexture.RedFireColors;
  18055. this.updateShaderUniforms();
  18056. this.refreshRate = 1;
  18057. }
  18058. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  18059. this.setFloat("time", this._time);
  18060. this.setVector2("speed", this._speed);
  18061. this.setColor3("c1", this._fireColors[0]);
  18062. this.setColor3("c2", this._fireColors[1]);
  18063. this.setColor3("c3", this._fireColors[2]);
  18064. this.setColor3("c4", this._fireColors[3]);
  18065. this.setColor3("c5", this._fireColors[4]);
  18066. this.setColor3("c6", this._fireColors[5]);
  18067. this.setFloat("alphaThreshold", this._alphaThreshold);
  18068. };
  18069. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18070. if (this._autoGenerateTime) {
  18071. this._time += this.getScene().getAnimationRatio() * 0.03;
  18072. this.updateShaderUniforms();
  18073. }
  18074. _super.prototype.render.call(this, useCameraPostProcess);
  18075. };
  18076. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  18077. get: function () {
  18078. return [
  18079. new BABYLON.Color3(0.5, 0.0, 1.0),
  18080. new BABYLON.Color3(0.9, 0.0, 1.0),
  18081. new BABYLON.Color3(0.2, 0.0, 1.0),
  18082. new BABYLON.Color3(1.0, 0.9, 1.0),
  18083. new BABYLON.Color3(0.1, 0.1, 1.0),
  18084. new BABYLON.Color3(0.9, 0.9, 1.0)
  18085. ];
  18086. },
  18087. enumerable: true,
  18088. configurable: true
  18089. });
  18090. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  18091. get: function () {
  18092. return [
  18093. new BABYLON.Color3(0.5, 1.0, 0.0),
  18094. new BABYLON.Color3(0.5, 1.0, 0.0),
  18095. new BABYLON.Color3(0.3, 0.4, 0.0),
  18096. new BABYLON.Color3(0.5, 1.0, 0.0),
  18097. new BABYLON.Color3(0.2, 0.0, 0.0),
  18098. new BABYLON.Color3(0.5, 1.0, 0.0)
  18099. ];
  18100. },
  18101. enumerable: true,
  18102. configurable: true
  18103. });
  18104. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  18105. get: function () {
  18106. return [
  18107. new BABYLON.Color3(0.5, 0.0, 0.1),
  18108. new BABYLON.Color3(0.9, 0.0, 0.0),
  18109. new BABYLON.Color3(0.2, 0.0, 0.0),
  18110. new BABYLON.Color3(1.0, 0.9, 0.0),
  18111. new BABYLON.Color3(0.1, 0.1, 0.1),
  18112. new BABYLON.Color3(0.9, 0.9, 0.9)
  18113. ];
  18114. },
  18115. enumerable: true,
  18116. configurable: true
  18117. });
  18118. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  18119. get: function () {
  18120. return [
  18121. new BABYLON.Color3(0.1, 0.0, 0.5),
  18122. new BABYLON.Color3(0.0, 0.0, 0.5),
  18123. new BABYLON.Color3(0.1, 0.0, 0.2),
  18124. new BABYLON.Color3(0.0, 0.0, 1.0),
  18125. new BABYLON.Color3(0.1, 0.2, 0.3),
  18126. new BABYLON.Color3(0.0, 0.2, 0.9)
  18127. ];
  18128. },
  18129. enumerable: true,
  18130. configurable: true
  18131. });
  18132. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  18133. get: function () {
  18134. return this._fireColors;
  18135. },
  18136. set: function (value) {
  18137. this._fireColors = value;
  18138. this.updateShaderUniforms();
  18139. },
  18140. enumerable: true,
  18141. configurable: true
  18142. });
  18143. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  18144. get: function () {
  18145. return this._time;
  18146. },
  18147. set: function (value) {
  18148. this._time = value;
  18149. this.updateShaderUniforms();
  18150. },
  18151. enumerable: true,
  18152. configurable: true
  18153. });
  18154. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  18155. get: function () {
  18156. return this._speed;
  18157. },
  18158. set: function (value) {
  18159. this._speed = value;
  18160. this.updateShaderUniforms();
  18161. },
  18162. enumerable: true,
  18163. configurable: true
  18164. });
  18165. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  18166. get: function () {
  18167. return this._alphaThreshold;
  18168. },
  18169. set: function (value) {
  18170. this._alphaThreshold = value;
  18171. this.updateShaderUniforms();
  18172. },
  18173. enumerable: true,
  18174. configurable: true
  18175. });
  18176. return FireProceduralTexture;
  18177. })(BABYLON.ProceduralTexture);
  18178. BABYLON.FireProceduralTexture = FireProceduralTexture;
  18179. var CloudProceduralTexture = (function (_super) {
  18180. __extends(CloudProceduralTexture, _super);
  18181. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18182. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  18183. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  18184. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  18185. this.updateShaderUniforms();
  18186. this.refreshRate = 0;
  18187. }
  18188. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  18189. this.setColor4("skyColor", this._skyColor);
  18190. this.setColor4("cloudColor", this._cloudColor);
  18191. };
  18192. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  18193. get: function () {
  18194. return this._skyColor;
  18195. },
  18196. set: function (value) {
  18197. this._skyColor = value;
  18198. this.updateShaderUniforms();
  18199. },
  18200. enumerable: true,
  18201. configurable: true
  18202. });
  18203. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  18204. get: function () {
  18205. return this._cloudColor;
  18206. },
  18207. set: function (value) {
  18208. this._cloudColor = value;
  18209. this.updateShaderUniforms();
  18210. },
  18211. enumerable: true,
  18212. configurable: true
  18213. });
  18214. return CloudProceduralTexture;
  18215. })(BABYLON.ProceduralTexture);
  18216. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  18217. var GrassProceduralTexture = (function (_super) {
  18218. __extends(GrassProceduralTexture, _super);
  18219. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18220. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  18221. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  18222. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  18223. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  18224. this._groundColor = new BABYLON.Color3(1, 1, 1);
  18225. this._grassColors = [
  18226. new BABYLON.Color3(0.29, 0.38, 0.02),
  18227. new BABYLON.Color3(0.36, 0.49, 0.09),
  18228. new BABYLON.Color3(0.51, 0.6, 0.28)
  18229. ];
  18230. this.updateShaderUniforms();
  18231. this.refreshRate = 0;
  18232. }
  18233. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  18234. this.setColor3("herb1Color", this._grassColors[0]);
  18235. this.setColor3("herb2Color", this._grassColors[1]);
  18236. this.setColor3("herb3Color", this._grassColors[2]);
  18237. this.setColor3("groundColor", this._groundColor);
  18238. };
  18239. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  18240. get: function () {
  18241. return this._grassColors;
  18242. },
  18243. set: function (value) {
  18244. this._grassColors = value;
  18245. this.updateShaderUniforms();
  18246. },
  18247. enumerable: true,
  18248. configurable: true
  18249. });
  18250. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  18251. get: function () {
  18252. return this._groundColor;
  18253. },
  18254. set: function (value) {
  18255. this.groundColor = value;
  18256. this.updateShaderUniforms();
  18257. },
  18258. enumerable: true,
  18259. configurable: true
  18260. });
  18261. return GrassProceduralTexture;
  18262. })(BABYLON.ProceduralTexture);
  18263. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  18264. var RoadProceduralTexture = (function (_super) {
  18265. __extends(RoadProceduralTexture, _super);
  18266. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18267. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  18268. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  18269. this.updateShaderUniforms();
  18270. this.refreshRate = 0;
  18271. }
  18272. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  18273. this.setColor3("roadColor", this._roadColor);
  18274. };
  18275. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  18276. get: function () {
  18277. return this._roadColor;
  18278. },
  18279. set: function (value) {
  18280. this._roadColor = value;
  18281. this.updateShaderUniforms();
  18282. },
  18283. enumerable: true,
  18284. configurable: true
  18285. });
  18286. return RoadProceduralTexture;
  18287. })(BABYLON.ProceduralTexture);
  18288. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  18289. var BrickProceduralTexture = (function (_super) {
  18290. __extends(BrickProceduralTexture, _super);
  18291. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18292. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  18293. this._numberOfBricksHeight = 15;
  18294. this._numberOfBricksWidth = 5;
  18295. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18296. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18297. this.updateShaderUniforms();
  18298. this.refreshRate = 0;
  18299. }
  18300. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  18301. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  18302. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  18303. this.setColor3("brickColor", this._brickColor);
  18304. this.setColor3("jointColor", this._jointColor);
  18305. };
  18306. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  18307. get: function () {
  18308. return this._numberOfBricksHeight;
  18309. },
  18310. set: function (value) {
  18311. this._numberOfBricksHeight = value;
  18312. this.updateShaderUniforms();
  18313. },
  18314. enumerable: true,
  18315. configurable: true
  18316. });
  18317. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  18318. get: function () {
  18319. return this._numberOfBricksWidth;
  18320. },
  18321. set: function (value) {
  18322. this._numberOfBricksWidth = value;
  18323. this.updateShaderUniforms();
  18324. },
  18325. enumerable: true,
  18326. configurable: true
  18327. });
  18328. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  18329. get: function () {
  18330. return this._jointColor;
  18331. },
  18332. set: function (value) {
  18333. this._jointColor = value;
  18334. this.updateShaderUniforms();
  18335. },
  18336. enumerable: true,
  18337. configurable: true
  18338. });
  18339. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  18340. get: function () {
  18341. return this._brickColor;
  18342. },
  18343. set: function (value) {
  18344. this._brickColor = value;
  18345. this.updateShaderUniforms();
  18346. },
  18347. enumerable: true,
  18348. configurable: true
  18349. });
  18350. return BrickProceduralTexture;
  18351. })(BABYLON.ProceduralTexture);
  18352. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  18353. var MarbleProceduralTexture = (function (_super) {
  18354. __extends(MarbleProceduralTexture, _super);
  18355. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18356. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  18357. this._numberOfTilesHeight = 3;
  18358. this._numberOfTilesWidth = 3;
  18359. this._amplitude = 9.0;
  18360. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18361. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18362. this.updateShaderUniforms();
  18363. this.refreshRate = 0;
  18364. }
  18365. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  18366. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  18367. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  18368. this.setFloat("amplitude", this._amplitude);
  18369. this.setColor3("marbleColor", this._marbleColor);
  18370. this.setColor3("jointColor", this._jointColor);
  18371. };
  18372. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  18373. get: function () {
  18374. return this._numberOfTilesHeight;
  18375. },
  18376. set: function (value) {
  18377. this._numberOfTilesHeight = value;
  18378. this.updateShaderUniforms();
  18379. },
  18380. enumerable: true,
  18381. configurable: true
  18382. });
  18383. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  18384. get: function () {
  18385. return this._numberOfTilesWidth;
  18386. },
  18387. set: function (value) {
  18388. this._numberOfTilesWidth = value;
  18389. this.updateShaderUniforms();
  18390. },
  18391. enumerable: true,
  18392. configurable: true
  18393. });
  18394. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  18395. get: function () {
  18396. return this._jointColor;
  18397. },
  18398. set: function (value) {
  18399. this._jointColor = value;
  18400. this.updateShaderUniforms();
  18401. },
  18402. enumerable: true,
  18403. configurable: true
  18404. });
  18405. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  18406. get: function () {
  18407. return this._marbleColor;
  18408. },
  18409. set: function (value) {
  18410. this._marbleColor = value;
  18411. this.updateShaderUniforms();
  18412. },
  18413. enumerable: true,
  18414. configurable: true
  18415. });
  18416. return MarbleProceduralTexture;
  18417. })(BABYLON.ProceduralTexture);
  18418. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18419. })(BABYLON || (BABYLON = {}));
  18420. var BABYLON;
  18421. (function (BABYLON) {
  18422. var EffectFallbacks = (function () {
  18423. function EffectFallbacks() {
  18424. this._defines = {};
  18425. this._currentRank = 32;
  18426. this._maxRank = -1;
  18427. }
  18428. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18429. if (!this._defines[rank]) {
  18430. if (rank < this._currentRank) {
  18431. this._currentRank = rank;
  18432. }
  18433. if (rank > this._maxRank) {
  18434. this._maxRank = rank;
  18435. }
  18436. this._defines[rank] = new Array();
  18437. }
  18438. this._defines[rank].push(define);
  18439. };
  18440. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18441. get: function () {
  18442. return this._currentRank <= this._maxRank;
  18443. },
  18444. enumerable: true,
  18445. configurable: true
  18446. });
  18447. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18448. var currentFallbacks = this._defines[this._currentRank];
  18449. for (var index = 0; index < currentFallbacks.length; index++) {
  18450. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18451. }
  18452. this._currentRank++;
  18453. return currentDefines;
  18454. };
  18455. return EffectFallbacks;
  18456. })();
  18457. BABYLON.EffectFallbacks = EffectFallbacks;
  18458. var Effect = (function () {
  18459. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18460. var _this = this;
  18461. this._isReady = false;
  18462. this._compilationError = "";
  18463. this._valueCache = [];
  18464. this._engine = engine;
  18465. this.name = baseName;
  18466. this.defines = defines;
  18467. this._uniformsNames = uniformsNames.concat(samplers);
  18468. this._samplers = samplers;
  18469. this._attributesNames = attributesNames;
  18470. this.onError = onError;
  18471. this.onCompiled = onCompiled;
  18472. var vertexSource;
  18473. var fragmentSource;
  18474. if (baseName.vertexElement) {
  18475. vertexSource = document.getElementById(baseName.vertexElement);
  18476. if (!vertexSource) {
  18477. vertexSource = baseName.vertexElement;
  18478. }
  18479. }
  18480. else {
  18481. vertexSource = baseName.vertex || baseName;
  18482. }
  18483. if (baseName.fragmentElement) {
  18484. fragmentSource = document.getElementById(baseName.fragmentElement);
  18485. if (!fragmentSource) {
  18486. fragmentSource = baseName.fragmentElement;
  18487. }
  18488. }
  18489. else {
  18490. fragmentSource = baseName.fragment || baseName;
  18491. }
  18492. this._loadVertexShader(vertexSource, function (vertexCode) {
  18493. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18494. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18495. });
  18496. });
  18497. }
  18498. // Properties
  18499. Effect.prototype.isReady = function () {
  18500. return this._isReady;
  18501. };
  18502. Effect.prototype.getProgram = function () {
  18503. return this._program;
  18504. };
  18505. Effect.prototype.getAttributesNames = function () {
  18506. return this._attributesNames;
  18507. };
  18508. Effect.prototype.getAttributeLocation = function (index) {
  18509. return this._attributes[index];
  18510. };
  18511. Effect.prototype.getAttributeLocationByName = function (name) {
  18512. var index = this._attributesNames.indexOf(name);
  18513. return this._attributes[index];
  18514. };
  18515. Effect.prototype.getAttributesCount = function () {
  18516. return this._attributes.length;
  18517. };
  18518. Effect.prototype.getUniformIndex = function (uniformName) {
  18519. return this._uniformsNames.indexOf(uniformName);
  18520. };
  18521. Effect.prototype.getUniform = function (uniformName) {
  18522. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18523. };
  18524. Effect.prototype.getSamplers = function () {
  18525. return this._samplers;
  18526. };
  18527. Effect.prototype.getCompilationError = function () {
  18528. return this._compilationError;
  18529. };
  18530. // Methods
  18531. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18532. // DOM element ?
  18533. if (vertex instanceof HTMLElement) {
  18534. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18535. callback(vertexCode);
  18536. return;
  18537. }
  18538. // Is in local store ?
  18539. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18540. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18541. return;
  18542. }
  18543. var vertexShaderUrl;
  18544. if (vertex[0] === "." || vertex[0] === "/") {
  18545. vertexShaderUrl = vertex;
  18546. }
  18547. else {
  18548. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18549. }
  18550. // Vertex shader
  18551. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18552. };
  18553. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18554. // DOM element ?
  18555. if (fragment instanceof HTMLElement) {
  18556. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18557. callback(fragmentCode);
  18558. return;
  18559. }
  18560. // Is in local store ?
  18561. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18562. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18563. return;
  18564. }
  18565. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18566. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18567. return;
  18568. }
  18569. var fragmentShaderUrl;
  18570. if (fragment[0] === "." || fragment[0] === "/") {
  18571. fragmentShaderUrl = fragment;
  18572. }
  18573. else {
  18574. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18575. }
  18576. // Fragment shader
  18577. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18578. };
  18579. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18580. try {
  18581. var engine = this._engine;
  18582. if (!engine.getCaps().highPrecisionShaderSupported) {
  18583. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18584. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18585. }
  18586. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18587. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18588. this._attributes = engine.getAttributes(this._program, attributesNames);
  18589. for (var index = 0; index < this._samplers.length; index++) {
  18590. var sampler = this.getUniform(this._samplers[index]);
  18591. if (sampler == null) {
  18592. this._samplers.splice(index, 1);
  18593. index--;
  18594. }
  18595. }
  18596. engine.bindSamplers(this);
  18597. this._isReady = true;
  18598. if (this.onCompiled) {
  18599. this.onCompiled(this);
  18600. }
  18601. }
  18602. catch (e) {
  18603. // Is it a problem with precision?
  18604. if (e.message.indexOf("highp") !== -1) {
  18605. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18606. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18607. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18608. return;
  18609. }
  18610. // Let's go through fallbacks then
  18611. if (fallbacks && fallbacks.isMoreFallbacks) {
  18612. defines = fallbacks.reduce(defines);
  18613. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18614. }
  18615. else {
  18616. BABYLON.Tools.Error("Unable to compile effect: ");
  18617. if (this.name.vertexElement) {
  18618. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18619. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18620. }
  18621. else if (this.name.vertex) {
  18622. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18623. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18624. }
  18625. else {
  18626. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18627. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18628. }
  18629. BABYLON.Tools.Error("Defines: " + defines);
  18630. BABYLON.Tools.Error("Error: " + e.message);
  18631. this._compilationError = e.message;
  18632. if (this.onError) {
  18633. this.onError(this, this._compilationError);
  18634. }
  18635. }
  18636. }
  18637. };
  18638. Effect.prototype._bindTexture = function (channel, texture) {
  18639. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18640. };
  18641. Effect.prototype.setTexture = function (channel, texture) {
  18642. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18643. };
  18644. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18645. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18646. };
  18647. //public _cacheMatrix(uniformName, matrix) {
  18648. // if (!this._valueCache[uniformName]) {
  18649. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18650. // }
  18651. // for (var index = 0; index < 16; index++) {
  18652. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18653. // }
  18654. //};
  18655. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18656. if (!this._valueCache[uniformName]) {
  18657. this._valueCache[uniformName] = [x, y];
  18658. return;
  18659. }
  18660. this._valueCache[uniformName][0] = x;
  18661. this._valueCache[uniformName][1] = y;
  18662. };
  18663. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18664. if (!this._valueCache[uniformName]) {
  18665. this._valueCache[uniformName] = [x, y, z];
  18666. return;
  18667. }
  18668. this._valueCache[uniformName][0] = x;
  18669. this._valueCache[uniformName][1] = y;
  18670. this._valueCache[uniformName][2] = z;
  18671. };
  18672. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18673. if (!this._valueCache[uniformName]) {
  18674. this._valueCache[uniformName] = [x, y, z, w];
  18675. return;
  18676. }
  18677. this._valueCache[uniformName][0] = x;
  18678. this._valueCache[uniformName][1] = y;
  18679. this._valueCache[uniformName][2] = z;
  18680. this._valueCache[uniformName][3] = w;
  18681. };
  18682. Effect.prototype.setArray = function (uniformName, array) {
  18683. this._engine.setArray(this.getUniform(uniformName), array);
  18684. return this;
  18685. };
  18686. Effect.prototype.setArray2 = function (uniformName, array) {
  18687. this._engine.setArray2(this.getUniform(uniformName), array);
  18688. return this;
  18689. };
  18690. Effect.prototype.setArray3 = function (uniformName, array) {
  18691. this._engine.setArray3(this.getUniform(uniformName), array);
  18692. return this;
  18693. };
  18694. Effect.prototype.setArray4 = function (uniformName, array) {
  18695. this._engine.setArray4(this.getUniform(uniformName), array);
  18696. return this;
  18697. };
  18698. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18699. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18700. return this;
  18701. };
  18702. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18703. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18704. // return;
  18705. //this._cacheMatrix(uniformName, matrix);
  18706. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18707. return this;
  18708. };
  18709. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18710. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18711. return this;
  18712. };
  18713. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18714. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18715. return this;
  18716. };
  18717. Effect.prototype.setFloat = function (uniformName, value) {
  18718. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18719. return this;
  18720. this._valueCache[uniformName] = value;
  18721. this._engine.setFloat(this.getUniform(uniformName), value);
  18722. return this;
  18723. };
  18724. Effect.prototype.setBool = function (uniformName, bool) {
  18725. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18726. return this;
  18727. this._valueCache[uniformName] = bool;
  18728. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18729. return this;
  18730. };
  18731. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18732. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18733. return this;
  18734. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18735. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18736. return this;
  18737. };
  18738. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18739. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18740. return this;
  18741. this._cacheFloat2(uniformName, x, y);
  18742. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18743. return this;
  18744. };
  18745. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18746. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18747. return this;
  18748. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18749. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18750. return this;
  18751. };
  18752. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18753. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18754. return this;
  18755. this._cacheFloat3(uniformName, x, y, z);
  18756. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18757. return this;
  18758. };
  18759. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18760. 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)
  18761. return this;
  18762. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18763. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18764. return this;
  18765. };
  18766. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18767. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18768. return this;
  18769. this._cacheFloat4(uniformName, x, y, z, w);
  18770. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18771. return this;
  18772. };
  18773. Effect.prototype.setColor3 = function (uniformName, color3) {
  18774. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18775. return this;
  18776. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18777. this._engine.setColor3(this.getUniform(uniformName), color3);
  18778. return this;
  18779. };
  18780. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18781. 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)
  18782. return this;
  18783. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18784. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18785. return this;
  18786. };
  18787. // Statics
  18788. Effect.ShadersStore = {};
  18789. return Effect;
  18790. })();
  18791. BABYLON.Effect = Effect;
  18792. })(BABYLON || (BABYLON = {}));
  18793. var BABYLON;
  18794. (function (BABYLON) {
  18795. var Material = (function () {
  18796. function Material(name, scene, doNotAdd) {
  18797. this.name = name;
  18798. this.checkReadyOnEveryCall = true;
  18799. this.checkReadyOnlyOnce = false;
  18800. this.state = "";
  18801. this.alpha = 1.0;
  18802. this.backFaceCulling = true;
  18803. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18804. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18805. this.disableDepthWrite = false;
  18806. this.fogEnabled = true;
  18807. this._wasPreviouslyReady = false;
  18808. this._fillMode = Material.TriangleFillMode;
  18809. this.pointSize = 1.0;
  18810. this.zOffset = 0;
  18811. this.id = name;
  18812. this._scene = scene;
  18813. if (!doNotAdd) {
  18814. scene.materials.push(this);
  18815. }
  18816. }
  18817. Object.defineProperty(Material, "TriangleFillMode", {
  18818. get: function () {
  18819. return Material._TriangleFillMode;
  18820. },
  18821. enumerable: true,
  18822. configurable: true
  18823. });
  18824. Object.defineProperty(Material, "WireFrameFillMode", {
  18825. get: function () {
  18826. return Material._WireFrameFillMode;
  18827. },
  18828. enumerable: true,
  18829. configurable: true
  18830. });
  18831. Object.defineProperty(Material, "PointFillMode", {
  18832. get: function () {
  18833. return Material._PointFillMode;
  18834. },
  18835. enumerable: true,
  18836. configurable: true
  18837. });
  18838. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18839. get: function () {
  18840. return Material._ClockWiseSideOrientation;
  18841. },
  18842. enumerable: true,
  18843. configurable: true
  18844. });
  18845. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18846. get: function () {
  18847. return Material._CounterClockWiseSideOrientation;
  18848. },
  18849. enumerable: true,
  18850. configurable: true
  18851. });
  18852. Object.defineProperty(Material.prototype, "wireframe", {
  18853. get: function () {
  18854. return this._fillMode === Material.WireFrameFillMode;
  18855. },
  18856. set: function (value) {
  18857. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18858. },
  18859. enumerable: true,
  18860. configurable: true
  18861. });
  18862. Object.defineProperty(Material.prototype, "pointsCloud", {
  18863. get: function () {
  18864. return this._fillMode === Material.PointFillMode;
  18865. },
  18866. set: function (value) {
  18867. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18868. },
  18869. enumerable: true,
  18870. configurable: true
  18871. });
  18872. Object.defineProperty(Material.prototype, "fillMode", {
  18873. get: function () {
  18874. return this._fillMode;
  18875. },
  18876. set: function (value) {
  18877. this._fillMode = value;
  18878. },
  18879. enumerable: true,
  18880. configurable: true
  18881. });
  18882. Material.prototype.isReady = function (mesh, useInstances) {
  18883. return true;
  18884. };
  18885. Material.prototype.getEffect = function () {
  18886. return this._effect;
  18887. };
  18888. Material.prototype.getScene = function () {
  18889. return this._scene;
  18890. };
  18891. Material.prototype.needAlphaBlending = function () {
  18892. return (this.alpha < 1.0);
  18893. };
  18894. Material.prototype.needAlphaTesting = function () {
  18895. return false;
  18896. };
  18897. Material.prototype.getAlphaTestTexture = function () {
  18898. return null;
  18899. };
  18900. Material.prototype.trackCreation = function (onCompiled, onError) {
  18901. };
  18902. Material.prototype._preBind = function () {
  18903. var engine = this._scene.getEngine();
  18904. engine.enableEffect(this._effect);
  18905. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18906. };
  18907. Material.prototype.bind = function (world, mesh) {
  18908. this._scene._cachedMaterial = this;
  18909. if (this.onBind) {
  18910. this.onBind(this, mesh);
  18911. }
  18912. if (this.disableDepthWrite) {
  18913. var engine = this._scene.getEngine();
  18914. this._cachedDepthWriteState = engine.getDepthWrite();
  18915. engine.setDepthWrite(false);
  18916. }
  18917. };
  18918. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18919. };
  18920. Material.prototype.unbind = function () {
  18921. if (this.disableDepthWrite) {
  18922. var engine = this._scene.getEngine();
  18923. engine.setDepthWrite(this._cachedDepthWriteState);
  18924. }
  18925. };
  18926. Material.prototype.clone = function (name) {
  18927. return null;
  18928. };
  18929. Material.prototype.dispose = function (forceDisposeEffect) {
  18930. // Remove from scene
  18931. var index = this._scene.materials.indexOf(this);
  18932. if (index >= 0) {
  18933. this._scene.materials.splice(index, 1);
  18934. }
  18935. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18936. if (forceDisposeEffect && this._effect) {
  18937. this._scene.getEngine()._releaseEffect(this._effect);
  18938. this._effect = null;
  18939. }
  18940. // Remove from meshes
  18941. for (index = 0; index < this._scene.meshes.length; index++) {
  18942. var mesh = this._scene.meshes[index];
  18943. if (mesh.material === this) {
  18944. mesh.material = null;
  18945. }
  18946. }
  18947. // Callback
  18948. if (this.onDispose) {
  18949. this.onDispose();
  18950. }
  18951. };
  18952. Material.prototype.copyTo = function (other) {
  18953. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18954. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18955. other.alpha = this.alpha;
  18956. other.fillMode = this.fillMode;
  18957. other.backFaceCulling = this.backFaceCulling;
  18958. other.wireframe = this.wireframe;
  18959. other.fogEnabled = this.fogEnabled;
  18960. other.wireframe = this.wireframe;
  18961. other.zOffset = this.zOffset;
  18962. other.alphaMode = this.alphaMode;
  18963. other.sideOrientation = this.sideOrientation;
  18964. other.disableDepthWrite = this.disableDepthWrite;
  18965. other.pointSize = this.pointSize;
  18966. other.pointsCloud = this.pointsCloud;
  18967. };
  18968. Material._TriangleFillMode = 0;
  18969. Material._WireFrameFillMode = 1;
  18970. Material._PointFillMode = 2;
  18971. Material._ClockWiseSideOrientation = 0;
  18972. Material._CounterClockWiseSideOrientation = 1;
  18973. return Material;
  18974. })();
  18975. BABYLON.Material = Material;
  18976. })(BABYLON || (BABYLON = {}));
  18977. var BABYLON;
  18978. (function (BABYLON) {
  18979. var maxSimultaneousLights = 4;
  18980. var FresnelParameters = (function () {
  18981. function FresnelParameters() {
  18982. this.isEnabled = true;
  18983. this.leftColor = BABYLON.Color3.White();
  18984. this.rightColor = BABYLON.Color3.Black();
  18985. this.bias = 0;
  18986. this.power = 1;
  18987. }
  18988. FresnelParameters.prototype.clone = function () {
  18989. var newFresnelParameters = new FresnelParameters();
  18990. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18991. return new FresnelParameters;
  18992. };
  18993. return FresnelParameters;
  18994. })();
  18995. BABYLON.FresnelParameters = FresnelParameters;
  18996. var StandardMaterialDefines = (function () {
  18997. function StandardMaterialDefines() {
  18998. this.DIFFUSE = false;
  18999. this.AMBIENT = false;
  19000. this.OPACITY = false;
  19001. this.OPACITYRGB = false;
  19002. this.REFLECTION = false;
  19003. this.EMISSIVE = false;
  19004. this.SPECULAR = false;
  19005. this.BUMP = false;
  19006. this.SPECULAROVERALPHA = false;
  19007. this.CLIPPLANE = false;
  19008. this.ALPHATEST = false;
  19009. this.ALPHAFROMDIFFUSE = false;
  19010. this.POINTSIZE = false;
  19011. this.FOG = false;
  19012. this.LIGHT0 = false;
  19013. this.LIGHT1 = false;
  19014. this.LIGHT2 = false;
  19015. this.LIGHT3 = false;
  19016. this.SPOTLIGHT0 = false;
  19017. this.SPOTLIGHT1 = false;
  19018. this.SPOTLIGHT2 = false;
  19019. this.SPOTLIGHT3 = false;
  19020. this.HEMILIGHT0 = false;
  19021. this.HEMILIGHT1 = false;
  19022. this.HEMILIGHT2 = false;
  19023. this.HEMILIGHT3 = false;
  19024. this.POINTDIRLIGHT0 = false;
  19025. this.POINTDIRLIGHT1 = false;
  19026. this.POINTDIRLIGHT2 = false;
  19027. this.POINTDIRLIGHT3 = false;
  19028. this.SPECULARTERM = false;
  19029. this.SHADOW0 = false;
  19030. this.SHADOW1 = false;
  19031. this.SHADOW2 = false;
  19032. this.SHADOW3 = false;
  19033. this.SHADOWS = false;
  19034. this.SHADOWVSM0 = false;
  19035. this.SHADOWVSM1 = false;
  19036. this.SHADOWVSM2 = false;
  19037. this.SHADOWVSM3 = false;
  19038. this.SHADOWPCF0 = false;
  19039. this.SHADOWPCF1 = false;
  19040. this.SHADOWPCF2 = false;
  19041. this.SHADOWPCF3 = false;
  19042. this.DIFFUSEFRESNEL = false;
  19043. this.OPACITYFRESNEL = false;
  19044. this.REFLECTIONFRESNEL = false;
  19045. this.EMISSIVEFRESNEL = false;
  19046. this.FRESNEL = false;
  19047. this.NORMAL = false;
  19048. this.UV1 = false;
  19049. this.UV2 = false;
  19050. this.VERTEXCOLOR = false;
  19051. this.VERTEXALPHA = false;
  19052. this.BONES = false;
  19053. this.BONES4 = false;
  19054. this.BonesPerMesh = 0;
  19055. this.INSTANCES = false;
  19056. this.GLOSSINESS = false;
  19057. this.ROUGHNESS = false;
  19058. this.EMISSIVEASILLUMINATION = false;
  19059. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19060. this.LIGHTMAP = false;
  19061. this.INVERTCUBICMAP = false;
  19062. this._keys = Object.keys(this);
  19063. }
  19064. StandardMaterialDefines.prototype.isEqual = function (other) {
  19065. for (var index = 0; index < this._keys.length; index++) {
  19066. var prop = this._keys[index];
  19067. if (this[prop] !== other[prop]) {
  19068. return false;
  19069. }
  19070. }
  19071. return true;
  19072. };
  19073. StandardMaterialDefines.prototype.cloneTo = function (other) {
  19074. for (var index = 0; index < this._keys.length; index++) {
  19075. var prop = this._keys[index];
  19076. other[prop] = this[prop];
  19077. }
  19078. };
  19079. StandardMaterialDefines.prototype.reset = function () {
  19080. for (var index = 0; index < this._keys.length; index++) {
  19081. var prop = this._keys[index];
  19082. if (prop === "BonesPerMesh") {
  19083. this[prop] = 0;
  19084. continue;
  19085. }
  19086. this[prop] = false;
  19087. }
  19088. };
  19089. StandardMaterialDefines.prototype.toString = function () {
  19090. var result = "";
  19091. for (var index = 0; index < this._keys.length; index++) {
  19092. var prop = this._keys[index];
  19093. if (prop === "BonesPerMesh" && this[prop] > 0) {
  19094. result += "#define BonesPerMesh " + this[prop] + "\n";
  19095. continue;
  19096. }
  19097. if (this[prop]) {
  19098. result += "#define " + prop + "\n";
  19099. }
  19100. }
  19101. return result;
  19102. };
  19103. return StandardMaterialDefines;
  19104. })();
  19105. var StandardMaterial = (function (_super) {
  19106. __extends(StandardMaterial, _super);
  19107. function StandardMaterial(name, scene) {
  19108. var _this = this;
  19109. _super.call(this, name, scene);
  19110. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19111. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19112. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19113. this.specularPower = 64;
  19114. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19115. this.useAlphaFromDiffuseTexture = false;
  19116. this.useEmissiveAsIllumination = false;
  19117. this.useReflectionFresnelFromSpecular = false;
  19118. this.useSpecularOverAlpha = true;
  19119. this.roughness = 0;
  19120. this.lightmapThreshold = 0;
  19121. this.useGlossinessFromSpecularMapAlpha = false;
  19122. this._renderTargets = new BABYLON.SmartArray(16);
  19123. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19124. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19125. this._scaledDiffuse = new BABYLON.Color3();
  19126. this._scaledSpecular = new BABYLON.Color3();
  19127. this._defines = new StandardMaterialDefines();
  19128. this._cachedDefines = new StandardMaterialDefines();
  19129. this._cachedDefines.BonesPerMesh = -1;
  19130. this.getRenderTargetTextures = function () {
  19131. _this._renderTargets.reset();
  19132. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19133. _this._renderTargets.push(_this.reflectionTexture);
  19134. }
  19135. return _this._renderTargets;
  19136. };
  19137. }
  19138. StandardMaterial.prototype.needAlphaBlending = function () {
  19139. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19140. };
  19141. StandardMaterial.prototype.needAlphaTesting = function () {
  19142. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19143. };
  19144. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19145. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19146. };
  19147. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19148. return this.diffuseTexture;
  19149. };
  19150. // Methods
  19151. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19152. if (this.checkReadyOnlyOnce) {
  19153. if (this._wasPreviouslyReady) {
  19154. return true;
  19155. }
  19156. }
  19157. var scene = this.getScene();
  19158. if (!this.checkReadyOnEveryCall) {
  19159. if (this._renderId === scene.getRenderId()) {
  19160. return true;
  19161. }
  19162. }
  19163. var engine = scene.getEngine();
  19164. var needNormals = false;
  19165. var needUVs = false;
  19166. this._defines.reset();
  19167. // Textures
  19168. if (scene.texturesEnabled) {
  19169. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19170. if (!this.diffuseTexture.isReady()) {
  19171. return false;
  19172. }
  19173. else {
  19174. needUVs = true;
  19175. this._defines.DIFFUSE = true;
  19176. }
  19177. }
  19178. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19179. if (!this.ambientTexture.isReady()) {
  19180. return false;
  19181. }
  19182. else {
  19183. needUVs = true;
  19184. this._defines.AMBIENT = true;
  19185. }
  19186. }
  19187. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19188. if (!this.opacityTexture.isReady()) {
  19189. return false;
  19190. }
  19191. else {
  19192. needUVs = true;
  19193. this._defines.OPACITY = true;
  19194. if (this.opacityTexture.getAlphaFromRGB) {
  19195. this._defines.OPACITYRGB = true;
  19196. }
  19197. }
  19198. }
  19199. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19200. if (!this.reflectionTexture.isReady()) {
  19201. return false;
  19202. }
  19203. else {
  19204. needNormals = true;
  19205. needUVs = true;
  19206. this._defines.REFLECTION = true;
  19207. if (this.roughness > 0) {
  19208. this._defines.ROUGHNESS = true;
  19209. }
  19210. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19211. this._defines.INVERTCUBICMAP = true;
  19212. }
  19213. }
  19214. }
  19215. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19216. if (!this.emissiveTexture.isReady()) {
  19217. return false;
  19218. }
  19219. else {
  19220. needUVs = true;
  19221. this._defines.EMISSIVE = true;
  19222. }
  19223. }
  19224. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19225. if (!this.lightmapTexture.isReady()) {
  19226. return false;
  19227. }
  19228. else {
  19229. needUVs = true;
  19230. this._defines.LIGHTMAP = true;
  19231. }
  19232. }
  19233. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19234. if (!this.specularTexture.isReady()) {
  19235. return false;
  19236. }
  19237. else {
  19238. needUVs = true;
  19239. this._defines.SPECULAR = true;
  19240. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19241. }
  19242. }
  19243. }
  19244. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19245. if (!this.bumpTexture.isReady()) {
  19246. return false;
  19247. }
  19248. else {
  19249. needUVs = true;
  19250. this._defines.BUMP = true;
  19251. }
  19252. }
  19253. // Effect
  19254. if (scene.clipPlane) {
  19255. this._defines.CLIPPLANE = true;
  19256. }
  19257. if (engine.getAlphaTesting()) {
  19258. this._defines.ALPHATEST = true;
  19259. }
  19260. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19261. this._defines.ALPHAFROMDIFFUSE = true;
  19262. }
  19263. if (this.useEmissiveAsIllumination) {
  19264. this._defines.EMISSIVEASILLUMINATION = true;
  19265. }
  19266. if (this.useReflectionFresnelFromSpecular) {
  19267. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19268. }
  19269. // Point size
  19270. if (this.pointsCloud || scene.forcePointsCloud) {
  19271. this._defines.POINTSIZE = true;
  19272. }
  19273. // Fog
  19274. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19275. this._defines.FOG = true;
  19276. }
  19277. var lightIndex = 0;
  19278. if (scene.lightsEnabled) {
  19279. for (var index = 0; index < scene.lights.length; index++) {
  19280. var light = scene.lights[index];
  19281. if (!light.isEnabled()) {
  19282. continue;
  19283. }
  19284. // Excluded check
  19285. if (light._excludedMeshesIds.length > 0) {
  19286. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19287. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19288. if (excludedMesh) {
  19289. light.excludedMeshes.push(excludedMesh);
  19290. }
  19291. }
  19292. light._excludedMeshesIds = [];
  19293. }
  19294. // Included check
  19295. if (light._includedOnlyMeshesIds.length > 0) {
  19296. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19297. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19298. if (includedOnlyMesh) {
  19299. light.includedOnlyMeshes.push(includedOnlyMesh);
  19300. }
  19301. }
  19302. light._includedOnlyMeshesIds = [];
  19303. }
  19304. if (!light.canAffectMesh(mesh)) {
  19305. continue;
  19306. }
  19307. needNormals = true;
  19308. this._defines["LIGHT" + lightIndex] = true;
  19309. var type;
  19310. if (light instanceof BABYLON.SpotLight) {
  19311. type = "SPOTLIGHT" + lightIndex;
  19312. }
  19313. else if (light instanceof BABYLON.HemisphericLight) {
  19314. type = "HEMILIGHT" + lightIndex;
  19315. }
  19316. else {
  19317. type = "POINTDIRLIGHT" + lightIndex;
  19318. }
  19319. this._defines[type] = true;
  19320. // Specular
  19321. if (!light.specular.equalsFloats(0, 0, 0)) {
  19322. this._defines.SPECULARTERM = true;
  19323. }
  19324. // Shadows
  19325. if (scene.shadowsEnabled) {
  19326. var shadowGenerator = light.getShadowGenerator();
  19327. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19328. this._defines["SHADOW" + lightIndex] = true;
  19329. this._defines.SHADOWS = true;
  19330. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19331. this._defines["SHADOWVSM" + lightIndex] = true;
  19332. }
  19333. if (shadowGenerator.usePoissonSampling) {
  19334. this._defines["SHADOWPCF" + lightIndex] = true;
  19335. }
  19336. }
  19337. }
  19338. lightIndex++;
  19339. if (lightIndex === maxSimultaneousLights)
  19340. break;
  19341. }
  19342. }
  19343. if (StandardMaterial.FresnelEnabled) {
  19344. // Fresnel
  19345. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19346. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19347. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19348. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19349. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19350. this._defines.DIFFUSEFRESNEL = true;
  19351. }
  19352. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19353. this._defines.OPACITYFRESNEL = true;
  19354. }
  19355. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19356. this._defines.REFLECTIONFRESNEL = true;
  19357. }
  19358. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19359. this._defines.EMISSIVEFRESNEL = true;
  19360. }
  19361. needNormals = true;
  19362. this._defines.FRESNEL = true;
  19363. }
  19364. }
  19365. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19366. this._defines.SPECULAROVERALPHA = true;
  19367. }
  19368. // Attribs
  19369. if (mesh) {
  19370. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19371. this._defines.NORMAL = true;
  19372. }
  19373. if (needUVs) {
  19374. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19375. this._defines.UV1 = true;
  19376. }
  19377. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19378. this._defines.UV2 = true;
  19379. }
  19380. }
  19381. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19382. this._defines.VERTEXCOLOR = true;
  19383. if (mesh.hasVertexAlpha) {
  19384. this._defines.VERTEXALPHA = true;
  19385. }
  19386. }
  19387. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19388. this._defines.BONES = true;
  19389. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19390. this._defines.BONES4 = true;
  19391. }
  19392. // Instances
  19393. if (useInstances) {
  19394. this._defines.INSTANCES = true;
  19395. }
  19396. }
  19397. // Get correct effect
  19398. if (!this._defines.isEqual(this._cachedDefines)) {
  19399. this._defines.cloneTo(this._cachedDefines);
  19400. scene.resetCachedMaterial();
  19401. // Fallbacks
  19402. var fallbacks = new BABYLON.EffectFallbacks();
  19403. if (this._defines.REFLECTION) {
  19404. fallbacks.addFallback(0, "REFLECTION");
  19405. }
  19406. if (this._defines.SPECULAR) {
  19407. fallbacks.addFallback(0, "SPECULAR");
  19408. }
  19409. if (this._defines.BUMP) {
  19410. fallbacks.addFallback(0, "BUMP");
  19411. }
  19412. if (this._defines.SPECULAROVERALPHA) {
  19413. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19414. }
  19415. if (this._defines.FOG) {
  19416. fallbacks.addFallback(1, "FOG");
  19417. }
  19418. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19419. if (!this._defines["LIGHT" + lightIndex]) {
  19420. continue;
  19421. }
  19422. if (lightIndex > 0) {
  19423. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19424. }
  19425. if (this._defines["SHADOW" + lightIndex]) {
  19426. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19427. }
  19428. if (this._defines["SHADOWPCF" + lightIndex]) {
  19429. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19430. }
  19431. if (this._defines["SHADOWVSM" + lightIndex]) {
  19432. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19433. }
  19434. }
  19435. if (this._defines.SPECULARTERM) {
  19436. fallbacks.addFallback(0, "SPECULARTERM");
  19437. }
  19438. if (this._defines.DIFFUSEFRESNEL) {
  19439. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19440. }
  19441. if (this._defines.OPACITYFRESNEL) {
  19442. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19443. }
  19444. if (this._defines.REFLECTIONFRESNEL) {
  19445. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19446. }
  19447. if (this._defines.EMISSIVEFRESNEL) {
  19448. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19449. }
  19450. if (this._defines.FRESNEL) {
  19451. fallbacks.addFallback(4, "FRESNEL");
  19452. }
  19453. if (this._defines.BONES4) {
  19454. fallbacks.addFallback(0, "BONES4");
  19455. }
  19456. //Attributes
  19457. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19458. if (this._defines.NORMAL) {
  19459. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19460. }
  19461. if (this._defines.UV1) {
  19462. attribs.push(BABYLON.VertexBuffer.UVKind);
  19463. }
  19464. if (this._defines.UV2) {
  19465. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19466. }
  19467. if (this._defines.VERTEXCOLOR) {
  19468. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19469. }
  19470. if (this._defines.BONES) {
  19471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19473. }
  19474. if (this._defines.INSTANCES) {
  19475. attribs.push("world0");
  19476. attribs.push("world1");
  19477. attribs.push("world2");
  19478. attribs.push("world3");
  19479. }
  19480. // Legacy browser patch
  19481. var shaderName = "default";
  19482. if (!scene.getEngine().getCaps().standardDerivatives) {
  19483. shaderName = "legacydefault";
  19484. }
  19485. var join = this._defines.toString();
  19486. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19487. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19488. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19489. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19490. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19491. "vFogInfos", "vFogColor", "pointSize",
  19492. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19493. "mBones",
  19494. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19495. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19496. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19497. "roughness"
  19498. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19499. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19500. ], join, fallbacks, this.onCompiled, this.onError);
  19501. }
  19502. if (!this._effect.isReady()) {
  19503. return false;
  19504. }
  19505. this._renderId = scene.getRenderId();
  19506. this._wasPreviouslyReady = true;
  19507. return true;
  19508. };
  19509. StandardMaterial.prototype.unbind = function () {
  19510. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19511. this._effect.setTexture("reflection2DSampler", null);
  19512. }
  19513. _super.prototype.unbind.call(this);
  19514. };
  19515. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19516. this._effect.setMatrix("world", world);
  19517. };
  19518. StandardMaterial.prototype.bind = function (world, mesh) {
  19519. var scene = this.getScene();
  19520. // Matrices
  19521. this.bindOnlyWorldMatrix(world);
  19522. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19523. // Bones
  19524. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19525. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19526. }
  19527. if (scene.getCachedMaterial() !== this) {
  19528. if (StandardMaterial.FresnelEnabled) {
  19529. // Fresnel
  19530. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19531. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19532. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19533. }
  19534. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19535. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19536. }
  19537. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19538. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19539. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19540. }
  19541. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19542. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19543. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19544. }
  19545. }
  19546. // Textures
  19547. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19548. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19549. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19550. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19551. }
  19552. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19553. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19554. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19555. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19556. }
  19557. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19558. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19559. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19560. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19561. }
  19562. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19563. if (this.reflectionTexture.isCube) {
  19564. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19565. if (this._defines.ROUGHNESS) {
  19566. this._effect.setFloat("roughness", this.roughness);
  19567. }
  19568. }
  19569. else {
  19570. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19571. }
  19572. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19573. 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);
  19574. }
  19575. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19576. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19577. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19578. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19579. }
  19580. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19581. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19582. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  19583. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19584. }
  19585. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19586. this._effect.setTexture("specularSampler", this.specularTexture);
  19587. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19588. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19589. }
  19590. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19591. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19592. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19593. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19594. }
  19595. // Clip plane
  19596. if (scene.clipPlane) {
  19597. var clipPlane = scene.clipPlane;
  19598. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19599. }
  19600. // Point size
  19601. if (this.pointsCloud) {
  19602. this._effect.setFloat("pointSize", this.pointSize);
  19603. }
  19604. // Colors
  19605. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19606. // Scaling down color according to emissive
  19607. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19608. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19609. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19610. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19611. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19612. if (this._defines.SPECULARTERM) {
  19613. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19614. }
  19615. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19616. }
  19617. // Scaling down color according to emissive
  19618. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19619. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19620. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19621. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19622. if (scene.lightsEnabled) {
  19623. var lightIndex = 0;
  19624. for (var index = 0; index < scene.lights.length; index++) {
  19625. var light = scene.lights[index];
  19626. if (!light.isEnabled()) {
  19627. continue;
  19628. }
  19629. if (!light.canAffectMesh(mesh)) {
  19630. continue;
  19631. }
  19632. if (light instanceof BABYLON.PointLight) {
  19633. // Point Light
  19634. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19635. }
  19636. else if (light instanceof BABYLON.DirectionalLight) {
  19637. // Directional Light
  19638. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19639. }
  19640. else if (light instanceof BABYLON.SpotLight) {
  19641. // Spot Light
  19642. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19643. }
  19644. else if (light instanceof BABYLON.HemisphericLight) {
  19645. // Hemispheric Light
  19646. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19647. }
  19648. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19649. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19650. if (this._defines.SPECULARTERM) {
  19651. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19652. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19653. }
  19654. // Shadows
  19655. if (scene.shadowsEnabled) {
  19656. var shadowGenerator = light.getShadowGenerator();
  19657. if (mesh.receiveShadows && shadowGenerator) {
  19658. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19659. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19660. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19661. }
  19662. }
  19663. lightIndex++;
  19664. if (lightIndex === maxSimultaneousLights)
  19665. break;
  19666. }
  19667. }
  19668. // View
  19669. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19670. this._effect.setMatrix("view", scene.getViewMatrix());
  19671. }
  19672. // Fog
  19673. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19674. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19675. this._effect.setColor3("vFogColor", scene.fogColor);
  19676. }
  19677. _super.prototype.bind.call(this, world, mesh);
  19678. };
  19679. StandardMaterial.prototype.getAnimatables = function () {
  19680. var results = [];
  19681. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19682. results.push(this.diffuseTexture);
  19683. }
  19684. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19685. results.push(this.ambientTexture);
  19686. }
  19687. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19688. results.push(this.opacityTexture);
  19689. }
  19690. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19691. results.push(this.reflectionTexture);
  19692. }
  19693. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19694. results.push(this.emissiveTexture);
  19695. }
  19696. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19697. results.push(this.specularTexture);
  19698. }
  19699. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19700. results.push(this.bumpTexture);
  19701. }
  19702. return results;
  19703. };
  19704. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19705. if (this.diffuseTexture) {
  19706. this.diffuseTexture.dispose();
  19707. }
  19708. if (this.ambientTexture) {
  19709. this.ambientTexture.dispose();
  19710. }
  19711. if (this.opacityTexture) {
  19712. this.opacityTexture.dispose();
  19713. }
  19714. if (this.reflectionTexture) {
  19715. this.reflectionTexture.dispose();
  19716. }
  19717. if (this.emissiveTexture) {
  19718. this.emissiveTexture.dispose();
  19719. }
  19720. if (this.specularTexture) {
  19721. this.specularTexture.dispose();
  19722. }
  19723. if (this.bumpTexture) {
  19724. this.bumpTexture.dispose();
  19725. }
  19726. _super.prototype.dispose.call(this, forceDisposeEffect);
  19727. };
  19728. StandardMaterial.prototype.clone = function (name) {
  19729. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19730. // Base material
  19731. this.copyTo(newStandardMaterial);
  19732. // Standard material
  19733. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19734. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19735. }
  19736. if (this.ambientTexture && this.ambientTexture.clone) {
  19737. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19738. }
  19739. if (this.opacityTexture && this.opacityTexture.clone) {
  19740. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19741. }
  19742. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19743. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19744. }
  19745. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19746. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19747. }
  19748. if (this.specularTexture && this.specularTexture.clone) {
  19749. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19750. }
  19751. if (this.bumpTexture && this.bumpTexture.clone) {
  19752. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19753. }
  19754. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19755. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19756. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19757. newStandardMaterial.lightmapThreshold = this.lightmapThreshold;
  19758. }
  19759. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19760. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19761. newStandardMaterial.specularColor = this.specularColor.clone();
  19762. newStandardMaterial.specularPower = this.specularPower;
  19763. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19764. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19765. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19766. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19767. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19768. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19769. newStandardMaterial.roughness = this.roughness;
  19770. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19771. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19772. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19773. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19774. return newStandardMaterial;
  19775. };
  19776. // Statics
  19777. // Flags used to enable or disable a type of texture for all Standard Materials
  19778. StandardMaterial.DiffuseTextureEnabled = true;
  19779. StandardMaterial.AmbientTextureEnabled = true;
  19780. StandardMaterial.OpacityTextureEnabled = true;
  19781. StandardMaterial.ReflectionTextureEnabled = true;
  19782. StandardMaterial.EmissiveTextureEnabled = true;
  19783. StandardMaterial.SpecularTextureEnabled = true;
  19784. StandardMaterial.BumpTextureEnabled = true;
  19785. StandardMaterial.FresnelEnabled = true;
  19786. StandardMaterial.LightmapEnabled = true;
  19787. return StandardMaterial;
  19788. })(BABYLON.Material);
  19789. BABYLON.StandardMaterial = StandardMaterial;
  19790. })(BABYLON || (BABYLON = {}));
  19791. var BABYLON;
  19792. (function (BABYLON) {
  19793. var MultiMaterial = (function (_super) {
  19794. __extends(MultiMaterial, _super);
  19795. function MultiMaterial(name, scene) {
  19796. _super.call(this, name, scene, true);
  19797. this.subMaterials = new Array();
  19798. scene.multiMaterials.push(this);
  19799. }
  19800. // Properties
  19801. MultiMaterial.prototype.getSubMaterial = function (index) {
  19802. if (index < 0 || index >= this.subMaterials.length) {
  19803. return this.getScene().defaultMaterial;
  19804. }
  19805. return this.subMaterials[index];
  19806. };
  19807. // Methods
  19808. MultiMaterial.prototype.isReady = function (mesh) {
  19809. for (var index = 0; index < this.subMaterials.length; index++) {
  19810. var subMaterial = this.subMaterials[index];
  19811. if (subMaterial) {
  19812. if (!this.subMaterials[index].isReady(mesh)) {
  19813. return false;
  19814. }
  19815. }
  19816. }
  19817. return true;
  19818. };
  19819. MultiMaterial.prototype.clone = function (name) {
  19820. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19821. for (var index = 0; index < this.subMaterials.length; index++) {
  19822. var subMaterial = this.subMaterials[index];
  19823. newMultiMaterial.subMaterials.push(subMaterial);
  19824. }
  19825. return newMultiMaterial;
  19826. };
  19827. return MultiMaterial;
  19828. })(BABYLON.Material);
  19829. BABYLON.MultiMaterial = MultiMaterial;
  19830. })(BABYLON || (BABYLON = {}));
  19831. var BABYLON;
  19832. (function (BABYLON) {
  19833. var SceneLoader = (function () {
  19834. function SceneLoader() {
  19835. }
  19836. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19837. get: function () {
  19838. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19839. },
  19840. set: function (value) {
  19841. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19847. get: function () {
  19848. return SceneLoader._ShowLoadingScreen;
  19849. },
  19850. set: function (value) {
  19851. SceneLoader._ShowLoadingScreen = value;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19857. var dotPosition = sceneFilename.lastIndexOf(".");
  19858. var queryStringPosition = sceneFilename.indexOf("?");
  19859. if (queryStringPosition === -1) {
  19860. queryStringPosition = sceneFilename.length;
  19861. }
  19862. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19863. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19864. var plugin = this._registeredPlugins[index];
  19865. if (plugin.extensions.indexOf(extension) !== -1) {
  19866. return plugin;
  19867. }
  19868. }
  19869. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19870. };
  19871. // Public functions
  19872. SceneLoader.RegisterPlugin = function (plugin) {
  19873. plugin.extensions = plugin.extensions.toLowerCase();
  19874. SceneLoader._registeredPlugins.push(plugin);
  19875. };
  19876. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19877. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19878. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19879. return;
  19880. }
  19881. var loadingToken = {};
  19882. scene._addPendingData(loadingToken);
  19883. var manifestChecked = function (success) {
  19884. scene.database = database;
  19885. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19886. var importMeshFromData = function (data) {
  19887. var meshes = [];
  19888. var particleSystems = [];
  19889. var skeletons = [];
  19890. try {
  19891. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19892. if (onerror) {
  19893. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19894. }
  19895. scene._removePendingData(loadingToken);
  19896. return;
  19897. }
  19898. }
  19899. catch (e) {
  19900. if (onerror) {
  19901. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19902. }
  19903. scene._removePendingData(loadingToken);
  19904. return;
  19905. }
  19906. if (onsuccess) {
  19907. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19908. onsuccess(meshes, particleSystems, skeletons);
  19909. scene._removePendingData(loadingToken);
  19910. }
  19911. };
  19912. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19913. // Direct load
  19914. importMeshFromData(sceneFilename.substr(5));
  19915. return;
  19916. }
  19917. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19918. importMeshFromData(data);
  19919. }, progressCallBack, database);
  19920. };
  19921. if (scene.getEngine().enableOfflineSupport) {
  19922. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19923. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19924. }
  19925. else {
  19926. manifestChecked(true);
  19927. }
  19928. };
  19929. /**
  19930. * Load a scene
  19931. * @param rootUrl a string that defines the root url for scene and resources
  19932. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19933. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19934. */
  19935. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19936. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19937. };
  19938. /**
  19939. * Append a scene
  19940. * @param rootUrl a string that defines the root url for scene and resources
  19941. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19942. * @param scene is the instance of BABYLON.Scene to append to
  19943. */
  19944. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19945. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19946. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19947. return;
  19948. }
  19949. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19950. var database;
  19951. var loadingToken = {};
  19952. scene._addPendingData(loadingToken);
  19953. if (SceneLoader.ShowLoadingScreen) {
  19954. scene.getEngine().displayLoadingUI();
  19955. }
  19956. var loadSceneFromData = function (data) {
  19957. scene.database = database;
  19958. if (!plugin.load(scene, data, rootUrl)) {
  19959. if (onerror) {
  19960. onerror(scene);
  19961. }
  19962. scene._removePendingData(loadingToken);
  19963. scene.getEngine().hideLoadingUI();
  19964. return;
  19965. }
  19966. if (onsuccess) {
  19967. onsuccess(scene);
  19968. }
  19969. scene._removePendingData(loadingToken);
  19970. if (SceneLoader.ShowLoadingScreen) {
  19971. scene.executeWhenReady(function () {
  19972. scene.getEngine().hideLoadingUI();
  19973. });
  19974. }
  19975. };
  19976. var manifestChecked = function (success) {
  19977. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19978. };
  19979. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19980. // Direct load
  19981. loadSceneFromData(sceneFilename.substr(5));
  19982. return;
  19983. }
  19984. if (rootUrl.indexOf("file:") === -1) {
  19985. if (scene.getEngine().enableOfflineSupport) {
  19986. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19987. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19988. }
  19989. else {
  19990. manifestChecked(true);
  19991. }
  19992. }
  19993. else {
  19994. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19995. }
  19996. };
  19997. // Flags
  19998. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19999. SceneLoader._ShowLoadingScreen = true;
  20000. // Members
  20001. SceneLoader._registeredPlugins = new Array();
  20002. return SceneLoader;
  20003. })();
  20004. BABYLON.SceneLoader = SceneLoader;
  20005. ;
  20006. })(BABYLON || (BABYLON = {}));
  20007. var BABYLON;
  20008. (function (BABYLON) {
  20009. var Internals;
  20010. (function (Internals) {
  20011. var checkColors4 = function (colors, count) {
  20012. // Check if color3 was used
  20013. if (colors.length === count * 3) {
  20014. var colors4 = [];
  20015. for (var index = 0; index < colors.length; index += 3) {
  20016. var newIndex = (index / 3) * 4;
  20017. colors4[newIndex] = colors[index];
  20018. colors4[newIndex + 1] = colors[index + 1];
  20019. colors4[newIndex + 2] = colors[index + 2];
  20020. colors4[newIndex + 3] = 1.0;
  20021. }
  20022. return colors4;
  20023. }
  20024. return colors;
  20025. };
  20026. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  20027. var texture = null;
  20028. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  20029. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20030. texture.name = parsedTexture.name;
  20031. texture.hasAlpha = parsedTexture.hasAlpha;
  20032. texture.level = parsedTexture.level;
  20033. texture.coordinatesMode = parsedTexture.coordinatesMode;
  20034. }
  20035. return texture;
  20036. };
  20037. var loadTexture = function (rootUrl, parsedTexture, scene) {
  20038. if (parsedTexture.isCube) {
  20039. return loadCubeTexture(rootUrl, parsedTexture, scene);
  20040. }
  20041. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20042. return null;
  20043. }
  20044. var texture;
  20045. if (parsedTexture.mirrorPlane) {
  20046. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20047. texture._waitingRenderList = parsedTexture.renderList;
  20048. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20049. }
  20050. else if (parsedTexture.isRenderTarget) {
  20051. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20052. texture._waitingRenderList = parsedTexture.renderList;
  20053. }
  20054. else {
  20055. if (parsedTexture.base64String) {
  20056. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20057. }
  20058. else {
  20059. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  20060. }
  20061. }
  20062. texture.name = parsedTexture.name;
  20063. texture.hasAlpha = parsedTexture.hasAlpha;
  20064. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  20065. texture.level = parsedTexture.level;
  20066. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  20067. texture.coordinatesMode = parsedTexture.coordinatesMode;
  20068. texture.uOffset = parsedTexture.uOffset;
  20069. texture.vOffset = parsedTexture.vOffset;
  20070. texture.uScale = parsedTexture.uScale;
  20071. texture.vScale = parsedTexture.vScale;
  20072. texture.uAng = parsedTexture.uAng;
  20073. texture.vAng = parsedTexture.vAng;
  20074. texture.wAng = parsedTexture.wAng;
  20075. texture.wrapU = parsedTexture.wrapU;
  20076. texture.wrapV = parsedTexture.wrapV;
  20077. // Animations
  20078. if (parsedTexture.animations) {
  20079. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20080. var parsedAnimation = parsedTexture.animations[animationIndex];
  20081. texture.animations.push(parseAnimation(parsedAnimation));
  20082. }
  20083. }
  20084. return texture;
  20085. };
  20086. var parseSkeleton = function (parsedSkeleton, scene) {
  20087. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  20088. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  20089. var parsedBone = parsedSkeleton.bones[index];
  20090. var parentBone = null;
  20091. if (parsedBone.parentBoneIndex > -1) {
  20092. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  20093. }
  20094. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  20095. if (parsedBone.animation) {
  20096. bone.animations.push(parseAnimation(parsedBone.animation));
  20097. }
  20098. }
  20099. return skeleton;
  20100. };
  20101. var parseFresnelParameters = function (parsedFresnelParameters) {
  20102. var fresnelParameters = new BABYLON.FresnelParameters();
  20103. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  20104. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  20105. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  20106. fresnelParameters.bias = parsedFresnelParameters.bias;
  20107. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  20108. return fresnelParameters;
  20109. };
  20110. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  20111. var material;
  20112. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  20113. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  20114. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  20115. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  20116. material.specularPower = parsedMaterial.specularPower;
  20117. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  20118. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  20119. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  20120. material.alpha = parsedMaterial.alpha;
  20121. material.id = parsedMaterial.id;
  20122. if (parsedMaterial.disableDepthWrite) {
  20123. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  20124. }
  20125. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  20126. material.backFaceCulling = parsedMaterial.backFaceCulling;
  20127. material.wireframe = parsedMaterial.wireframe;
  20128. if (parsedMaterial.diffuseTexture) {
  20129. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  20130. }
  20131. if (parsedMaterial.diffuseFresnelParameters) {
  20132. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  20133. }
  20134. if (parsedMaterial.ambientTexture) {
  20135. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  20136. }
  20137. if (parsedMaterial.opacityTexture) {
  20138. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  20139. }
  20140. if (parsedMaterial.opacityFresnelParameters) {
  20141. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  20142. }
  20143. if (parsedMaterial.reflectionTexture) {
  20144. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  20145. }
  20146. if (parsedMaterial.reflectionFresnelParameters) {
  20147. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  20148. }
  20149. if (parsedMaterial.emissiveTexture) {
  20150. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  20151. }
  20152. if (parsedMaterial.lightmapTexture) {
  20153. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  20154. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  20155. }
  20156. if (parsedMaterial.emissiveFresnelParameters) {
  20157. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  20158. }
  20159. if (parsedMaterial.specularTexture) {
  20160. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  20161. }
  20162. if (parsedMaterial.bumpTexture) {
  20163. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  20164. }
  20165. if (parsedMaterial.checkReadyOnlyOnce) {
  20166. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  20167. }
  20168. return material;
  20169. };
  20170. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20171. for (var index = 0; index < parsedData.materials.length; index++) {
  20172. var parsedMaterial = parsedData.materials[index];
  20173. if (parsedMaterial.id === id) {
  20174. return parseMaterial(parsedMaterial, scene, rootUrl);
  20175. }
  20176. }
  20177. return null;
  20178. };
  20179. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  20180. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  20181. multiMaterial.id = parsedMultiMaterial.id;
  20182. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  20183. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20184. var subMatId = parsedMultiMaterial.materials[matIndex];
  20185. if (subMatId) {
  20186. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  20187. }
  20188. else {
  20189. multiMaterial.subMaterials.push(null);
  20190. }
  20191. }
  20192. return multiMaterial;
  20193. };
  20194. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  20195. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  20196. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  20197. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  20198. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  20199. var parsedFlare = parsedLensFlareSystem.flares[index];
  20200. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  20201. }
  20202. return lensFlareSystem;
  20203. };
  20204. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  20205. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  20206. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  20207. if (parsedParticleSystem.textureName) {
  20208. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  20209. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  20210. }
  20211. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  20212. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  20213. particleSystem.minSize = parsedParticleSystem.minSize;
  20214. particleSystem.maxSize = parsedParticleSystem.maxSize;
  20215. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  20216. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  20217. particleSystem.emitter = emitter;
  20218. particleSystem.emitRate = parsedParticleSystem.emitRate;
  20219. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  20220. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  20221. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  20222. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  20223. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  20224. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  20225. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  20226. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  20227. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  20228. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  20229. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  20230. particleSystem.blendMode = parsedParticleSystem.blendMode;
  20231. particleSystem.start();
  20232. return particleSystem;
  20233. };
  20234. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  20235. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  20236. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  20237. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  20238. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  20239. shadowGenerator.getShadowMap().renderList.push(mesh);
  20240. }
  20241. if (parsedShadowGenerator.usePoissonSampling) {
  20242. shadowGenerator.usePoissonSampling = true;
  20243. }
  20244. else if (parsedShadowGenerator.useVarianceShadowMap) {
  20245. shadowGenerator.useVarianceShadowMap = true;
  20246. }
  20247. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  20248. shadowGenerator.useBlurVarianceShadowMap = true;
  20249. if (parsedShadowGenerator.blurScale) {
  20250. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  20251. }
  20252. if (parsedShadowGenerator.blurBoxOffset) {
  20253. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  20254. }
  20255. }
  20256. if (parsedShadowGenerator.bias !== undefined) {
  20257. shadowGenerator.bias = parsedShadowGenerator.bias;
  20258. }
  20259. return shadowGenerator;
  20260. };
  20261. var parseAnimation = function (parsedAnimation) {
  20262. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  20263. var dataType = parsedAnimation.dataType;
  20264. var keys = [];
  20265. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  20266. var key = parsedAnimation.keys[index];
  20267. var data;
  20268. switch (dataType) {
  20269. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  20270. data = key.values[0];
  20271. break;
  20272. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  20273. data = BABYLON.Quaternion.FromArray(key.values);
  20274. break;
  20275. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  20276. data = BABYLON.Matrix.FromArray(key.values);
  20277. break;
  20278. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  20279. default:
  20280. data = BABYLON.Vector3.FromArray(key.values);
  20281. break;
  20282. }
  20283. keys.push({
  20284. frame: key.frame,
  20285. value: data
  20286. });
  20287. }
  20288. animation.setKeys(keys);
  20289. return animation;
  20290. };
  20291. var parseLight = function (parsedLight, scene) {
  20292. var light;
  20293. switch (parsedLight.type) {
  20294. case 0:
  20295. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  20296. break;
  20297. case 1:
  20298. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20299. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  20300. break;
  20301. case 2:
  20302. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  20303. break;
  20304. case 3:
  20305. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20306. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  20307. break;
  20308. }
  20309. light.id = parsedLight.id;
  20310. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  20311. if (parsedLight.intensity !== undefined) {
  20312. light.intensity = parsedLight.intensity;
  20313. }
  20314. if (parsedLight.range) {
  20315. light.range = parsedLight.range;
  20316. }
  20317. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  20318. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  20319. if (parsedLight.excludedMeshesIds) {
  20320. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20321. }
  20322. // Parent
  20323. if (parsedLight.parentId) {
  20324. light._waitingParentId = parsedLight.parentId;
  20325. }
  20326. if (parsedLight.includedOnlyMeshesIds) {
  20327. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20328. }
  20329. // Animations
  20330. if (parsedLight.animations) {
  20331. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20332. var parsedAnimation = parsedLight.animations[animationIndex];
  20333. light.animations.push(parseAnimation(parsedAnimation));
  20334. }
  20335. }
  20336. if (parsedLight.autoAnimate) {
  20337. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  20338. }
  20339. };
  20340. var parseCamera = function (parsedCamera, scene) {
  20341. var camera;
  20342. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20343. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20344. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20345. var alpha = parsedCamera.alpha;
  20346. var beta = parsedCamera.beta;
  20347. var radius = parsedCamera.radius;
  20348. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20349. var interaxial_distance = parsedCamera.interaxial_distance;
  20350. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  20351. }
  20352. else {
  20353. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20354. }
  20355. }
  20356. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20357. interaxial_distance = parsedCamera.interaxial_distance;
  20358. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  20359. }
  20360. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20361. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20362. }
  20363. else if (parsedCamera.type === "FollowCamera") {
  20364. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20365. camera.heightOffset = parsedCamera.heightOffset;
  20366. camera.radius = parsedCamera.radius;
  20367. camera.rotationOffset = parsedCamera.rotationOffset;
  20368. if (lockedTargetMesh)
  20369. camera.target = lockedTargetMesh;
  20370. }
  20371. else if (parsedCamera.type === "GamepadCamera") {
  20372. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20373. }
  20374. else if (parsedCamera.type === "TouchCamera") {
  20375. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20376. }
  20377. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20378. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20379. }
  20380. else if (parsedCamera.type === "WebVRFreeCamera") {
  20381. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  20382. }
  20383. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  20384. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  20385. }
  20386. else {
  20387. // Free Camera is the default value
  20388. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20389. }
  20390. // apply 3d rig, when found
  20391. if (parsedCamera.cameraRigMode) {
  20392. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20393. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20394. }
  20395. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20396. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20397. camera.lockedTarget = lockedTargetMesh;
  20398. }
  20399. camera.id = parsedCamera.id;
  20400. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20401. // Parent
  20402. if (parsedCamera.parentId) {
  20403. camera._waitingParentId = parsedCamera.parentId;
  20404. }
  20405. // Target
  20406. if (parsedCamera.target) {
  20407. if (camera.setTarget) {
  20408. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20409. }
  20410. else {
  20411. //For ArcRotate
  20412. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20413. }
  20414. }
  20415. else {
  20416. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20417. }
  20418. camera.fov = parsedCamera.fov;
  20419. camera.minZ = parsedCamera.minZ;
  20420. camera.maxZ = parsedCamera.maxZ;
  20421. camera.speed = parsedCamera.speed;
  20422. camera.inertia = parsedCamera.inertia;
  20423. camera.checkCollisions = parsedCamera.checkCollisions;
  20424. camera.applyGravity = parsedCamera.applyGravity;
  20425. if (parsedCamera.ellipsoid) {
  20426. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20427. }
  20428. // Animations
  20429. if (parsedCamera.animations) {
  20430. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20431. var parsedAnimation = parsedCamera.animations[animationIndex];
  20432. camera.animations.push(parseAnimation(parsedAnimation));
  20433. }
  20434. }
  20435. if (parsedCamera.autoAnimate) {
  20436. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20437. }
  20438. // Layer Mask
  20439. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20440. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20441. }
  20442. else {
  20443. camera.layerMask = 0x0FFFFFFF;
  20444. }
  20445. return camera;
  20446. };
  20447. var parseGeometry = function (parsedGeometry, scene) {
  20448. var id = parsedGeometry.id;
  20449. return scene.getGeometryByID(id);
  20450. };
  20451. var parseBox = function (parsedBox, scene) {
  20452. if (parseGeometry(parsedBox, scene)) {
  20453. return null; // null since geometry could be something else than a box...
  20454. }
  20455. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20456. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20457. scene.pushGeometry(box, true);
  20458. return box;
  20459. };
  20460. var parseSphere = function (parsedSphere, scene) {
  20461. if (parseGeometry(parsedSphere, scene)) {
  20462. return null; // null since geometry could be something else than a sphere...
  20463. }
  20464. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20465. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20466. scene.pushGeometry(sphere, true);
  20467. return sphere;
  20468. };
  20469. var parseCylinder = function (parsedCylinder, scene) {
  20470. if (parseGeometry(parsedCylinder, scene)) {
  20471. return null; // null since geometry could be something else than a cylinder...
  20472. }
  20473. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20474. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20475. scene.pushGeometry(cylinder, true);
  20476. return cylinder;
  20477. };
  20478. var parseTorus = function (parsedTorus, scene) {
  20479. if (parseGeometry(parsedTorus, scene)) {
  20480. return null; // null since geometry could be something else than a torus...
  20481. }
  20482. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20483. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20484. scene.pushGeometry(torus, true);
  20485. return torus;
  20486. };
  20487. var parseGround = function (parsedGround, scene) {
  20488. if (parseGeometry(parsedGround, scene)) {
  20489. return null; // null since geometry could be something else than a ground...
  20490. }
  20491. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20492. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20493. scene.pushGeometry(ground, true);
  20494. return ground;
  20495. };
  20496. var parsePlane = function (parsedPlane, scene) {
  20497. if (parseGeometry(parsedPlane, scene)) {
  20498. return null; // null since geometry could be something else than a plane...
  20499. }
  20500. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20501. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20502. scene.pushGeometry(plane, true);
  20503. return plane;
  20504. };
  20505. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20506. if (parseGeometry(parsedTorusKnot, scene)) {
  20507. return null; // null since geometry could be something else than a torusKnot...
  20508. }
  20509. 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);
  20510. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20511. scene.pushGeometry(torusKnot, true);
  20512. return torusKnot;
  20513. };
  20514. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20515. if (parseGeometry(parsedVertexData, scene)) {
  20516. return null; // null since geometry could be a primitive
  20517. }
  20518. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20519. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20520. if (parsedVertexData.delayLoadingFile) {
  20521. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20522. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20523. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20524. geometry._delayInfo = [];
  20525. if (parsedVertexData.hasUVs) {
  20526. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20527. }
  20528. if (parsedVertexData.hasUVs2) {
  20529. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20530. }
  20531. if (parsedVertexData.hasUVs3) {
  20532. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20533. }
  20534. if (parsedVertexData.hasUVs4) {
  20535. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20536. }
  20537. if (parsedVertexData.hasUVs5) {
  20538. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20539. }
  20540. if (parsedVertexData.hasUVs6) {
  20541. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20542. }
  20543. if (parsedVertexData.hasColors) {
  20544. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20545. }
  20546. if (parsedVertexData.hasMatricesIndices) {
  20547. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20548. }
  20549. if (parsedVertexData.hasMatricesWeights) {
  20550. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20551. }
  20552. geometry._delayLoadingFunction = importVertexData;
  20553. }
  20554. else {
  20555. importVertexData(parsedVertexData, geometry);
  20556. }
  20557. scene.pushGeometry(geometry, true);
  20558. return geometry;
  20559. };
  20560. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20561. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20562. mesh.id = parsedMesh.id;
  20563. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20564. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20565. if (parsedMesh.rotationQuaternion) {
  20566. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20567. }
  20568. else if (parsedMesh.rotation) {
  20569. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20570. }
  20571. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20572. if (parsedMesh.localMatrix) {
  20573. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20574. }
  20575. else if (parsedMesh.pivotMatrix) {
  20576. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20577. }
  20578. mesh.setEnabled(parsedMesh.isEnabled);
  20579. mesh.isVisible = parsedMesh.isVisible;
  20580. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20581. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20582. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20583. if (parsedMesh.applyFog !== undefined) {
  20584. mesh.applyFog = parsedMesh.applyFog;
  20585. }
  20586. if (parsedMesh.pickable !== undefined) {
  20587. mesh.isPickable = parsedMesh.pickable;
  20588. }
  20589. if (parsedMesh.alphaIndex !== undefined) {
  20590. mesh.alphaIndex = parsedMesh.alphaIndex;
  20591. }
  20592. mesh.receiveShadows = parsedMesh.receiveShadows;
  20593. mesh.billboardMode = parsedMesh.billboardMode;
  20594. if (parsedMesh.visibility !== undefined) {
  20595. mesh.visibility = parsedMesh.visibility;
  20596. }
  20597. mesh.checkCollisions = parsedMesh.checkCollisions;
  20598. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20599. // freezeWorldMatrix
  20600. if (parsedMesh.freezeWorldMatrix) {
  20601. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20602. }
  20603. // Parent
  20604. if (parsedMesh.parentId) {
  20605. mesh._waitingParentId = parsedMesh.parentId;
  20606. }
  20607. // Actions
  20608. if (parsedMesh.actions !== undefined) {
  20609. mesh._waitingActions = parsedMesh.actions;
  20610. }
  20611. // Geometry
  20612. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20613. if (parsedMesh.delayLoadingFile) {
  20614. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20615. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20616. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20617. if (parsedMesh._binaryInfo) {
  20618. mesh._binaryInfo = parsedMesh._binaryInfo;
  20619. }
  20620. mesh._delayInfo = [];
  20621. if (parsedMesh.hasUVs) {
  20622. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20623. }
  20624. if (parsedMesh.hasUVs2) {
  20625. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20626. }
  20627. if (parsedMesh.hasUVs3) {
  20628. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20629. }
  20630. if (parsedMesh.hasUVs4) {
  20631. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20632. }
  20633. if (parsedMesh.hasUVs5) {
  20634. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20635. }
  20636. if (parsedMesh.hasUVs6) {
  20637. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20638. }
  20639. if (parsedMesh.hasColors) {
  20640. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20641. }
  20642. if (parsedMesh.hasMatricesIndices) {
  20643. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20644. }
  20645. if (parsedMesh.hasMatricesWeights) {
  20646. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20647. }
  20648. mesh._delayLoadingFunction = importGeometry;
  20649. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20650. mesh._checkDelayState();
  20651. }
  20652. }
  20653. else {
  20654. importGeometry(parsedMesh, mesh);
  20655. }
  20656. // Material
  20657. if (parsedMesh.materialId) {
  20658. mesh.setMaterialByID(parsedMesh.materialId);
  20659. }
  20660. else {
  20661. mesh.material = null;
  20662. }
  20663. // Skeleton
  20664. if (parsedMesh.skeletonId > -1) {
  20665. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20666. }
  20667. // Physics
  20668. if (parsedMesh.physicsImpostor) {
  20669. if (!scene.isPhysicsEnabled()) {
  20670. scene.enablePhysics();
  20671. }
  20672. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20673. }
  20674. // Animations
  20675. if (parsedMesh.animations) {
  20676. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20677. var parsedAnimation = parsedMesh.animations[animationIndex];
  20678. mesh.animations.push(parseAnimation(parsedAnimation));
  20679. }
  20680. }
  20681. if (parsedMesh.autoAnimate) {
  20682. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20683. }
  20684. // Layer Mask
  20685. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20686. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20687. }
  20688. else {
  20689. mesh.layerMask = 0x0FFFFFFF;
  20690. }
  20691. // Instances
  20692. if (parsedMesh.instances) {
  20693. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20694. var parsedInstance = parsedMesh.instances[index];
  20695. var instance = mesh.createInstance(parsedInstance.name);
  20696. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20697. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20698. if (parsedInstance.rotationQuaternion) {
  20699. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20700. }
  20701. else if (parsedInstance.rotation) {
  20702. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20703. }
  20704. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20705. instance.checkCollisions = mesh.checkCollisions;
  20706. if (parsedMesh.animations) {
  20707. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20708. parsedAnimation = parsedMesh.animations[animationIndex];
  20709. instance.animations.push(parseAnimation(parsedAnimation));
  20710. }
  20711. }
  20712. }
  20713. }
  20714. return mesh;
  20715. };
  20716. var parseActions = function (parsedActions, object, scene) {
  20717. var actionManager = new BABYLON.ActionManager(scene);
  20718. if (object === null)
  20719. scene.actionManager = actionManager;
  20720. else
  20721. object.actionManager = actionManager;
  20722. // instanciate a new object
  20723. var instanciate = function (name, params) {
  20724. var newInstance = Object.create(BABYLON[name].prototype);
  20725. newInstance.constructor.apply(newInstance, params);
  20726. return newInstance;
  20727. };
  20728. var parseParameter = function (name, value, target, propertyPath) {
  20729. if (propertyPath === null) {
  20730. // String, boolean or float
  20731. var floatValue = parseFloat(value);
  20732. if (value === "true" || value === "false")
  20733. return value === "true";
  20734. else
  20735. return isNaN(floatValue) ? value : floatValue;
  20736. }
  20737. var effectiveTarget = propertyPath.split(".");
  20738. var values = value.split(",");
  20739. // Get effective Target
  20740. for (var i = 0; i < effectiveTarget.length; i++) {
  20741. target = target[effectiveTarget[i]];
  20742. }
  20743. // Return appropriate value with its type
  20744. if (typeof (target) === "boolean")
  20745. return values[0] === "true";
  20746. if (typeof (target) === "string")
  20747. return values[0];
  20748. // Parameters with multiple values such as Vector3 etc.
  20749. var split = new Array();
  20750. for (var i = 0; i < values.length; i++)
  20751. split.push(parseFloat(values[i]));
  20752. if (target instanceof BABYLON.Vector3)
  20753. return BABYLON.Vector3.FromArray(split);
  20754. if (target instanceof BABYLON.Vector4)
  20755. return BABYLON.Vector4.FromArray(split);
  20756. if (target instanceof BABYLON.Color3)
  20757. return BABYLON.Color3.FromArray(split);
  20758. if (target instanceof BABYLON.Color4)
  20759. return BABYLON.Color4.FromArray(split);
  20760. return parseFloat(values[0]);
  20761. };
  20762. // traverse graph per trigger
  20763. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20764. if (combineArray === void 0) { combineArray = null; }
  20765. if (parsedAction.detached)
  20766. return;
  20767. var parameters = new Array();
  20768. var target = null;
  20769. var propertyPath = null;
  20770. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20771. // Parameters
  20772. if (parsedAction.type === 2)
  20773. parameters.push(actionManager);
  20774. else
  20775. parameters.push(trigger);
  20776. if (combine) {
  20777. var actions = new Array();
  20778. for (var j = 0; j < parsedAction.combine.length; j++) {
  20779. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20780. }
  20781. parameters.push(actions);
  20782. }
  20783. else {
  20784. for (var i = 0; i < parsedAction.properties.length; i++) {
  20785. var value = parsedAction.properties[i].value;
  20786. var name = parsedAction.properties[i].name;
  20787. var targetType = parsedAction.properties[i].targetType;
  20788. if (name === "target")
  20789. if (targetType !== null && targetType === "SceneProperties")
  20790. value = target = scene;
  20791. else
  20792. value = target = scene.getNodeByName(value);
  20793. else if (name === "parent")
  20794. value = scene.getNodeByName(value);
  20795. else if (name === "sound")
  20796. value = scene.getSoundByName(value);
  20797. else if (name !== "propertyPath") {
  20798. if (parsedAction.type === 2 && name === "operator")
  20799. value = BABYLON.ValueCondition[value];
  20800. else
  20801. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20802. }
  20803. else {
  20804. propertyPath = value;
  20805. }
  20806. parameters.push(value);
  20807. }
  20808. }
  20809. if (combineArray === null) {
  20810. parameters.push(condition);
  20811. }
  20812. else {
  20813. parameters.push(null);
  20814. }
  20815. // If interpolate value action
  20816. if (parsedAction.name === "InterpolateValueAction") {
  20817. var param = parameters[parameters.length - 2];
  20818. parameters[parameters.length - 1] = param;
  20819. parameters[parameters.length - 2] = condition;
  20820. }
  20821. // Action or condition(s) and not CombineAction
  20822. var newAction = instanciate(parsedAction.name, parameters);
  20823. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20824. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20825. if (action)
  20826. action.then(nothing);
  20827. else
  20828. actionManager.registerAction(nothing);
  20829. action = nothing;
  20830. }
  20831. if (combineArray === null) {
  20832. if (newAction instanceof BABYLON.Condition) {
  20833. condition = newAction;
  20834. newAction = action;
  20835. }
  20836. else {
  20837. condition = null;
  20838. if (action)
  20839. action.then(newAction);
  20840. else
  20841. actionManager.registerAction(newAction);
  20842. }
  20843. }
  20844. else {
  20845. combineArray.push(newAction);
  20846. }
  20847. for (var i = 0; i < parsedAction.children.length; i++)
  20848. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20849. };
  20850. // triggers
  20851. for (var i = 0; i < parsedActions.children.length; i++) {
  20852. var triggerParams;
  20853. var trigger = parsedActions.children[i];
  20854. if (trigger.properties.length > 0) {
  20855. var param = trigger.properties[0].value;
  20856. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20857. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20858. }
  20859. else
  20860. triggerParams = BABYLON.ActionManager[trigger.name];
  20861. for (var j = 0; j < trigger.children.length; j++) {
  20862. if (!trigger.detached)
  20863. traverse(trigger.children[j], triggerParams, null, null);
  20864. }
  20865. }
  20866. };
  20867. var parseSound = function (parsedSound, scene, rootUrl) {
  20868. var soundName = parsedSound.name;
  20869. var soundUrl = rootUrl + soundName;
  20870. var options = {
  20871. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20872. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20873. rolloffFactor: parsedSound.rolloffFactor,
  20874. refDistance: parsedSound.refDistance,
  20875. distanceModel: parsedSound.distanceModel,
  20876. playbackRate: parsedSound.playbackRate
  20877. };
  20878. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20879. scene._addPendingData(newSound);
  20880. if (parsedSound.position) {
  20881. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20882. newSound.setPosition(soundPosition);
  20883. }
  20884. if (parsedSound.isDirectional) {
  20885. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20886. if (parsedSound.localDirectionToMesh) {
  20887. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20888. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20889. }
  20890. }
  20891. if (parsedSound.connectedMeshId) {
  20892. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20893. if (connectedMesh) {
  20894. newSound.attachToMesh(connectedMesh);
  20895. }
  20896. }
  20897. };
  20898. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20899. names = (names instanceof Array) ? names : [names];
  20900. for (var i in names) {
  20901. if (mesh.name === names[i]) {
  20902. hierarchyIds.push(mesh.id);
  20903. return true;
  20904. }
  20905. }
  20906. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20907. hierarchyIds.push(mesh.id);
  20908. return true;
  20909. }
  20910. return false;
  20911. };
  20912. var importVertexData = function (parsedVertexData, geometry) {
  20913. var vertexData = new BABYLON.VertexData();
  20914. // positions
  20915. var positions = parsedVertexData.positions;
  20916. if (positions) {
  20917. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20918. }
  20919. // normals
  20920. var normals = parsedVertexData.normals;
  20921. if (normals) {
  20922. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20923. }
  20924. // uvs
  20925. var uvs = parsedVertexData.uvs;
  20926. if (uvs) {
  20927. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20928. }
  20929. // uv2s
  20930. var uv2s = parsedVertexData.uv2s;
  20931. if (uv2s) {
  20932. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20933. }
  20934. // uv3s
  20935. var uv3s = parsedVertexData.uv3s;
  20936. if (uv3s) {
  20937. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20938. }
  20939. // uv4s
  20940. var uv4s = parsedVertexData.uv4s;
  20941. if (uv4s) {
  20942. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20943. }
  20944. // uv5s
  20945. var uv5s = parsedVertexData.uv5s;
  20946. if (uv5s) {
  20947. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20948. }
  20949. // uv6s
  20950. var uv6s = parsedVertexData.uv6s;
  20951. if (uv6s) {
  20952. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20953. }
  20954. // colors
  20955. var colors = parsedVertexData.colors;
  20956. if (colors) {
  20957. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20958. }
  20959. // matricesIndices
  20960. var matricesIndices = parsedVertexData.matricesIndices;
  20961. if (matricesIndices) {
  20962. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20963. }
  20964. // matricesWeights
  20965. var matricesWeights = parsedVertexData.matricesWeights;
  20966. if (matricesWeights) {
  20967. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20968. }
  20969. // indices
  20970. var indices = parsedVertexData.indices;
  20971. if (indices) {
  20972. vertexData.indices = indices;
  20973. }
  20974. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20975. };
  20976. var importGeometry = function (parsedGeometry, mesh) {
  20977. var scene = mesh.getScene();
  20978. // Geometry
  20979. var geometryId = parsedGeometry.geometryId;
  20980. if (geometryId) {
  20981. var geometry = scene.getGeometryByID(geometryId);
  20982. if (geometry) {
  20983. geometry.applyToMesh(mesh);
  20984. }
  20985. }
  20986. else if (parsedGeometry instanceof ArrayBuffer) {
  20987. var binaryInfo = mesh._binaryInfo;
  20988. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20989. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20990. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20991. }
  20992. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20993. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20994. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20995. }
  20996. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20997. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20998. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20999. }
  21000. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  21001. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  21002. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  21003. }
  21004. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  21005. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  21006. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  21007. }
  21008. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  21009. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  21010. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  21011. }
  21012. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  21013. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  21014. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  21015. }
  21016. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  21017. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  21018. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  21019. }
  21020. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  21021. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  21022. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  21023. }
  21024. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  21025. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  21026. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  21027. }
  21028. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  21029. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  21030. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  21031. }
  21032. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  21033. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  21034. mesh.setIndices(indicesData);
  21035. }
  21036. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  21037. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  21038. mesh.subMeshes = [];
  21039. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  21040. var materialIndex = subMeshesData[(i * 5) + 0];
  21041. var verticesStart = subMeshesData[(i * 5) + 1];
  21042. var verticesCount = subMeshesData[(i * 5) + 2];
  21043. var indexStart = subMeshesData[(i * 5) + 3];
  21044. var indexCount = subMeshesData[(i * 5) + 4];
  21045. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  21046. }
  21047. }
  21048. }
  21049. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  21050. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  21051. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  21052. if (parsedGeometry.uvs) {
  21053. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  21054. }
  21055. if (parsedGeometry.uvs2) {
  21056. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  21057. }
  21058. if (parsedGeometry.uvs3) {
  21059. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  21060. }
  21061. if (parsedGeometry.uvs4) {
  21062. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  21063. }
  21064. if (parsedGeometry.uvs5) {
  21065. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  21066. }
  21067. if (parsedGeometry.uvs6) {
  21068. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  21069. }
  21070. if (parsedGeometry.colors) {
  21071. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  21072. }
  21073. if (parsedGeometry.matricesIndices) {
  21074. if (!parsedGeometry.matricesIndices._isExpanded) {
  21075. var floatIndices = [];
  21076. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  21077. var matricesIndex = parsedGeometry.matricesIndices[i];
  21078. floatIndices.push(matricesIndex & 0x000000FF);
  21079. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  21080. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  21081. floatIndices.push(matricesIndex >> 24);
  21082. }
  21083. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  21084. }
  21085. else {
  21086. delete parsedGeometry.matricesIndices._isExpanded;
  21087. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  21088. }
  21089. }
  21090. if (parsedGeometry.matricesWeights) {
  21091. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  21092. }
  21093. mesh.setIndices(parsedGeometry.indices);
  21094. }
  21095. // SubMeshes
  21096. if (parsedGeometry.subMeshes) {
  21097. mesh.subMeshes = [];
  21098. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  21099. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  21100. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  21101. }
  21102. }
  21103. // Flat shading
  21104. if (mesh._shouldGenerateFlatShading) {
  21105. mesh.convertToFlatShadedMesh();
  21106. delete mesh._shouldGenerateFlatShading;
  21107. }
  21108. // Update
  21109. mesh.computeWorldMatrix(true);
  21110. // Octree
  21111. if (scene._selectionOctree) {
  21112. scene._selectionOctree.addMesh(mesh);
  21113. }
  21114. };
  21115. BABYLON.SceneLoader.RegisterPlugin({
  21116. extensions: ".babylon",
  21117. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21118. var parsedData = JSON.parse(data);
  21119. var loadedSkeletonsIds = [];
  21120. var loadedMaterialsIds = [];
  21121. var hierarchyIds = [];
  21122. for (var index = 0; index < parsedData.meshes.length; index++) {
  21123. var parsedMesh = parsedData.meshes[index];
  21124. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21125. if (meshesNames instanceof Array) {
  21126. // Remove found mesh name from list.
  21127. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21128. }
  21129. //Geometry?
  21130. if (parsedMesh.geometryId) {
  21131. //does the file contain geometries?
  21132. if (parsedData.geometries) {
  21133. //find the correct geometry and add it to the scene
  21134. var found = false;
  21135. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21136. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21137. return;
  21138. }
  21139. else {
  21140. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21141. if (parsedGeometryData.id == parsedMesh.geometryId) {
  21142. switch (geometryType) {
  21143. case "boxes":
  21144. parseBox(parsedGeometryData, scene);
  21145. break;
  21146. case "spheres":
  21147. parseSphere(parsedGeometryData, scene);
  21148. break;
  21149. case "cylinders":
  21150. parseCylinder(parsedGeometryData, scene);
  21151. break;
  21152. case "toruses":
  21153. parseTorus(parsedGeometryData, scene);
  21154. break;
  21155. case "grounds":
  21156. parseGround(parsedGeometryData, scene);
  21157. break;
  21158. case "planes":
  21159. parsePlane(parsedGeometryData, scene);
  21160. break;
  21161. case "torusKnots":
  21162. parseTorusKnot(parsedGeometryData, scene);
  21163. break;
  21164. case "vertexData":
  21165. parseVertexData(parsedGeometryData, scene, rootUrl);
  21166. break;
  21167. }
  21168. found = true;
  21169. }
  21170. });
  21171. }
  21172. });
  21173. if (!found) {
  21174. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21175. }
  21176. }
  21177. }
  21178. // Material ?
  21179. if (parsedMesh.materialId) {
  21180. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21181. if (!materialFound && parsedData.multiMaterials) {
  21182. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  21183. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21184. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  21185. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21186. var subMatId = parsedMultiMaterial.materials[matIndex];
  21187. loadedMaterialsIds.push(subMatId);
  21188. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21189. }
  21190. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21191. parseMultiMaterial(parsedMultiMaterial, scene);
  21192. materialFound = true;
  21193. break;
  21194. }
  21195. }
  21196. }
  21197. if (!materialFound) {
  21198. loadedMaterialsIds.push(parsedMesh.materialId);
  21199. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21200. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21201. }
  21202. }
  21203. }
  21204. // Skeleton ?
  21205. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21206. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21207. if (!skeletonAlreadyLoaded) {
  21208. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  21209. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21210. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21211. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  21212. loadedSkeletonsIds.push(parsedSkeleton.id);
  21213. }
  21214. }
  21215. }
  21216. }
  21217. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  21218. meshes.push(mesh);
  21219. }
  21220. }
  21221. // Connecting parents
  21222. for (index = 0; index < scene.meshes.length; index++) {
  21223. var currentMesh = scene.meshes[index];
  21224. if (currentMesh._waitingParentId) {
  21225. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21226. currentMesh._waitingParentId = undefined;
  21227. }
  21228. }
  21229. // freeze world matrix application
  21230. for (index = 0; index < scene.meshes.length; index++) {
  21231. var currentMesh = scene.meshes[index];
  21232. if (currentMesh._waitingFreezeWorldMatrix) {
  21233. currentMesh.freezeWorldMatrix();
  21234. currentMesh._waitingFreezeWorldMatrix = undefined;
  21235. }
  21236. }
  21237. // Particles
  21238. if (parsedData.particleSystems) {
  21239. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21240. var parsedParticleSystem = parsedData.particleSystems[index];
  21241. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21242. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  21243. }
  21244. }
  21245. }
  21246. return true;
  21247. },
  21248. load: function (scene, data, rootUrl) {
  21249. var parsedData = JSON.parse(data);
  21250. // Scene
  21251. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21252. scene.autoClear = parsedData.autoClear;
  21253. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21254. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21255. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21256. // Fog
  21257. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21258. scene.fogMode = parsedData.fogMode;
  21259. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21260. scene.fogStart = parsedData.fogStart;
  21261. scene.fogEnd = parsedData.fogEnd;
  21262. scene.fogDensity = parsedData.fogDensity;
  21263. }
  21264. // Lights
  21265. for (var index = 0; index < parsedData.lights.length; index++) {
  21266. var parsedLight = parsedData.lights[index];
  21267. parseLight(parsedLight, scene);
  21268. }
  21269. // Materials
  21270. if (parsedData.materials) {
  21271. for (index = 0; index < parsedData.materials.length; index++) {
  21272. var parsedMaterial = parsedData.materials[index];
  21273. parseMaterial(parsedMaterial, scene, rootUrl);
  21274. }
  21275. }
  21276. if (parsedData.multiMaterials) {
  21277. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  21278. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21279. parseMultiMaterial(parsedMultiMaterial, scene);
  21280. }
  21281. }
  21282. // Skeletons
  21283. if (parsedData.skeletons) {
  21284. for (index = 0; index < parsedData.skeletons.length; index++) {
  21285. var parsedSkeleton = parsedData.skeletons[index];
  21286. parseSkeleton(parsedSkeleton, scene);
  21287. }
  21288. }
  21289. // Geometries
  21290. var geometries = parsedData.geometries;
  21291. if (geometries) {
  21292. // Boxes
  21293. var boxes = geometries.boxes;
  21294. if (boxes) {
  21295. for (index = 0; index < boxes.length; index++) {
  21296. var parsedBox = boxes[index];
  21297. parseBox(parsedBox, scene);
  21298. }
  21299. }
  21300. // Spheres
  21301. var spheres = geometries.spheres;
  21302. if (spheres) {
  21303. for (index = 0; index < spheres.length; index++) {
  21304. var parsedSphere = spheres[index];
  21305. parseSphere(parsedSphere, scene);
  21306. }
  21307. }
  21308. // Cylinders
  21309. var cylinders = geometries.cylinders;
  21310. if (cylinders) {
  21311. for (index = 0; index < cylinders.length; index++) {
  21312. var parsedCylinder = cylinders[index];
  21313. parseCylinder(parsedCylinder, scene);
  21314. }
  21315. }
  21316. // Toruses
  21317. var toruses = geometries.toruses;
  21318. if (toruses) {
  21319. for (index = 0; index < toruses.length; index++) {
  21320. var parsedTorus = toruses[index];
  21321. parseTorus(parsedTorus, scene);
  21322. }
  21323. }
  21324. // Grounds
  21325. var grounds = geometries.grounds;
  21326. if (grounds) {
  21327. for (index = 0; index < grounds.length; index++) {
  21328. var parsedGround = grounds[index];
  21329. parseGround(parsedGround, scene);
  21330. }
  21331. }
  21332. // Planes
  21333. var planes = geometries.planes;
  21334. if (planes) {
  21335. for (index = 0; index < planes.length; index++) {
  21336. var parsedPlane = planes[index];
  21337. parsePlane(parsedPlane, scene);
  21338. }
  21339. }
  21340. // TorusKnots
  21341. var torusKnots = geometries.torusKnots;
  21342. if (torusKnots) {
  21343. for (index = 0; index < torusKnots.length; index++) {
  21344. var parsedTorusKnot = torusKnots[index];
  21345. parseTorusKnot(parsedTorusKnot, scene);
  21346. }
  21347. }
  21348. // VertexData
  21349. var vertexData = geometries.vertexData;
  21350. if (vertexData) {
  21351. for (index = 0; index < vertexData.length; index++) {
  21352. var parsedVertexData = vertexData[index];
  21353. parseVertexData(parsedVertexData, scene, rootUrl);
  21354. }
  21355. }
  21356. }
  21357. // Meshes
  21358. for (index = 0; index < parsedData.meshes.length; index++) {
  21359. var parsedMesh = parsedData.meshes[index];
  21360. parseMesh(parsedMesh, scene, rootUrl);
  21361. }
  21362. // Cameras
  21363. for (index = 0; index < parsedData.cameras.length; index++) {
  21364. var parsedCamera = parsedData.cameras[index];
  21365. parseCamera(parsedCamera, scene);
  21366. }
  21367. if (parsedData.activeCameraID) {
  21368. scene.setActiveCameraByID(parsedData.activeCameraID);
  21369. }
  21370. // Browsing all the graph to connect the dots
  21371. for (index = 0; index < scene.cameras.length; index++) {
  21372. var camera = scene.cameras[index];
  21373. if (camera._waitingParentId) {
  21374. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21375. camera._waitingParentId = undefined;
  21376. }
  21377. }
  21378. for (index = 0; index < scene.lights.length; index++) {
  21379. var light = scene.lights[index];
  21380. if (light._waitingParentId) {
  21381. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21382. light._waitingParentId = undefined;
  21383. }
  21384. }
  21385. // Sounds
  21386. if (parsedData.sounds) {
  21387. for (index = 0; index < parsedData.sounds.length; index++) {
  21388. var parsedSound = parsedData.sounds[index];
  21389. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21390. parseSound(parsedSound, scene, rootUrl);
  21391. }
  21392. else {
  21393. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21394. }
  21395. }
  21396. }
  21397. // Connect parents & children and parse actions
  21398. for (index = 0; index < scene.meshes.length; index++) {
  21399. var mesh = scene.meshes[index];
  21400. if (mesh._waitingParentId) {
  21401. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21402. mesh._waitingParentId = undefined;
  21403. }
  21404. if (mesh._waitingActions) {
  21405. parseActions(mesh._waitingActions, mesh, scene);
  21406. mesh._waitingActions = undefined;
  21407. }
  21408. }
  21409. // freeze world matrix application
  21410. for (index = 0; index < scene.meshes.length; index++) {
  21411. var currentMesh = scene.meshes[index];
  21412. if (currentMesh._waitingFreezeWorldMatrix) {
  21413. currentMesh.freezeWorldMatrix();
  21414. currentMesh._waitingFreezeWorldMatrix = undefined;
  21415. }
  21416. }
  21417. // Particles Systems
  21418. if (parsedData.particleSystems) {
  21419. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21420. var parsedParticleSystem = parsedData.particleSystems[index];
  21421. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  21422. }
  21423. }
  21424. // Lens flares
  21425. if (parsedData.lensFlareSystems) {
  21426. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  21427. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21428. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  21429. }
  21430. }
  21431. // Shadows
  21432. if (parsedData.shadowGenerators) {
  21433. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  21434. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21435. parseShadowGenerator(parsedShadowGenerator, scene);
  21436. }
  21437. }
  21438. // Actions (scene)
  21439. if (parsedData.actions) {
  21440. parseActions(parsedData.actions, null, scene);
  21441. }
  21442. // Finish
  21443. return true;
  21444. }
  21445. });
  21446. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21447. })(BABYLON || (BABYLON = {}));
  21448. var BABYLON;
  21449. (function (BABYLON) {
  21450. var SpriteManager = (function () {
  21451. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21453. this.name = name;
  21454. this.cellSize = cellSize;
  21455. this.sprites = new Array();
  21456. this.renderingGroupId = 0;
  21457. this.layerMask = 0x0FFFFFFF;
  21458. this.fogEnabled = true;
  21459. this._vertexDeclaration = [4, 4, 4, 4];
  21460. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21461. this._capacity = capacity;
  21462. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21463. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21464. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21465. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21466. this._scene = scene;
  21467. this._scene.spriteManagers.push(this);
  21468. // VBO
  21469. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21470. var indices = [];
  21471. var index = 0;
  21472. for (var count = 0; count < capacity; count++) {
  21473. indices.push(index);
  21474. indices.push(index + 1);
  21475. indices.push(index + 2);
  21476. indices.push(index);
  21477. indices.push(index + 2);
  21478. indices.push(index + 3);
  21479. index += 4;
  21480. }
  21481. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21482. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21483. // Effects
  21484. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21485. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21486. }
  21487. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21488. var arrayOffset = index * 16;
  21489. if (offsetX === 0)
  21490. offsetX = this._epsilon;
  21491. else if (offsetX === 1)
  21492. offsetX = 1 - this._epsilon;
  21493. if (offsetY === 0)
  21494. offsetY = this._epsilon;
  21495. else if (offsetY === 1)
  21496. offsetY = 1 - this._epsilon;
  21497. this._vertices[arrayOffset] = sprite.position.x;
  21498. this._vertices[arrayOffset + 1] = sprite.position.y;
  21499. this._vertices[arrayOffset + 2] = sprite.position.z;
  21500. this._vertices[arrayOffset + 3] = sprite.angle;
  21501. this._vertices[arrayOffset + 4] = sprite.width;
  21502. this._vertices[arrayOffset + 5] = sprite.height;
  21503. this._vertices[arrayOffset + 6] = offsetX;
  21504. this._vertices[arrayOffset + 7] = offsetY;
  21505. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21506. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21507. var offset = (sprite.cellIndex / rowSize) >> 0;
  21508. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21509. this._vertices[arrayOffset + 11] = offset;
  21510. // Color
  21511. this._vertices[arrayOffset + 12] = sprite.color.r;
  21512. this._vertices[arrayOffset + 13] = sprite.color.g;
  21513. this._vertices[arrayOffset + 14] = sprite.color.b;
  21514. this._vertices[arrayOffset + 15] = sprite.color.a;
  21515. };
  21516. SpriteManager.prototype.render = function () {
  21517. // Check
  21518. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21519. return;
  21520. var engine = this._scene.getEngine();
  21521. var baseSize = this._spriteTexture.getBaseSize();
  21522. // Sprites
  21523. var deltaTime = engine.getDeltaTime();
  21524. var max = Math.min(this._capacity, this.sprites.length);
  21525. var rowSize = baseSize.width / this.cellSize;
  21526. var offset = 0;
  21527. for (var index = 0; index < max; index++) {
  21528. var sprite = this.sprites[index];
  21529. if (!sprite) {
  21530. continue;
  21531. }
  21532. sprite._animate(deltaTime);
  21533. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21534. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21535. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21536. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21537. }
  21538. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21539. // Render
  21540. var effect = this._effectBase;
  21541. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21542. effect = this._effectFog;
  21543. }
  21544. engine.enableEffect(effect);
  21545. var viewMatrix = this._scene.getViewMatrix();
  21546. effect.setTexture("diffuseSampler", this._spriteTexture);
  21547. effect.setMatrix("view", viewMatrix);
  21548. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21549. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21550. // Fog
  21551. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21552. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21553. effect.setColor3("vFogColor", this._scene.fogColor);
  21554. }
  21555. // VBOs
  21556. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21557. // Draw order
  21558. engine.setDepthFunctionToLessOrEqual();
  21559. effect.setBool("alphaTest", true);
  21560. engine.setColorWrite(false);
  21561. engine.draw(true, 0, max * 6);
  21562. engine.setColorWrite(true);
  21563. effect.setBool("alphaTest", false);
  21564. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21565. engine.draw(true, 0, max * 6);
  21566. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21567. };
  21568. SpriteManager.prototype.dispose = function () {
  21569. if (this._vertexBuffer) {
  21570. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21571. this._vertexBuffer = null;
  21572. }
  21573. if (this._indexBuffer) {
  21574. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21575. this._indexBuffer = null;
  21576. }
  21577. if (this._spriteTexture) {
  21578. this._spriteTexture.dispose();
  21579. this._spriteTexture = null;
  21580. }
  21581. // Remove from scene
  21582. var index = this._scene.spriteManagers.indexOf(this);
  21583. this._scene.spriteManagers.splice(index, 1);
  21584. // Callback
  21585. if (this.onDispose) {
  21586. this.onDispose();
  21587. }
  21588. };
  21589. return SpriteManager;
  21590. })();
  21591. BABYLON.SpriteManager = SpriteManager;
  21592. })(BABYLON || (BABYLON = {}));
  21593. var BABYLON;
  21594. (function (BABYLON) {
  21595. var Sprite = (function () {
  21596. function Sprite(name, manager) {
  21597. this.name = name;
  21598. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21599. this.width = 1.0;
  21600. this.height = 1.0;
  21601. this.angle = 0;
  21602. this.cellIndex = 0;
  21603. this.invertU = 0;
  21604. this.invertV = 0;
  21605. this.animations = new Array();
  21606. this._animationStarted = false;
  21607. this._loopAnimation = false;
  21608. this._fromIndex = 0;
  21609. this._toIndex = 0;
  21610. this._delay = 0;
  21611. this._direction = 1;
  21612. this._frameCount = 0;
  21613. this._time = 0;
  21614. this._manager = manager;
  21615. this._manager.sprites.push(this);
  21616. this.position = BABYLON.Vector3.Zero();
  21617. }
  21618. Object.defineProperty(Sprite.prototype, "size", {
  21619. get: function () {
  21620. return this.width;
  21621. },
  21622. set: function (value) {
  21623. this.width = value;
  21624. this.height = value;
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21630. this._fromIndex = from;
  21631. this._toIndex = to;
  21632. this._loopAnimation = loop;
  21633. this._delay = delay;
  21634. this._animationStarted = true;
  21635. this._direction = from < to ? 1 : -1;
  21636. this.cellIndex = from;
  21637. this._time = 0;
  21638. };
  21639. Sprite.prototype.stopAnimation = function () {
  21640. this._animationStarted = false;
  21641. };
  21642. Sprite.prototype._animate = function (deltaTime) {
  21643. if (!this._animationStarted)
  21644. return;
  21645. this._time += deltaTime;
  21646. if (this._time > this._delay) {
  21647. this._time = this._time % this._delay;
  21648. this.cellIndex += this._direction;
  21649. if (this.cellIndex == this._toIndex) {
  21650. if (this._loopAnimation) {
  21651. this.cellIndex = this._fromIndex;
  21652. }
  21653. else {
  21654. this._animationStarted = false;
  21655. if (this.disposeWhenFinishedAnimating) {
  21656. this.dispose();
  21657. }
  21658. }
  21659. }
  21660. }
  21661. };
  21662. Sprite.prototype.dispose = function () {
  21663. for (var i = 0; i < this._manager.sprites.length; i++) {
  21664. if (this._manager.sprites[i] == this) {
  21665. this._manager.sprites.splice(i, 1);
  21666. }
  21667. }
  21668. };
  21669. return Sprite;
  21670. })();
  21671. BABYLON.Sprite = Sprite;
  21672. })(BABYLON || (BABYLON = {}));
  21673. var BABYLON;
  21674. (function (BABYLON) {
  21675. var Layer = (function () {
  21676. function Layer(name, imgUrl, scene, isBackground, color) {
  21677. this.name = name;
  21678. this._vertexDeclaration = [2];
  21679. this._vertexStrideSize = 2 * 4;
  21680. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21681. this.isBackground = isBackground === undefined ? true : isBackground;
  21682. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21683. this._scene = scene;
  21684. this._scene.layers.push(this);
  21685. // VBO
  21686. var vertices = [];
  21687. vertices.push(1, 1);
  21688. vertices.push(-1, 1);
  21689. vertices.push(-1, -1);
  21690. vertices.push(1, -1);
  21691. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21692. // Indices
  21693. var indices = [];
  21694. indices.push(0);
  21695. indices.push(1);
  21696. indices.push(2);
  21697. indices.push(0);
  21698. indices.push(2);
  21699. indices.push(3);
  21700. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21701. // Effects
  21702. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21703. }
  21704. Layer.prototype.render = function () {
  21705. // Check
  21706. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21707. return;
  21708. var engine = this._scene.getEngine();
  21709. // Render
  21710. engine.enableEffect(this._effect);
  21711. engine.setState(false);
  21712. // Texture
  21713. this._effect.setTexture("textureSampler", this.texture);
  21714. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21715. // Color
  21716. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21717. // VBOs
  21718. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21719. // Draw order
  21720. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21721. engine.draw(true, 0, 6);
  21722. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21723. };
  21724. Layer.prototype.dispose = function () {
  21725. if (this._vertexBuffer) {
  21726. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21727. this._vertexBuffer = null;
  21728. }
  21729. if (this._indexBuffer) {
  21730. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21731. this._indexBuffer = null;
  21732. }
  21733. if (this.texture) {
  21734. this.texture.dispose();
  21735. this.texture = null;
  21736. }
  21737. // Remove from scene
  21738. var index = this._scene.layers.indexOf(this);
  21739. this._scene.layers.splice(index, 1);
  21740. // Callback
  21741. if (this.onDispose) {
  21742. this.onDispose();
  21743. }
  21744. };
  21745. return Layer;
  21746. })();
  21747. BABYLON.Layer = Layer;
  21748. })(BABYLON || (BABYLON = {}));
  21749. var BABYLON;
  21750. (function (BABYLON) {
  21751. var Particle = (function () {
  21752. function Particle() {
  21753. this.position = BABYLON.Vector3.Zero();
  21754. this.direction = BABYLON.Vector3.Zero();
  21755. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21756. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21757. this.lifeTime = 1.0;
  21758. this.age = 0;
  21759. this.size = 0;
  21760. this.angle = 0;
  21761. this.angularSpeed = 0;
  21762. }
  21763. Particle.prototype.copyTo = function (other) {
  21764. other.position.copyFrom(this.position);
  21765. other.direction.copyFrom(this.direction);
  21766. other.color.copyFrom(this.color);
  21767. other.colorStep.copyFrom(this.colorStep);
  21768. other.lifeTime = this.lifeTime;
  21769. other.age = this.age;
  21770. other.size = this.size;
  21771. other.angle = this.angle;
  21772. other.angularSpeed = this.angularSpeed;
  21773. };
  21774. return Particle;
  21775. })();
  21776. BABYLON.Particle = Particle;
  21777. })(BABYLON || (BABYLON = {}));
  21778. var BABYLON;
  21779. (function (BABYLON) {
  21780. var randomNumber = function (min, max) {
  21781. if (min === max) {
  21782. return (min);
  21783. }
  21784. var random = Math.random();
  21785. return ((random * (max - min)) + min);
  21786. };
  21787. var ParticleSystem = (function () {
  21788. function ParticleSystem(name, capacity, scene, customEffect) {
  21789. var _this = this;
  21790. this.name = name;
  21791. this.renderingGroupId = 0;
  21792. this.emitter = null;
  21793. this.emitRate = 10;
  21794. this.manualEmitCount = -1;
  21795. this.updateSpeed = 0.01;
  21796. this.targetStopDuration = 0;
  21797. this.disposeOnStop = false;
  21798. this.minEmitPower = 1;
  21799. this.maxEmitPower = 1;
  21800. this.minLifeTime = 1;
  21801. this.maxLifeTime = 1;
  21802. this.minSize = 1;
  21803. this.maxSize = 1;
  21804. this.minAngularSpeed = 0;
  21805. this.maxAngularSpeed = 0;
  21806. this.layerMask = 0x0FFFFFFF;
  21807. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21808. this.forceDepthWrite = false;
  21809. this.gravity = BABYLON.Vector3.Zero();
  21810. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21811. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21812. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21813. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21814. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21815. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21816. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21817. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21818. this.particles = new Array();
  21819. this._vertexDeclaration = [3, 4, 4];
  21820. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21821. this._stockParticles = new Array();
  21822. this._newPartsExcess = 0;
  21823. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21824. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21825. this._scaledDirection = BABYLON.Vector3.Zero();
  21826. this._scaledGravity = BABYLON.Vector3.Zero();
  21827. this._currentRenderId = -1;
  21828. this._started = false;
  21829. this._stopped = false;
  21830. this._actualFrame = 0;
  21831. this.id = name;
  21832. this._capacity = capacity;
  21833. this._scene = scene;
  21834. this._customEffect = customEffect;
  21835. scene.particleSystems.push(this);
  21836. // VBO
  21837. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21838. var indices = [];
  21839. var index = 0;
  21840. for (var count = 0; count < capacity; count++) {
  21841. indices.push(index);
  21842. indices.push(index + 1);
  21843. indices.push(index + 2);
  21844. indices.push(index);
  21845. indices.push(index + 2);
  21846. indices.push(index + 3);
  21847. index += 4;
  21848. }
  21849. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21850. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21851. // Default behaviors
  21852. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21853. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21854. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21855. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21856. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21857. };
  21858. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21859. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21860. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21861. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21862. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21863. };
  21864. this.updateFunction = function (particles) {
  21865. for (var index = 0; index < particles.length; index++) {
  21866. var particle = particles[index];
  21867. particle.age += _this._scaledUpdateSpeed;
  21868. if (particle.age >= particle.lifeTime) {
  21869. _this.recycleParticle(particle);
  21870. index--;
  21871. continue;
  21872. }
  21873. else {
  21874. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21875. particle.color.addInPlace(_this._scaledColorStep);
  21876. if (particle.color.a < 0)
  21877. particle.color.a = 0;
  21878. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21879. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21880. particle.position.addInPlace(_this._scaledDirection);
  21881. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21882. particle.direction.addInPlace(_this._scaledGravity);
  21883. }
  21884. }
  21885. };
  21886. }
  21887. ParticleSystem.prototype.recycleParticle = function (particle) {
  21888. var lastParticle = this.particles.pop();
  21889. if (lastParticle !== particle) {
  21890. lastParticle.copyTo(particle);
  21891. this._stockParticles.push(lastParticle);
  21892. }
  21893. };
  21894. ParticleSystem.prototype.getCapacity = function () {
  21895. return this._capacity;
  21896. };
  21897. ParticleSystem.prototype.isAlive = function () {
  21898. return this._alive;
  21899. };
  21900. ParticleSystem.prototype.isStarted = function () {
  21901. return this._started;
  21902. };
  21903. ParticleSystem.prototype.start = function () {
  21904. this._started = true;
  21905. this._stopped = false;
  21906. this._actualFrame = 0;
  21907. };
  21908. ParticleSystem.prototype.stop = function () {
  21909. this._stopped = true;
  21910. };
  21911. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21912. var offset = index * 11;
  21913. this._vertices[offset] = particle.position.x;
  21914. this._vertices[offset + 1] = particle.position.y;
  21915. this._vertices[offset + 2] = particle.position.z;
  21916. this._vertices[offset + 3] = particle.color.r;
  21917. this._vertices[offset + 4] = particle.color.g;
  21918. this._vertices[offset + 5] = particle.color.b;
  21919. this._vertices[offset + 6] = particle.color.a;
  21920. this._vertices[offset + 7] = particle.angle;
  21921. this._vertices[offset + 8] = particle.size;
  21922. this._vertices[offset + 9] = offsetX;
  21923. this._vertices[offset + 10] = offsetY;
  21924. };
  21925. ParticleSystem.prototype._update = function (newParticles) {
  21926. // Update current
  21927. this._alive = this.particles.length > 0;
  21928. this.updateFunction(this.particles);
  21929. // Add new ones
  21930. var worldMatrix;
  21931. if (this.emitter.position) {
  21932. worldMatrix = this.emitter.getWorldMatrix();
  21933. }
  21934. else {
  21935. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21936. }
  21937. for (var index = 0; index < newParticles; index++) {
  21938. if (this.particles.length === this._capacity) {
  21939. break;
  21940. }
  21941. if (this._stockParticles.length !== 0) {
  21942. var particle = this._stockParticles.pop();
  21943. particle.age = 0;
  21944. }
  21945. else {
  21946. particle = new BABYLON.Particle();
  21947. }
  21948. this.particles.push(particle);
  21949. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21950. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21951. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21952. particle.size = randomNumber(this.minSize, this.maxSize);
  21953. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21954. this.startPositionFunction(worldMatrix, particle.position);
  21955. var step = randomNumber(0, 1.0);
  21956. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21957. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21958. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21959. }
  21960. };
  21961. ParticleSystem.prototype._getEffect = function () {
  21962. if (this._customEffect) {
  21963. return this._customEffect;
  21964. }
  21965. ;
  21966. var defines = [];
  21967. if (this._scene.clipPlane) {
  21968. defines.push("#define CLIPPLANE");
  21969. }
  21970. // Effect
  21971. var join = defines.join("\n");
  21972. if (this._cachedDefines !== join) {
  21973. this._cachedDefines = join;
  21974. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21975. }
  21976. return this._effect;
  21977. };
  21978. ParticleSystem.prototype.animate = function () {
  21979. if (!this._started)
  21980. return;
  21981. var effect = this._getEffect();
  21982. // Check
  21983. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21984. return;
  21985. if (this._currentRenderId === this._scene.getRenderId()) {
  21986. return;
  21987. }
  21988. this._currentRenderId = this._scene.getRenderId();
  21989. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21990. // determine the number of particles we need to create
  21991. var emitCout;
  21992. if (this.manualEmitCount > -1) {
  21993. emitCout = this.manualEmitCount;
  21994. this.manualEmitCount = 0;
  21995. }
  21996. else {
  21997. emitCout = this.emitRate;
  21998. }
  21999. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  22000. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  22001. if (this._newPartsExcess > 1.0) {
  22002. newParticles += this._newPartsExcess >> 0;
  22003. this._newPartsExcess -= this._newPartsExcess >> 0;
  22004. }
  22005. this._alive = false;
  22006. if (!this._stopped) {
  22007. this._actualFrame += this._scaledUpdateSpeed;
  22008. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22009. this.stop();
  22010. }
  22011. else {
  22012. newParticles = 0;
  22013. }
  22014. this._update(newParticles);
  22015. // Stopped?
  22016. if (this._stopped) {
  22017. if (!this._alive) {
  22018. this._started = false;
  22019. if (this.disposeOnStop) {
  22020. this._scene._toBeDisposed.push(this);
  22021. }
  22022. }
  22023. }
  22024. // Update VBO
  22025. var offset = 0;
  22026. for (var index = 0; index < this.particles.length; index++) {
  22027. var particle = this.particles[index];
  22028. this._appendParticleVertex(offset++, particle, 0, 0);
  22029. this._appendParticleVertex(offset++, particle, 1, 0);
  22030. this._appendParticleVertex(offset++, particle, 1, 1);
  22031. this._appendParticleVertex(offset++, particle, 0, 1);
  22032. }
  22033. var engine = this._scene.getEngine();
  22034. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22035. };
  22036. ParticleSystem.prototype.render = function () {
  22037. var effect = this._getEffect();
  22038. // Check
  22039. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22040. return 0;
  22041. var engine = this._scene.getEngine();
  22042. // Render
  22043. engine.enableEffect(effect);
  22044. engine.setState(false);
  22045. var viewMatrix = this._scene.getViewMatrix();
  22046. effect.setTexture("diffuseSampler", this.particleTexture);
  22047. effect.setMatrix("view", viewMatrix);
  22048. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22049. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22050. if (this._scene.clipPlane) {
  22051. var clipPlane = this._scene.clipPlane;
  22052. var invView = viewMatrix.clone();
  22053. invView.invert();
  22054. effect.setMatrix("invView", invView);
  22055. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22056. }
  22057. // VBOs
  22058. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22059. // Draw order
  22060. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22061. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22062. }
  22063. else {
  22064. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22065. }
  22066. if (this.forceDepthWrite) {
  22067. engine.setDepthWrite(true);
  22068. }
  22069. engine.draw(true, 0, this.particles.length * 6);
  22070. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22071. return this.particles.length;
  22072. };
  22073. ParticleSystem.prototype.dispose = function () {
  22074. if (this._vertexBuffer) {
  22075. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22076. this._vertexBuffer = null;
  22077. }
  22078. if (this._indexBuffer) {
  22079. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22080. this._indexBuffer = null;
  22081. }
  22082. if (this.particleTexture) {
  22083. this.particleTexture.dispose();
  22084. this.particleTexture = null;
  22085. }
  22086. // Remove from scene
  22087. var index = this._scene.particleSystems.indexOf(this);
  22088. this._scene.particleSystems.splice(index, 1);
  22089. // Callback
  22090. if (this.onDispose) {
  22091. this.onDispose();
  22092. }
  22093. };
  22094. // Clone
  22095. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22096. var result = new ParticleSystem(name, this._capacity, this._scene);
  22097. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22098. if (newEmitter === undefined) {
  22099. newEmitter = this.emitter;
  22100. }
  22101. result.emitter = newEmitter;
  22102. if (this.particleTexture) {
  22103. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22104. }
  22105. result.start();
  22106. return result;
  22107. };
  22108. // Statics
  22109. ParticleSystem.BLENDMODE_ONEONE = 0;
  22110. ParticleSystem.BLENDMODE_STANDARD = 1;
  22111. return ParticleSystem;
  22112. })();
  22113. BABYLON.ParticleSystem = ParticleSystem;
  22114. })(BABYLON || (BABYLON = {}));
  22115. var BABYLON;
  22116. (function (BABYLON) {
  22117. var Animation = (function () {
  22118. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22119. this.name = name;
  22120. this.targetProperty = targetProperty;
  22121. this.framePerSecond = framePerSecond;
  22122. this.dataType = dataType;
  22123. this.loopMode = loopMode;
  22124. this._offsetsCache = {};
  22125. this._highLimitsCache = {};
  22126. this._stopped = false;
  22127. this.allowMatricesInterpolation = false;
  22128. this.targetPropertyPath = targetProperty.split(".");
  22129. this.dataType = dataType;
  22130. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22131. }
  22132. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22133. var dataType = undefined;
  22134. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22135. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22136. }
  22137. else if (from instanceof BABYLON.Quaternion) {
  22138. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22139. }
  22140. else if (from instanceof BABYLON.Vector3) {
  22141. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22142. }
  22143. else if (from instanceof BABYLON.Vector2) {
  22144. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22145. }
  22146. else if (from instanceof BABYLON.Color3) {
  22147. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22148. }
  22149. if (dataType == undefined) {
  22150. return null;
  22151. }
  22152. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22153. var keys = [];
  22154. keys.push({ frame: 0, value: from });
  22155. keys.push({ frame: totalFrame, value: to });
  22156. animation.setKeys(keys);
  22157. if (easingFunction !== undefined) {
  22158. animation.setEasingFunction(easingFunction);
  22159. }
  22160. mesh.animations.push(animation);
  22161. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22162. };
  22163. // Methods
  22164. Animation.prototype.reset = function () {
  22165. this._offsetsCache = {};
  22166. this._highLimitsCache = {};
  22167. this.currentFrame = 0;
  22168. };
  22169. Animation.prototype.isStopped = function () {
  22170. return this._stopped;
  22171. };
  22172. Animation.prototype.getKeys = function () {
  22173. return this._keys;
  22174. };
  22175. Animation.prototype.getEasingFunction = function () {
  22176. return this._easingFunction;
  22177. };
  22178. Animation.prototype.setEasingFunction = function (easingFunction) {
  22179. this._easingFunction = easingFunction;
  22180. };
  22181. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22182. return startValue + (endValue - startValue) * gradient;
  22183. };
  22184. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22185. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22186. };
  22187. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22188. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22189. };
  22190. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22191. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22192. };
  22193. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22194. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22195. };
  22196. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22197. var startScale = new BABYLON.Vector3(0, 0, 0);
  22198. var startRotation = new BABYLON.Quaternion();
  22199. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  22200. startValue.decompose(startScale, startRotation, startTranslation);
  22201. var endScale = new BABYLON.Vector3(0, 0, 0);
  22202. var endRotation = new BABYLON.Quaternion();
  22203. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  22204. endValue.decompose(endScale, endRotation, endTranslation);
  22205. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  22206. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  22207. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  22208. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  22209. return result;
  22210. };
  22211. Animation.prototype.clone = function () {
  22212. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22213. clone.setKeys(this._keys);
  22214. return clone;
  22215. };
  22216. Animation.prototype.setKeys = function (values) {
  22217. this._keys = values.slice(0);
  22218. this._offsetsCache = {};
  22219. this._highLimitsCache = {};
  22220. };
  22221. Animation.prototype._getKeyValue = function (value) {
  22222. if (typeof value === "function") {
  22223. return value();
  22224. }
  22225. return value;
  22226. };
  22227. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22228. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22229. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22230. }
  22231. this.currentFrame = currentFrame;
  22232. // Try to get a hash to find the right key
  22233. 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));
  22234. if (this._keys[startKey].frame >= currentFrame) {
  22235. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22236. startKey--;
  22237. }
  22238. }
  22239. for (var key = startKey; key < this._keys.length; key++) {
  22240. if (this._keys[key + 1].frame >= currentFrame) {
  22241. var startValue = this._getKeyValue(this._keys[key].value);
  22242. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22243. // gradient : percent of currentFrame between the frame inf and the frame sup
  22244. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22245. // check for easingFunction and correction of gradient
  22246. if (this._easingFunction != null) {
  22247. gradient = this._easingFunction.ease(gradient);
  22248. }
  22249. switch (this.dataType) {
  22250. // Float
  22251. case Animation.ANIMATIONTYPE_FLOAT:
  22252. switch (loopMode) {
  22253. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22254. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22255. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22256. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22257. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22258. }
  22259. break;
  22260. // Quaternion
  22261. case Animation.ANIMATIONTYPE_QUATERNION:
  22262. var quaternion = null;
  22263. switch (loopMode) {
  22264. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22265. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22266. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22267. break;
  22268. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22269. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22270. break;
  22271. }
  22272. return quaternion;
  22273. // Vector3
  22274. case Animation.ANIMATIONTYPE_VECTOR3:
  22275. switch (loopMode) {
  22276. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22277. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22278. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22279. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22280. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22281. }
  22282. // Vector2
  22283. case Animation.ANIMATIONTYPE_VECTOR2:
  22284. switch (loopMode) {
  22285. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22286. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22287. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22288. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22289. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22290. }
  22291. // Color3
  22292. case Animation.ANIMATIONTYPE_COLOR3:
  22293. switch (loopMode) {
  22294. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22295. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22296. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22297. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22298. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22299. }
  22300. // Matrix
  22301. case Animation.ANIMATIONTYPE_MATRIX:
  22302. switch (loopMode) {
  22303. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22304. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22305. if (this.allowMatricesInterpolation) {
  22306. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22307. }
  22308. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22309. return startValue;
  22310. }
  22311. default:
  22312. break;
  22313. }
  22314. break;
  22315. }
  22316. }
  22317. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22318. };
  22319. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22320. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22321. this._stopped = true;
  22322. return false;
  22323. }
  22324. var returnValue = true;
  22325. // Adding a start key at frame 0 if missing
  22326. if (this._keys[0].frame !== 0) {
  22327. var newKey = { frame: 0, value: this._keys[0].value };
  22328. this._keys.splice(0, 0, newKey);
  22329. }
  22330. // Check limits
  22331. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22332. from = this._keys[0].frame;
  22333. }
  22334. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22335. to = this._keys[this._keys.length - 1].frame;
  22336. }
  22337. // Compute ratio
  22338. var range = to - from;
  22339. var offsetValue;
  22340. // ratio represents the frame delta between from and to
  22341. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22342. var highLimitValue = 0;
  22343. if (ratio > range && !loop) {
  22344. returnValue = false;
  22345. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22346. }
  22347. else {
  22348. // Get max value if required
  22349. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22350. var keyOffset = to.toString() + from.toString();
  22351. if (!this._offsetsCache[keyOffset]) {
  22352. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22353. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22354. switch (this.dataType) {
  22355. // Float
  22356. case Animation.ANIMATIONTYPE_FLOAT:
  22357. this._offsetsCache[keyOffset] = toValue - fromValue;
  22358. break;
  22359. // Quaternion
  22360. case Animation.ANIMATIONTYPE_QUATERNION:
  22361. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22362. break;
  22363. // Vector3
  22364. case Animation.ANIMATIONTYPE_VECTOR3:
  22365. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22366. // Vector2
  22367. case Animation.ANIMATIONTYPE_VECTOR2:
  22368. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22369. // Color3
  22370. case Animation.ANIMATIONTYPE_COLOR3:
  22371. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22372. default:
  22373. break;
  22374. }
  22375. this._highLimitsCache[keyOffset] = toValue;
  22376. }
  22377. highLimitValue = this._highLimitsCache[keyOffset];
  22378. offsetValue = this._offsetsCache[keyOffset];
  22379. }
  22380. }
  22381. if (offsetValue === undefined) {
  22382. switch (this.dataType) {
  22383. // Float
  22384. case Animation.ANIMATIONTYPE_FLOAT:
  22385. offsetValue = 0;
  22386. break;
  22387. // Quaternion
  22388. case Animation.ANIMATIONTYPE_QUATERNION:
  22389. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22390. break;
  22391. // Vector3
  22392. case Animation.ANIMATIONTYPE_VECTOR3:
  22393. offsetValue = BABYLON.Vector3.Zero();
  22394. break;
  22395. // Vector2
  22396. case Animation.ANIMATIONTYPE_VECTOR2:
  22397. offsetValue = BABYLON.Vector2.Zero();
  22398. break;
  22399. // Color3
  22400. case Animation.ANIMATIONTYPE_COLOR3:
  22401. offsetValue = BABYLON.Color3.Black();
  22402. }
  22403. }
  22404. // Compute value
  22405. var repeatCount = (ratio / range) >> 0;
  22406. var currentFrame = returnValue ? from + ratio % range : to;
  22407. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22408. // Set value
  22409. if (this.targetPropertyPath.length > 1) {
  22410. var property = this._target[this.targetPropertyPath[0]];
  22411. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22412. property = property[this.targetPropertyPath[index]];
  22413. }
  22414. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22415. }
  22416. else {
  22417. this._target[this.targetPropertyPath[0]] = currentValue;
  22418. }
  22419. if (this._target.markAsDirty) {
  22420. this._target.markAsDirty(this.targetProperty);
  22421. }
  22422. if (!returnValue) {
  22423. this._stopped = true;
  22424. }
  22425. return returnValue;
  22426. };
  22427. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22428. get: function () {
  22429. return Animation._ANIMATIONTYPE_FLOAT;
  22430. },
  22431. enumerable: true,
  22432. configurable: true
  22433. });
  22434. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22435. get: function () {
  22436. return Animation._ANIMATIONTYPE_VECTOR3;
  22437. },
  22438. enumerable: true,
  22439. configurable: true
  22440. });
  22441. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22442. get: function () {
  22443. return Animation._ANIMATIONTYPE_VECTOR2;
  22444. },
  22445. enumerable: true,
  22446. configurable: true
  22447. });
  22448. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22449. get: function () {
  22450. return Animation._ANIMATIONTYPE_QUATERNION;
  22451. },
  22452. enumerable: true,
  22453. configurable: true
  22454. });
  22455. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22456. get: function () {
  22457. return Animation._ANIMATIONTYPE_MATRIX;
  22458. },
  22459. enumerable: true,
  22460. configurable: true
  22461. });
  22462. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22463. get: function () {
  22464. return Animation._ANIMATIONTYPE_COLOR3;
  22465. },
  22466. enumerable: true,
  22467. configurable: true
  22468. });
  22469. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22470. get: function () {
  22471. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22472. },
  22473. enumerable: true,
  22474. configurable: true
  22475. });
  22476. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22477. get: function () {
  22478. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22479. },
  22480. enumerable: true,
  22481. configurable: true
  22482. });
  22483. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22484. get: function () {
  22485. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22486. },
  22487. enumerable: true,
  22488. configurable: true
  22489. });
  22490. // Statics
  22491. Animation._ANIMATIONTYPE_FLOAT = 0;
  22492. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22493. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22494. Animation._ANIMATIONTYPE_MATRIX = 3;
  22495. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22496. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22497. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22498. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22499. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22500. return Animation;
  22501. })();
  22502. BABYLON.Animation = Animation;
  22503. })(BABYLON || (BABYLON = {}));
  22504. var BABYLON;
  22505. (function (BABYLON) {
  22506. var Animatable = (function () {
  22507. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22508. if (fromFrame === void 0) { fromFrame = 0; }
  22509. if (toFrame === void 0) { toFrame = 100; }
  22510. if (loopAnimation === void 0) { loopAnimation = false; }
  22511. if (speedRatio === void 0) { speedRatio = 1.0; }
  22512. this.target = target;
  22513. this.fromFrame = fromFrame;
  22514. this.toFrame = toFrame;
  22515. this.loopAnimation = loopAnimation;
  22516. this.speedRatio = speedRatio;
  22517. this.onAnimationEnd = onAnimationEnd;
  22518. this._animations = new Array();
  22519. this._paused = false;
  22520. this.animationStarted = false;
  22521. if (animations) {
  22522. this.appendAnimations(target, animations);
  22523. }
  22524. this._scene = scene;
  22525. scene._activeAnimatables.push(this);
  22526. }
  22527. // Methods
  22528. Animatable.prototype.appendAnimations = function (target, animations) {
  22529. for (var index = 0; index < animations.length; index++) {
  22530. var animation = animations[index];
  22531. animation._target = target;
  22532. this._animations.push(animation);
  22533. }
  22534. };
  22535. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22536. var animations = this._animations;
  22537. for (var index = 0; index < animations.length; index++) {
  22538. if (animations[index].targetProperty === property) {
  22539. return animations[index];
  22540. }
  22541. }
  22542. return null;
  22543. };
  22544. Animatable.prototype.reset = function () {
  22545. var animations = this._animations;
  22546. for (var index = 0; index < animations.length; index++) {
  22547. animations[index].reset();
  22548. }
  22549. this._localDelayOffset = null;
  22550. this._pausedDelay = null;
  22551. };
  22552. Animatable.prototype.pause = function () {
  22553. if (this._paused) {
  22554. return;
  22555. }
  22556. this._paused = true;
  22557. };
  22558. Animatable.prototype.restart = function () {
  22559. this._paused = false;
  22560. };
  22561. Animatable.prototype.stop = function () {
  22562. var index = this._scene._activeAnimatables.indexOf(this);
  22563. if (index > -1) {
  22564. this._scene._activeAnimatables.splice(index, 1);
  22565. }
  22566. if (this.onAnimationEnd) {
  22567. this.onAnimationEnd();
  22568. }
  22569. };
  22570. Animatable.prototype._animate = function (delay) {
  22571. if (this._paused) {
  22572. if (!this._pausedDelay) {
  22573. this._pausedDelay = delay;
  22574. }
  22575. return true;
  22576. }
  22577. if (!this._localDelayOffset) {
  22578. this._localDelayOffset = delay;
  22579. }
  22580. else if (this._pausedDelay) {
  22581. this._localDelayOffset += delay - this._pausedDelay;
  22582. this._pausedDelay = null;
  22583. }
  22584. // Animating
  22585. var running = false;
  22586. var animations = this._animations;
  22587. for (var index = 0; index < animations.length; index++) {
  22588. var animation = animations[index];
  22589. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22590. running = running || isRunning;
  22591. }
  22592. if (!running) {
  22593. // Remove from active animatables
  22594. index = this._scene._activeAnimatables.indexOf(this);
  22595. this._scene._activeAnimatables.splice(index, 1);
  22596. }
  22597. if (!running && this.onAnimationEnd) {
  22598. this.onAnimationEnd();
  22599. }
  22600. return running;
  22601. };
  22602. return Animatable;
  22603. })();
  22604. BABYLON.Animatable = Animatable;
  22605. })(BABYLON || (BABYLON = {}));
  22606. var BABYLON;
  22607. (function (BABYLON) {
  22608. var EasingFunction = (function () {
  22609. function EasingFunction() {
  22610. // Properties
  22611. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22612. }
  22613. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22614. get: function () {
  22615. return EasingFunction._EASINGMODE_EASEIN;
  22616. },
  22617. enumerable: true,
  22618. configurable: true
  22619. });
  22620. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22621. get: function () {
  22622. return EasingFunction._EASINGMODE_EASEOUT;
  22623. },
  22624. enumerable: true,
  22625. configurable: true
  22626. });
  22627. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22628. get: function () {
  22629. return EasingFunction._EASINGMODE_EASEINOUT;
  22630. },
  22631. enumerable: true,
  22632. configurable: true
  22633. });
  22634. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22635. var n = Math.min(Math.max(easingMode, 0), 2);
  22636. this._easingMode = n;
  22637. };
  22638. EasingFunction.prototype.getEasingMode = function () {
  22639. return this._easingMode;
  22640. };
  22641. EasingFunction.prototype.easeInCore = function (gradient) {
  22642. throw new Error('You must implement this method');
  22643. };
  22644. EasingFunction.prototype.ease = function (gradient) {
  22645. switch (this._easingMode) {
  22646. case EasingFunction.EASINGMODE_EASEIN:
  22647. return this.easeInCore(gradient);
  22648. case EasingFunction.EASINGMODE_EASEOUT:
  22649. return (1 - this.easeInCore(1 - gradient));
  22650. }
  22651. if (gradient >= 0.5) {
  22652. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22653. }
  22654. return (this.easeInCore(gradient * 2) * 0.5);
  22655. };
  22656. //Statics
  22657. EasingFunction._EASINGMODE_EASEIN = 0;
  22658. EasingFunction._EASINGMODE_EASEOUT = 1;
  22659. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22660. return EasingFunction;
  22661. })();
  22662. BABYLON.EasingFunction = EasingFunction;
  22663. var CircleEase = (function (_super) {
  22664. __extends(CircleEase, _super);
  22665. function CircleEase() {
  22666. _super.apply(this, arguments);
  22667. }
  22668. CircleEase.prototype.easeInCore = function (gradient) {
  22669. gradient = Math.max(0, Math.min(1, gradient));
  22670. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22671. };
  22672. return CircleEase;
  22673. })(EasingFunction);
  22674. BABYLON.CircleEase = CircleEase;
  22675. var BackEase = (function (_super) {
  22676. __extends(BackEase, _super);
  22677. function BackEase(amplitude) {
  22678. if (amplitude === void 0) { amplitude = 1; }
  22679. _super.call(this);
  22680. this.amplitude = amplitude;
  22681. }
  22682. BackEase.prototype.easeInCore = function (gradient) {
  22683. var num = Math.max(0, this.amplitude);
  22684. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22685. };
  22686. return BackEase;
  22687. })(EasingFunction);
  22688. BABYLON.BackEase = BackEase;
  22689. var BounceEase = (function (_super) {
  22690. __extends(BounceEase, _super);
  22691. function BounceEase(bounces, bounciness) {
  22692. if (bounces === void 0) { bounces = 3; }
  22693. if (bounciness === void 0) { bounciness = 2; }
  22694. _super.call(this);
  22695. this.bounces = bounces;
  22696. this.bounciness = bounciness;
  22697. }
  22698. BounceEase.prototype.easeInCore = function (gradient) {
  22699. var y = Math.max(0.0, this.bounces);
  22700. var bounciness = this.bounciness;
  22701. if (bounciness <= 1.0) {
  22702. bounciness = 1.001;
  22703. }
  22704. var num9 = Math.pow(bounciness, y);
  22705. var num5 = 1.0 - bounciness;
  22706. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22707. var num15 = gradient * num4;
  22708. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22709. var num3 = Math.floor(num65);
  22710. var num13 = num3 + 1.0;
  22711. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22712. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22713. var num7 = (num8 + num12) * 0.5;
  22714. var num6 = gradient - num7;
  22715. var num2 = num7 - num8;
  22716. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22717. };
  22718. return BounceEase;
  22719. })(EasingFunction);
  22720. BABYLON.BounceEase = BounceEase;
  22721. var CubicEase = (function (_super) {
  22722. __extends(CubicEase, _super);
  22723. function CubicEase() {
  22724. _super.apply(this, arguments);
  22725. }
  22726. CubicEase.prototype.easeInCore = function (gradient) {
  22727. return (gradient * gradient * gradient);
  22728. };
  22729. return CubicEase;
  22730. })(EasingFunction);
  22731. BABYLON.CubicEase = CubicEase;
  22732. var ElasticEase = (function (_super) {
  22733. __extends(ElasticEase, _super);
  22734. function ElasticEase(oscillations, springiness) {
  22735. if (oscillations === void 0) { oscillations = 3; }
  22736. if (springiness === void 0) { springiness = 3; }
  22737. _super.call(this);
  22738. this.oscillations = oscillations;
  22739. this.springiness = springiness;
  22740. }
  22741. ElasticEase.prototype.easeInCore = function (gradient) {
  22742. var num2;
  22743. var num3 = Math.max(0.0, this.oscillations);
  22744. var num = Math.max(0.0, this.springiness);
  22745. if (num == 0) {
  22746. num2 = gradient;
  22747. }
  22748. else {
  22749. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22750. }
  22751. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22752. };
  22753. return ElasticEase;
  22754. })(EasingFunction);
  22755. BABYLON.ElasticEase = ElasticEase;
  22756. var ExponentialEase = (function (_super) {
  22757. __extends(ExponentialEase, _super);
  22758. function ExponentialEase(exponent) {
  22759. if (exponent === void 0) { exponent = 2; }
  22760. _super.call(this);
  22761. this.exponent = exponent;
  22762. }
  22763. ExponentialEase.prototype.easeInCore = function (gradient) {
  22764. if (this.exponent <= 0) {
  22765. return gradient;
  22766. }
  22767. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22768. };
  22769. return ExponentialEase;
  22770. })(EasingFunction);
  22771. BABYLON.ExponentialEase = ExponentialEase;
  22772. var PowerEase = (function (_super) {
  22773. __extends(PowerEase, _super);
  22774. function PowerEase(power) {
  22775. if (power === void 0) { power = 2; }
  22776. _super.call(this);
  22777. this.power = power;
  22778. }
  22779. PowerEase.prototype.easeInCore = function (gradient) {
  22780. var y = Math.max(0.0, this.power);
  22781. return Math.pow(gradient, y);
  22782. };
  22783. return PowerEase;
  22784. })(EasingFunction);
  22785. BABYLON.PowerEase = PowerEase;
  22786. var QuadraticEase = (function (_super) {
  22787. __extends(QuadraticEase, _super);
  22788. function QuadraticEase() {
  22789. _super.apply(this, arguments);
  22790. }
  22791. QuadraticEase.prototype.easeInCore = function (gradient) {
  22792. return (gradient * gradient);
  22793. };
  22794. return QuadraticEase;
  22795. })(EasingFunction);
  22796. BABYLON.QuadraticEase = QuadraticEase;
  22797. var QuarticEase = (function (_super) {
  22798. __extends(QuarticEase, _super);
  22799. function QuarticEase() {
  22800. _super.apply(this, arguments);
  22801. }
  22802. QuarticEase.prototype.easeInCore = function (gradient) {
  22803. return (gradient * gradient * gradient * gradient);
  22804. };
  22805. return QuarticEase;
  22806. })(EasingFunction);
  22807. BABYLON.QuarticEase = QuarticEase;
  22808. var QuinticEase = (function (_super) {
  22809. __extends(QuinticEase, _super);
  22810. function QuinticEase() {
  22811. _super.apply(this, arguments);
  22812. }
  22813. QuinticEase.prototype.easeInCore = function (gradient) {
  22814. return (gradient * gradient * gradient * gradient * gradient);
  22815. };
  22816. return QuinticEase;
  22817. })(EasingFunction);
  22818. BABYLON.QuinticEase = QuinticEase;
  22819. var SineEase = (function (_super) {
  22820. __extends(SineEase, _super);
  22821. function SineEase() {
  22822. _super.apply(this, arguments);
  22823. }
  22824. SineEase.prototype.easeInCore = function (gradient) {
  22825. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22826. };
  22827. return SineEase;
  22828. })(EasingFunction);
  22829. BABYLON.SineEase = SineEase;
  22830. var BezierCurveEase = (function (_super) {
  22831. __extends(BezierCurveEase, _super);
  22832. function BezierCurveEase(x1, y1, x2, y2) {
  22833. if (x1 === void 0) { x1 = 0; }
  22834. if (y1 === void 0) { y1 = 0; }
  22835. if (x2 === void 0) { x2 = 1; }
  22836. if (y2 === void 0) { y2 = 1; }
  22837. _super.call(this);
  22838. this.x1 = x1;
  22839. this.y1 = y1;
  22840. this.x2 = x2;
  22841. this.y2 = y2;
  22842. }
  22843. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22844. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22845. };
  22846. return BezierCurveEase;
  22847. })(EasingFunction);
  22848. BABYLON.BezierCurveEase = BezierCurveEase;
  22849. })(BABYLON || (BABYLON = {}));
  22850. var BABYLON;
  22851. (function (BABYLON) {
  22852. var Octree = (function () {
  22853. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22854. if (maxDepth === void 0) { maxDepth = 2; }
  22855. this.maxDepth = maxDepth;
  22856. this.dynamicContent = new Array();
  22857. this._maxBlockCapacity = maxBlockCapacity || 64;
  22858. this._selectionContent = new BABYLON.SmartArray(1024);
  22859. this._creationFunc = creationFunc;
  22860. }
  22861. // Methods
  22862. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22863. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22864. };
  22865. Octree.prototype.addMesh = function (entry) {
  22866. for (var index = 0; index < this.blocks.length; index++) {
  22867. var block = this.blocks[index];
  22868. block.addEntry(entry);
  22869. }
  22870. };
  22871. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22872. this._selectionContent.reset();
  22873. for (var index = 0; index < this.blocks.length; index++) {
  22874. var block = this.blocks[index];
  22875. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22876. }
  22877. if (allowDuplicate) {
  22878. this._selectionContent.concat(this.dynamicContent);
  22879. }
  22880. else {
  22881. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22882. }
  22883. return this._selectionContent;
  22884. };
  22885. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22886. this._selectionContent.reset();
  22887. for (var index = 0; index < this.blocks.length; index++) {
  22888. var block = this.blocks[index];
  22889. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22890. }
  22891. if (allowDuplicate) {
  22892. this._selectionContent.concat(this.dynamicContent);
  22893. }
  22894. else {
  22895. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22896. }
  22897. return this._selectionContent;
  22898. };
  22899. Octree.prototype.intersectsRay = function (ray) {
  22900. this._selectionContent.reset();
  22901. for (var index = 0; index < this.blocks.length; index++) {
  22902. var block = this.blocks[index];
  22903. block.intersectsRay(ray, this._selectionContent);
  22904. }
  22905. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22906. return this._selectionContent;
  22907. };
  22908. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22909. target.blocks = new Array();
  22910. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22911. // Segmenting space
  22912. for (var x = 0; x < 2; x++) {
  22913. for (var y = 0; y < 2; y++) {
  22914. for (var z = 0; z < 2; z++) {
  22915. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22916. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22917. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22918. block.addEntries(entries);
  22919. target.blocks.push(block);
  22920. }
  22921. }
  22922. }
  22923. };
  22924. Octree.CreationFuncForMeshes = function (entry, block) {
  22925. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22926. block.entries.push(entry);
  22927. }
  22928. };
  22929. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22930. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22931. block.entries.push(entry);
  22932. }
  22933. };
  22934. return Octree;
  22935. })();
  22936. BABYLON.Octree = Octree;
  22937. })(BABYLON || (BABYLON = {}));
  22938. var BABYLON;
  22939. (function (BABYLON) {
  22940. var OctreeBlock = (function () {
  22941. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22942. this.entries = new Array();
  22943. this._boundingVectors = new Array();
  22944. this._capacity = capacity;
  22945. this._depth = depth;
  22946. this._maxDepth = maxDepth;
  22947. this._creationFunc = creationFunc;
  22948. this._minPoint = minPoint;
  22949. this._maxPoint = maxPoint;
  22950. this._boundingVectors.push(minPoint.clone());
  22951. this._boundingVectors.push(maxPoint.clone());
  22952. this._boundingVectors.push(minPoint.clone());
  22953. this._boundingVectors[2].x = maxPoint.x;
  22954. this._boundingVectors.push(minPoint.clone());
  22955. this._boundingVectors[3].y = maxPoint.y;
  22956. this._boundingVectors.push(minPoint.clone());
  22957. this._boundingVectors[4].z = maxPoint.z;
  22958. this._boundingVectors.push(maxPoint.clone());
  22959. this._boundingVectors[5].z = minPoint.z;
  22960. this._boundingVectors.push(maxPoint.clone());
  22961. this._boundingVectors[6].x = minPoint.x;
  22962. this._boundingVectors.push(maxPoint.clone());
  22963. this._boundingVectors[7].y = minPoint.y;
  22964. }
  22965. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22966. // Property
  22967. get: function () {
  22968. return this._capacity;
  22969. },
  22970. enumerable: true,
  22971. configurable: true
  22972. });
  22973. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22974. get: function () {
  22975. return this._minPoint;
  22976. },
  22977. enumerable: true,
  22978. configurable: true
  22979. });
  22980. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22981. get: function () {
  22982. return this._maxPoint;
  22983. },
  22984. enumerable: true,
  22985. configurable: true
  22986. });
  22987. // Methods
  22988. OctreeBlock.prototype.addEntry = function (entry) {
  22989. if (this.blocks) {
  22990. for (var index = 0; index < this.blocks.length; index++) {
  22991. var block = this.blocks[index];
  22992. block.addEntry(entry);
  22993. }
  22994. return;
  22995. }
  22996. this._creationFunc(entry, this);
  22997. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22998. this.createInnerBlocks();
  22999. }
  23000. };
  23001. OctreeBlock.prototype.addEntries = function (entries) {
  23002. for (var index = 0; index < entries.length; index++) {
  23003. var mesh = entries[index];
  23004. this.addEntry(mesh);
  23005. }
  23006. };
  23007. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  23008. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  23009. if (this.blocks) {
  23010. for (var index = 0; index < this.blocks.length; index++) {
  23011. var block = this.blocks[index];
  23012. block.select(frustumPlanes, selection, allowDuplicate);
  23013. }
  23014. return;
  23015. }
  23016. if (allowDuplicate) {
  23017. selection.concat(this.entries);
  23018. }
  23019. else {
  23020. selection.concatWithNoDuplicate(this.entries);
  23021. }
  23022. }
  23023. };
  23024. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  23025. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  23026. if (this.blocks) {
  23027. for (var index = 0; index < this.blocks.length; index++) {
  23028. var block = this.blocks[index];
  23029. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  23030. }
  23031. return;
  23032. }
  23033. if (allowDuplicate) {
  23034. selection.concat(this.entries);
  23035. }
  23036. else {
  23037. selection.concatWithNoDuplicate(this.entries);
  23038. }
  23039. }
  23040. };
  23041. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  23042. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  23043. if (this.blocks) {
  23044. for (var index = 0; index < this.blocks.length; index++) {
  23045. var block = this.blocks[index];
  23046. block.intersectsRay(ray, selection);
  23047. }
  23048. return;
  23049. }
  23050. selection.concatWithNoDuplicate(this.entries);
  23051. }
  23052. };
  23053. OctreeBlock.prototype.createInnerBlocks = function () {
  23054. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  23055. };
  23056. return OctreeBlock;
  23057. })();
  23058. BABYLON.OctreeBlock = OctreeBlock;
  23059. })(BABYLON || (BABYLON = {}));
  23060. var BABYLON;
  23061. (function (BABYLON) {
  23062. var Bone = (function (_super) {
  23063. __extends(Bone, _super);
  23064. function Bone(name, skeleton, parentBone, matrix) {
  23065. _super.call(this, name, skeleton.getScene());
  23066. this.name = name;
  23067. this.children = new Array();
  23068. this.animations = new Array();
  23069. this._worldTransform = new BABYLON.Matrix();
  23070. this._absoluteTransform = new BABYLON.Matrix();
  23071. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23072. this._skeleton = skeleton;
  23073. this._matrix = matrix;
  23074. this._baseMatrix = matrix;
  23075. skeleton.bones.push(this);
  23076. if (parentBone) {
  23077. this._parent = parentBone;
  23078. parentBone.children.push(this);
  23079. }
  23080. else {
  23081. this._parent = null;
  23082. }
  23083. this._updateDifferenceMatrix();
  23084. }
  23085. // Members
  23086. Bone.prototype.getParent = function () {
  23087. return this._parent;
  23088. };
  23089. Bone.prototype.getLocalMatrix = function () {
  23090. return this._matrix;
  23091. };
  23092. Bone.prototype.getBaseMatrix = function () {
  23093. return this._baseMatrix;
  23094. };
  23095. Bone.prototype.getWorldMatrix = function () {
  23096. return this._worldTransform;
  23097. };
  23098. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23099. return this._invertedAbsoluteTransform;
  23100. };
  23101. Bone.prototype.getAbsoluteMatrix = function () {
  23102. var matrix = this._matrix.clone();
  23103. var parent = this._parent;
  23104. while (parent) {
  23105. matrix = matrix.multiply(parent.getLocalMatrix());
  23106. parent = parent.getParent();
  23107. }
  23108. return matrix;
  23109. };
  23110. // Methods
  23111. Bone.prototype.updateMatrix = function (matrix) {
  23112. this._matrix = matrix;
  23113. this._skeleton._markAsDirty();
  23114. this._updateDifferenceMatrix();
  23115. };
  23116. Bone.prototype._updateDifferenceMatrix = function () {
  23117. if (this._parent) {
  23118. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23119. }
  23120. else {
  23121. this._absoluteTransform.copyFrom(this._matrix);
  23122. }
  23123. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23124. for (var index = 0; index < this.children.length; index++) {
  23125. this.children[index]._updateDifferenceMatrix();
  23126. }
  23127. };
  23128. Bone.prototype.markAsDirty = function () {
  23129. this._currentRenderId++;
  23130. this._skeleton._markAsDirty();
  23131. };
  23132. return Bone;
  23133. })(BABYLON.Node);
  23134. BABYLON.Bone = Bone;
  23135. })(BABYLON || (BABYLON = {}));
  23136. var BABYLON;
  23137. (function (BABYLON) {
  23138. var Skeleton = (function () {
  23139. function Skeleton(name, id, scene) {
  23140. this.name = name;
  23141. this.id = id;
  23142. this.bones = new Array();
  23143. this._isDirty = true;
  23144. this._identity = BABYLON.Matrix.Identity();
  23145. this.bones = [];
  23146. this._scene = scene;
  23147. scene.skeletons.push(this);
  23148. this.prepare();
  23149. //make sure it will recalculate the matrix next time prepare is called.
  23150. this._isDirty = true;
  23151. }
  23152. // Members
  23153. Skeleton.prototype.getTransformMatrices = function () {
  23154. return this._transformMatrices;
  23155. };
  23156. Skeleton.prototype.getScene = function () {
  23157. return this._scene;
  23158. };
  23159. // Methods
  23160. Skeleton.prototype._markAsDirty = function () {
  23161. this._isDirty = true;
  23162. };
  23163. Skeleton.prototype.prepare = function () {
  23164. if (!this._isDirty) {
  23165. return;
  23166. }
  23167. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23168. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23169. }
  23170. for (var index = 0; index < this.bones.length; index++) {
  23171. var bone = this.bones[index];
  23172. var parentBone = bone.getParent();
  23173. if (parentBone) {
  23174. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23175. }
  23176. else {
  23177. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23178. }
  23179. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  23180. }
  23181. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  23182. this._isDirty = false;
  23183. this._scene._activeBones += this.bones.length;
  23184. };
  23185. Skeleton.prototype.getAnimatables = function () {
  23186. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23187. this._animatables = [];
  23188. for (var index = 0; index < this.bones.length; index++) {
  23189. this._animatables.push(this.bones[index]);
  23190. }
  23191. }
  23192. return this._animatables;
  23193. };
  23194. Skeleton.prototype.clone = function (name, id) {
  23195. var result = new Skeleton(name, id || name, this._scene);
  23196. for (var index = 0; index < this.bones.length; index++) {
  23197. var source = this.bones[index];
  23198. var parentBone = null;
  23199. if (source.getParent()) {
  23200. var parentIndex = this.bones.indexOf(source.getParent());
  23201. parentBone = result.bones[parentIndex];
  23202. }
  23203. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  23204. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23205. }
  23206. return result;
  23207. };
  23208. return Skeleton;
  23209. })();
  23210. BABYLON.Skeleton = Skeleton;
  23211. })(BABYLON || (BABYLON = {}));
  23212. var BABYLON;
  23213. (function (BABYLON) {
  23214. var PostProcess = (function () {
  23215. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23217. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23218. this.name = name;
  23219. this.width = -1;
  23220. this.height = -1;
  23221. this._reusable = false;
  23222. this._textures = new BABYLON.SmartArray(2);
  23223. this._currentRenderTextureInd = 0;
  23224. if (camera != null) {
  23225. this._camera = camera;
  23226. this._scene = camera.getScene();
  23227. camera.attachPostProcess(this);
  23228. this._engine = this._scene.getEngine();
  23229. }
  23230. else {
  23231. this._engine = engine;
  23232. }
  23233. this._renderRatio = ratio;
  23234. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23235. this._reusable = reusable || false;
  23236. this._textureType = textureType;
  23237. samplers = samplers || [];
  23238. samplers.push("textureSampler");
  23239. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  23240. }
  23241. PostProcess.prototype.isReusable = function () {
  23242. return this._reusable;
  23243. };
  23244. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23245. camera = camera || this._camera;
  23246. var scene = camera.getScene();
  23247. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23248. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23249. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23250. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  23251. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  23252. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23253. if (this._textures.length > 0) {
  23254. for (var i = 0; i < this._textures.length; i++) {
  23255. this._engine._releaseTexture(this._textures.data[i]);
  23256. }
  23257. this._textures.reset();
  23258. }
  23259. this.width = desiredWidth;
  23260. this.height = desiredHeight;
  23261. 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 }));
  23262. if (this._reusable) {
  23263. 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 }));
  23264. }
  23265. if (this.onSizeChanged) {
  23266. this.onSizeChanged();
  23267. }
  23268. }
  23269. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23270. if (this.onActivate) {
  23271. this.onActivate(camera);
  23272. }
  23273. // Clear
  23274. if (this.clearColor) {
  23275. this._engine.clear(this.clearColor, true, true);
  23276. }
  23277. else {
  23278. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23279. }
  23280. if (this._reusable) {
  23281. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23282. }
  23283. };
  23284. PostProcess.prototype.apply = function () {
  23285. // Check
  23286. if (!this._effect.isReady())
  23287. return null;
  23288. // States
  23289. this._engine.enableEffect(this._effect);
  23290. this._engine.setState(false);
  23291. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23292. this._engine.setDepthBuffer(false);
  23293. this._engine.setDepthWrite(false);
  23294. // Texture
  23295. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23296. // Parameters
  23297. if (this.onApply) {
  23298. this.onApply(this._effect);
  23299. }
  23300. return this._effect;
  23301. };
  23302. PostProcess.prototype.dispose = function (camera) {
  23303. camera = camera || this._camera;
  23304. if (this._textures.length > 0) {
  23305. for (var i = 0; i < this._textures.length; i++) {
  23306. this._engine._releaseTexture(this._textures.data[i]);
  23307. }
  23308. this._textures.reset();
  23309. }
  23310. if (!camera) {
  23311. return;
  23312. }
  23313. camera.detachPostProcess(this);
  23314. var index = camera._postProcesses.indexOf(this);
  23315. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23316. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23317. }
  23318. };
  23319. return PostProcess;
  23320. })();
  23321. BABYLON.PostProcess = PostProcess;
  23322. })(BABYLON || (BABYLON = {}));
  23323. var BABYLON;
  23324. (function (BABYLON) {
  23325. var PostProcessManager = (function () {
  23326. function PostProcessManager(scene) {
  23327. this._vertexDeclaration = [2];
  23328. this._vertexStrideSize = 2 * 4;
  23329. this._scene = scene;
  23330. }
  23331. PostProcessManager.prototype._prepareBuffers = function () {
  23332. if (this._vertexBuffer) {
  23333. return;
  23334. }
  23335. // VBO
  23336. var vertices = [];
  23337. vertices.push(1, 1);
  23338. vertices.push(-1, 1);
  23339. vertices.push(-1, -1);
  23340. vertices.push(1, -1);
  23341. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23342. // Indices
  23343. var indices = [];
  23344. indices.push(0);
  23345. indices.push(1);
  23346. indices.push(2);
  23347. indices.push(0);
  23348. indices.push(2);
  23349. indices.push(3);
  23350. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23351. };
  23352. // Methods
  23353. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23354. var postProcesses = this._scene.activeCamera._postProcesses;
  23355. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23356. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23357. return false;
  23358. }
  23359. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23360. return true;
  23361. };
  23362. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23363. var engine = this._scene.getEngine();
  23364. for (var index = 0; index < postProcesses.length; index++) {
  23365. if (index < postProcesses.length - 1) {
  23366. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23367. }
  23368. else {
  23369. if (targetTexture) {
  23370. engine.bindFramebuffer(targetTexture);
  23371. }
  23372. else {
  23373. engine.restoreDefaultFramebuffer();
  23374. }
  23375. }
  23376. var pp = postProcesses[index];
  23377. var effect = pp.apply();
  23378. if (effect) {
  23379. if (pp.onBeforeRender) {
  23380. pp.onBeforeRender(effect);
  23381. }
  23382. // VBOs
  23383. this._prepareBuffers();
  23384. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23385. // Draw order
  23386. engine.draw(true, 0, 6);
  23387. if (pp.onAfterRender) {
  23388. pp.onAfterRender(effect);
  23389. }
  23390. }
  23391. }
  23392. // Restore depth buffer
  23393. engine.setDepthBuffer(true);
  23394. engine.setDepthWrite(true);
  23395. };
  23396. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23397. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23398. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23399. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23400. return;
  23401. }
  23402. var engine = this._scene.getEngine();
  23403. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23404. if (index < postProcessesTakenIndices.length - 1) {
  23405. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  23406. }
  23407. else {
  23408. if (targetTexture) {
  23409. engine.bindFramebuffer(targetTexture, faceIndex);
  23410. }
  23411. else {
  23412. engine.restoreDefaultFramebuffer();
  23413. }
  23414. }
  23415. if (doNotPresent) {
  23416. break;
  23417. }
  23418. var pp = postProcesses[postProcessesTakenIndices[index]];
  23419. var effect = pp.apply();
  23420. if (effect) {
  23421. if (pp.onBeforeRender) {
  23422. pp.onBeforeRender(effect);
  23423. }
  23424. // VBOs
  23425. this._prepareBuffers();
  23426. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23427. // Draw order
  23428. engine.draw(true, 0, 6);
  23429. if (pp.onAfterRender) {
  23430. pp.onAfterRender(effect);
  23431. }
  23432. }
  23433. }
  23434. // Restore depth buffer
  23435. engine.setDepthBuffer(true);
  23436. engine.setDepthWrite(true);
  23437. };
  23438. PostProcessManager.prototype.dispose = function () {
  23439. if (this._vertexBuffer) {
  23440. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23441. this._vertexBuffer = null;
  23442. }
  23443. if (this._indexBuffer) {
  23444. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23445. this._indexBuffer = null;
  23446. }
  23447. };
  23448. return PostProcessManager;
  23449. })();
  23450. BABYLON.PostProcessManager = PostProcessManager;
  23451. })(BABYLON || (BABYLON = {}));
  23452. var BABYLON;
  23453. (function (BABYLON) {
  23454. var PassPostProcess = (function (_super) {
  23455. __extends(PassPostProcess, _super);
  23456. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23457. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23458. }
  23459. return PassPostProcess;
  23460. })(BABYLON.PostProcess);
  23461. BABYLON.PassPostProcess = PassPostProcess;
  23462. })(BABYLON || (BABYLON = {}));
  23463. var BABYLON;
  23464. (function (BABYLON) {
  23465. var BlurPostProcess = (function (_super) {
  23466. __extends(BlurPostProcess, _super);
  23467. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  23468. var _this = this;
  23469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  23470. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  23471. this.direction = direction;
  23472. this.blurWidth = blurWidth;
  23473. this.onApply = function (effect) {
  23474. effect.setFloat2("screenSize", _this.width, _this.height);
  23475. effect.setVector2("direction", _this.direction);
  23476. effect.setFloat("blurWidth", _this.blurWidth);
  23477. };
  23478. }
  23479. return BlurPostProcess;
  23480. })(BABYLON.PostProcess);
  23481. BABYLON.BlurPostProcess = BlurPostProcess;
  23482. })(BABYLON || (BABYLON = {}));
  23483. var BABYLON;
  23484. (function (BABYLON) {
  23485. var RefractionPostProcess = (function (_super) {
  23486. __extends(RefractionPostProcess, _super);
  23487. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  23488. var _this = this;
  23489. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  23490. this.color = color;
  23491. this.depth = depth;
  23492. this.colorLevel = colorLevel;
  23493. this.onActivate = function (cam) {
  23494. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23495. };
  23496. this.onApply = function (effect) {
  23497. effect.setColor3("baseColor", _this.color);
  23498. effect.setFloat("depth", _this.depth);
  23499. effect.setFloat("colorLevel", _this.colorLevel);
  23500. effect.setTexture("refractionSampler", _this._refRexture);
  23501. };
  23502. }
  23503. // Methods
  23504. RefractionPostProcess.prototype.dispose = function (camera) {
  23505. if (this._refRexture) {
  23506. this._refRexture.dispose();
  23507. }
  23508. _super.prototype.dispose.call(this, camera);
  23509. };
  23510. return RefractionPostProcess;
  23511. })(BABYLON.PostProcess);
  23512. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23513. })(BABYLON || (BABYLON = {}));
  23514. var BABYLON;
  23515. (function (BABYLON) {
  23516. var BlackAndWhitePostProcess = (function (_super) {
  23517. __extends(BlackAndWhitePostProcess, _super);
  23518. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23519. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23520. }
  23521. return BlackAndWhitePostProcess;
  23522. })(BABYLON.PostProcess);
  23523. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23524. })(BABYLON || (BABYLON = {}));
  23525. var BABYLON;
  23526. (function (BABYLON) {
  23527. var ConvolutionPostProcess = (function (_super) {
  23528. __extends(ConvolutionPostProcess, _super);
  23529. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23530. var _this = this;
  23531. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23532. this.kernel = kernel;
  23533. this.onApply = function (effect) {
  23534. effect.setFloat2("screenSize", _this.width, _this.height);
  23535. effect.setArray("kernel", _this.kernel);
  23536. };
  23537. }
  23538. // Statics
  23539. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23540. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23541. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23542. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23543. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23544. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23545. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23546. return ConvolutionPostProcess;
  23547. })(BABYLON.PostProcess);
  23548. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23549. })(BABYLON || (BABYLON = {}));
  23550. var BABYLON;
  23551. (function (BABYLON) {
  23552. var FilterPostProcess = (function (_super) {
  23553. __extends(FilterPostProcess, _super);
  23554. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23555. var _this = this;
  23556. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23557. this.kernelMatrix = kernelMatrix;
  23558. this.onApply = function (effect) {
  23559. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23560. };
  23561. }
  23562. return FilterPostProcess;
  23563. })(BABYLON.PostProcess);
  23564. BABYLON.FilterPostProcess = FilterPostProcess;
  23565. })(BABYLON || (BABYLON = {}));
  23566. var BABYLON;
  23567. (function (BABYLON) {
  23568. var FxaaPostProcess = (function (_super) {
  23569. __extends(FxaaPostProcess, _super);
  23570. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23571. var _this = this;
  23572. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23573. this.onSizeChanged = function () {
  23574. _this.texelWidth = 1.0 / _this.width;
  23575. _this.texelHeight = 1.0 / _this.height;
  23576. };
  23577. this.onApply = function (effect) {
  23578. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23579. };
  23580. }
  23581. return FxaaPostProcess;
  23582. })(BABYLON.PostProcess);
  23583. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23584. })(BABYLON || (BABYLON = {}));
  23585. var BABYLON;
  23586. (function (BABYLON) {
  23587. var StereoscopicInterlacePostProcess = (function (_super) {
  23588. __extends(StereoscopicInterlacePostProcess, _super);
  23589. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23590. var _this = this;
  23591. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23592. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23593. this.onSizeChanged = function () {
  23594. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23595. };
  23596. this.onApply = function (effect) {
  23597. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23598. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23599. };
  23600. }
  23601. return StereoscopicInterlacePostProcess;
  23602. })(BABYLON.PostProcess);
  23603. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23604. })(BABYLON || (BABYLON = {}));
  23605. var BABYLON;
  23606. (function (BABYLON) {
  23607. var LensFlare = (function () {
  23608. function LensFlare(size, position, color, imgUrl, system) {
  23609. this.size = size;
  23610. this.position = position;
  23611. this.dispose = function () {
  23612. if (this.texture) {
  23613. this.texture.dispose();
  23614. }
  23615. // Remove from scene
  23616. var index = this._system.lensFlares.indexOf(this);
  23617. this._system.lensFlares.splice(index, 1);
  23618. };
  23619. this.color = color || new BABYLON.Color3(1, 1, 1);
  23620. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23621. this._system = system;
  23622. system.lensFlares.push(this);
  23623. }
  23624. return LensFlare;
  23625. })();
  23626. BABYLON.LensFlare = LensFlare;
  23627. })(BABYLON || (BABYLON = {}));
  23628. var BABYLON;
  23629. (function (BABYLON) {
  23630. var LensFlareSystem = (function () {
  23631. function LensFlareSystem(name, emitter, scene) {
  23632. this.name = name;
  23633. this.lensFlares = new Array();
  23634. this.borderLimit = 300;
  23635. this.layerMask = 0x0FFFFFFF;
  23636. this._vertexDeclaration = [2];
  23637. this._vertexStrideSize = 2 * 4;
  23638. this._isEnabled = true;
  23639. this._scene = scene;
  23640. this._emitter = emitter;
  23641. scene.lensFlareSystems.push(this);
  23642. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23643. // VBO
  23644. var vertices = [];
  23645. vertices.push(1, 1);
  23646. vertices.push(-1, 1);
  23647. vertices.push(-1, -1);
  23648. vertices.push(1, -1);
  23649. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23650. // Indices
  23651. var indices = [];
  23652. indices.push(0);
  23653. indices.push(1);
  23654. indices.push(2);
  23655. indices.push(0);
  23656. indices.push(2);
  23657. indices.push(3);
  23658. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23659. // Effects
  23660. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23661. }
  23662. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23663. get: function () {
  23664. return this._isEnabled;
  23665. },
  23666. set: function (value) {
  23667. this._isEnabled = value;
  23668. },
  23669. enumerable: true,
  23670. configurable: true
  23671. });
  23672. LensFlareSystem.prototype.getScene = function () {
  23673. return this._scene;
  23674. };
  23675. LensFlareSystem.prototype.getEmitter = function () {
  23676. return this._emitter;
  23677. };
  23678. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23679. this._emitter = newEmitter;
  23680. };
  23681. LensFlareSystem.prototype.getEmitterPosition = function () {
  23682. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23683. };
  23684. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23685. var position = this.getEmitterPosition();
  23686. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23687. this._positionX = position.x;
  23688. this._positionY = position.y;
  23689. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23690. if (position.z > 0) {
  23691. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23692. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23693. return true;
  23694. }
  23695. }
  23696. return false;
  23697. };
  23698. LensFlareSystem.prototype._isVisible = function () {
  23699. if (!this._isEnabled) {
  23700. return false;
  23701. }
  23702. var emitterPosition = this.getEmitterPosition();
  23703. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23704. var distance = direction.length();
  23705. direction.normalize();
  23706. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23707. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23708. return !pickInfo.hit || pickInfo.distance > distance;
  23709. };
  23710. LensFlareSystem.prototype.render = function () {
  23711. if (!this._effect.isReady())
  23712. return false;
  23713. var engine = this._scene.getEngine();
  23714. var viewport = this._scene.activeCamera.viewport;
  23715. var globalViewport = viewport.toGlobal(engine);
  23716. // Position
  23717. if (!this.computeEffectivePosition(globalViewport)) {
  23718. return false;
  23719. }
  23720. // Visibility
  23721. if (!this._isVisible()) {
  23722. return false;
  23723. }
  23724. // Intensity
  23725. var awayX;
  23726. var awayY;
  23727. if (this._positionX < this.borderLimit + globalViewport.x) {
  23728. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23729. }
  23730. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23731. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23732. }
  23733. else {
  23734. awayX = 0;
  23735. }
  23736. if (this._positionY < this.borderLimit + globalViewport.y) {
  23737. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23738. }
  23739. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23740. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23741. }
  23742. else {
  23743. awayY = 0;
  23744. }
  23745. var away = (awayX > awayY) ? awayX : awayY;
  23746. if (away > this.borderLimit) {
  23747. away = this.borderLimit;
  23748. }
  23749. var intensity = 1.0 - (away / this.borderLimit);
  23750. if (intensity < 0) {
  23751. return false;
  23752. }
  23753. if (intensity > 1.0) {
  23754. intensity = 1.0;
  23755. }
  23756. // Position
  23757. var centerX = globalViewport.x + globalViewport.width / 2;
  23758. var centerY = globalViewport.y + globalViewport.height / 2;
  23759. var distX = centerX - this._positionX;
  23760. var distY = centerY - this._positionY;
  23761. // Effects
  23762. engine.enableEffect(this._effect);
  23763. engine.setState(false);
  23764. engine.setDepthBuffer(false);
  23765. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23766. // VBOs
  23767. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23768. // Flares
  23769. for (var index = 0; index < this.lensFlares.length; index++) {
  23770. var flare = this.lensFlares[index];
  23771. var x = centerX - (distX * flare.position);
  23772. var y = centerY - (distY * flare.position);
  23773. var cw = flare.size;
  23774. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23775. var cx = 2 * (x / globalViewport.width) - 1.0;
  23776. var cy = 1.0 - 2 * (y / globalViewport.height);
  23777. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23778. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23779. // Texture
  23780. this._effect.setTexture("textureSampler", flare.texture);
  23781. // Color
  23782. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23783. // Draw order
  23784. engine.draw(true, 0, 6);
  23785. }
  23786. engine.setDepthBuffer(true);
  23787. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23788. return true;
  23789. };
  23790. LensFlareSystem.prototype.dispose = function () {
  23791. if (this._vertexBuffer) {
  23792. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23793. this._vertexBuffer = null;
  23794. }
  23795. if (this._indexBuffer) {
  23796. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23797. this._indexBuffer = null;
  23798. }
  23799. while (this.lensFlares.length) {
  23800. this.lensFlares[0].dispose();
  23801. }
  23802. // Remove from scene
  23803. var index = this._scene.lensFlareSystems.indexOf(this);
  23804. this._scene.lensFlareSystems.splice(index, 1);
  23805. };
  23806. return LensFlareSystem;
  23807. })();
  23808. BABYLON.LensFlareSystem = LensFlareSystem;
  23809. })(BABYLON || (BABYLON = {}));
  23810. var BABYLON;
  23811. (function (BABYLON) {
  23812. var CannonJSPlugin = (function () {
  23813. function CannonJSPlugin() {
  23814. this._registeredMeshes = [];
  23815. this._physicsMaterials = [];
  23816. this.updateBodyPosition = function (mesh) {
  23817. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23818. var registeredMesh = this._registeredMeshes[index];
  23819. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23820. var body = registeredMesh.body;
  23821. var center = mesh.getBoundingInfo().boundingBox.center;
  23822. body.position.set(center.x, center.z, center.y);
  23823. body.quaternion.x = mesh.rotationQuaternion.x;
  23824. body.quaternion.z = mesh.rotationQuaternion.y;
  23825. body.quaternion.y = mesh.rotationQuaternion.z;
  23826. body.quaternion.w = -mesh.rotationQuaternion.w;
  23827. return;
  23828. }
  23829. }
  23830. };
  23831. }
  23832. CannonJSPlugin.prototype.initialize = function (iterations) {
  23833. if (iterations === void 0) { iterations = 10; }
  23834. this._world = new CANNON.World();
  23835. this._world.broadphase = new CANNON.NaiveBroadphase();
  23836. this._world.solver.iterations = iterations;
  23837. };
  23838. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23839. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23840. };
  23841. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23842. this._world.step(delta);
  23843. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23844. var registeredMesh = this._registeredMeshes[index];
  23845. if (registeredMesh.isChild) {
  23846. continue;
  23847. }
  23848. // Body position
  23849. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23850. var deltaPos = registeredMesh.delta;
  23851. if (deltaPos) {
  23852. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23853. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23854. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23855. }
  23856. else {
  23857. registeredMesh.mesh.position.x = bodyX;
  23858. registeredMesh.mesh.position.y = bodyZ;
  23859. registeredMesh.mesh.position.z = bodyY;
  23860. }
  23861. if (!registeredMesh.mesh.rotationQuaternion) {
  23862. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23863. }
  23864. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23865. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23866. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23867. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23868. }
  23869. };
  23870. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23871. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23872. };
  23873. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23874. this.unregisterMesh(mesh);
  23875. mesh.computeWorldMatrix(true);
  23876. switch (impostor) {
  23877. case BABYLON.PhysicsEngine.SphereImpostor:
  23878. var bbox = mesh.getBoundingInfo().boundingBox;
  23879. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23880. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23881. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23882. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23883. case BABYLON.PhysicsEngine.BoxImpostor:
  23884. bbox = mesh.getBoundingInfo().boundingBox;
  23885. var min = bbox.minimumWorld;
  23886. var max = bbox.maximumWorld;
  23887. var box = max.subtract(min).scale(0.5);
  23888. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23889. case BABYLON.PhysicsEngine.PlaneImpostor:
  23890. return this._createPlane(mesh, options);
  23891. case BABYLON.PhysicsEngine.MeshImpostor:
  23892. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23893. var rawFaces = mesh.getIndices();
  23894. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23895. }
  23896. return null;
  23897. };
  23898. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23899. var shape = new CANNON.Sphere(radius);
  23900. if (!options) {
  23901. return shape;
  23902. }
  23903. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23904. };
  23905. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23906. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23907. if (!options) {
  23908. return shape;
  23909. }
  23910. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23911. };
  23912. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23913. var shape = new CANNON.Plane();
  23914. if (!options) {
  23915. return shape;
  23916. }
  23917. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23918. };
  23919. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23920. var verts = [], faces = [];
  23921. mesh.computeWorldMatrix(true);
  23922. // Get vertices
  23923. for (var i = 0; i < rawVerts.length; i += 3) {
  23924. var transformed = BABYLON.Vector3.Zero();
  23925. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23926. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23927. }
  23928. // Get faces
  23929. for (var j = 0; j < rawFaces.length; j += 3) {
  23930. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23931. }
  23932. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23933. if (!options) {
  23934. return shape;
  23935. }
  23936. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23937. };
  23938. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23939. var index;
  23940. var mat;
  23941. for (index = 0; index < this._physicsMaterials.length; index++) {
  23942. mat = this._physicsMaterials[index];
  23943. if (mat.friction === friction && mat.restitution === restitution) {
  23944. return mat;
  23945. }
  23946. }
  23947. var currentMat = new CANNON.Material();
  23948. currentMat.friction = friction;
  23949. currentMat.restitution = restitution;
  23950. this._physicsMaterials.push(currentMat);
  23951. for (index = 0; index < this._physicsMaterials.length; index++) {
  23952. mat = this._physicsMaterials[index];
  23953. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23954. contactMaterial.contactEquationStiffness = 1e10;
  23955. contactMaterial.contactEquationRegularizationTime = 10;
  23956. this._world.addContactMaterial(contactMaterial);
  23957. }
  23958. return currentMat;
  23959. };
  23960. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23961. var initialRotation = null;
  23962. if (mesh.rotationQuaternion) {
  23963. initialRotation = mesh.rotationQuaternion.clone();
  23964. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23965. }
  23966. // The delta between the mesh position and the mesh bounding box center
  23967. var bbox = mesh.getBoundingInfo().boundingBox;
  23968. var deltaPosition = mesh.position.subtract(bbox.center);
  23969. var material = this._addMaterial(friction, restitution);
  23970. var body = new CANNON.RigidBody(mass, shape, material);
  23971. if (initialRotation) {
  23972. body.quaternion.x = initialRotation.x;
  23973. body.quaternion.z = initialRotation.y;
  23974. body.quaternion.y = initialRotation.z;
  23975. body.quaternion.w = -initialRotation.w;
  23976. }
  23977. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23978. this._world.add(body);
  23979. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23980. return body;
  23981. };
  23982. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23983. var compoundShape = new CANNON.Compound();
  23984. for (var index = 0; index < parts.length; index++) {
  23985. var mesh = parts[index].mesh;
  23986. var shape = this.registerMesh(mesh, parts[index].impostor);
  23987. if (index == 0) {
  23988. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23989. }
  23990. else {
  23991. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23992. }
  23993. }
  23994. var initialMesh = parts[0].mesh;
  23995. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23996. body.parts = parts;
  23997. return body;
  23998. };
  23999. CannonJSPlugin.prototype._unbindBody = function (body) {
  24000. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24001. var registeredMesh = this._registeredMeshes[index];
  24002. if (registeredMesh.body === body) {
  24003. registeredMesh.body = null;
  24004. registeredMesh.delta = 0;
  24005. }
  24006. }
  24007. };
  24008. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24009. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24010. var registeredMesh = this._registeredMeshes[index];
  24011. if (registeredMesh.mesh === mesh) {
  24012. // Remove body
  24013. if (registeredMesh.body) {
  24014. this._world.remove(registeredMesh.body);
  24015. this._unbindBody(registeredMesh.body);
  24016. }
  24017. this._registeredMeshes.splice(index, 1);
  24018. return;
  24019. }
  24020. }
  24021. };
  24022. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24023. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24024. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24025. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24026. var registeredMesh = this._registeredMeshes[index];
  24027. if (registeredMesh.mesh === mesh) {
  24028. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24029. return;
  24030. }
  24031. }
  24032. };
  24033. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24034. var body1 = null, body2 = null;
  24035. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24036. var registeredMesh = this._registeredMeshes[index];
  24037. if (registeredMesh.mesh === mesh1) {
  24038. body1 = registeredMesh.body;
  24039. }
  24040. else if (registeredMesh.mesh === mesh2) {
  24041. body2 = registeredMesh.body;
  24042. }
  24043. }
  24044. if (!body1 || !body2) {
  24045. return false;
  24046. }
  24047. 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));
  24048. this._world.addConstraint(constraint);
  24049. return true;
  24050. };
  24051. CannonJSPlugin.prototype.dispose = function () {
  24052. while (this._registeredMeshes.length) {
  24053. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24054. }
  24055. };
  24056. CannonJSPlugin.prototype.isSupported = function () {
  24057. return window.CANNON !== undefined;
  24058. };
  24059. return CannonJSPlugin;
  24060. })();
  24061. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24062. })(BABYLON || (BABYLON = {}));
  24063. var BABYLON;
  24064. (function (BABYLON) {
  24065. var OimoJSPlugin = (function () {
  24066. function OimoJSPlugin() {
  24067. this._registeredMeshes = [];
  24068. /**
  24069. * Update the body position according to the mesh position
  24070. * @param mesh
  24071. */
  24072. this.updateBodyPosition = function (mesh) {
  24073. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24074. var registeredMesh = this._registeredMeshes[index];
  24075. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24076. var body = registeredMesh.body.body;
  24077. mesh.computeWorldMatrix(true);
  24078. var center = mesh.getBoundingInfo().boundingBox.center;
  24079. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  24080. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  24081. body.sleeping = false;
  24082. return;
  24083. }
  24084. // Case where the parent has been updated
  24085. if (registeredMesh.mesh.parent === mesh) {
  24086. mesh.computeWorldMatrix(true);
  24087. registeredMesh.mesh.computeWorldMatrix(true);
  24088. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  24089. var absoluteRotation = mesh.rotation;
  24090. body = registeredMesh.body.body;
  24091. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  24092. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  24093. body.sleeping = false;
  24094. return;
  24095. }
  24096. }
  24097. };
  24098. }
  24099. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  24100. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24101. };
  24102. OimoJSPlugin.prototype.initialize = function (iterations) {
  24103. this._world = new OIMO.World();
  24104. this._world.clear();
  24105. };
  24106. OimoJSPlugin.prototype.setGravity = function (gravity) {
  24107. this._world.gravity = gravity;
  24108. };
  24109. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24110. var body = null;
  24111. this.unregisterMesh(mesh);
  24112. mesh.computeWorldMatrix(true);
  24113. var initialRotation = null;
  24114. if (mesh.rotationQuaternion) {
  24115. initialRotation = mesh.rotationQuaternion.clone();
  24116. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24117. mesh.computeWorldMatrix(true);
  24118. }
  24119. var bbox = mesh.getBoundingInfo().boundingBox;
  24120. // The delta between the mesh position and the mesh bounding box center
  24121. var deltaPosition = mesh.position.subtract(bbox.center);
  24122. // Transform delta position with the rotation
  24123. if (initialRotation) {
  24124. var m = new BABYLON.Matrix();
  24125. initialRotation.toRotationMatrix(m);
  24126. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  24127. }
  24128. // register mesh
  24129. switch (impostor) {
  24130. case BABYLON.PhysicsEngine.SphereImpostor:
  24131. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24132. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24133. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24134. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  24135. body = new OIMO.Body({
  24136. type: 'sphere',
  24137. size: [size],
  24138. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  24139. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  24140. move: options.mass != 0,
  24141. config: [options.mass, options.friction, options.restitution],
  24142. world: this._world
  24143. });
  24144. break;
  24145. case BABYLON.PhysicsEngine.PlaneImpostor:
  24146. //Oimo "fakes" a cylinder as a box, so why don't we!
  24147. case BABYLON.PhysicsEngine.CylinderImpostor:
  24148. case BABYLON.PhysicsEngine.BoxImpostor:
  24149. var min = bbox.minimumWorld;
  24150. var max = bbox.maximumWorld;
  24151. var box = max.subtract(min);
  24152. var sizeX = this._checkWithEpsilon(box.x);
  24153. var sizeY = this._checkWithEpsilon(box.y);
  24154. var sizeZ = this._checkWithEpsilon(box.z);
  24155. body = new OIMO.Body({
  24156. type: 'box',
  24157. size: [sizeX, sizeY, sizeZ],
  24158. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  24159. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  24160. move: options.mass != 0,
  24161. config: [options.mass, options.friction, options.restitution],
  24162. world: this._world
  24163. });
  24164. break;
  24165. }
  24166. //If quaternion was set as the rotation of the object
  24167. if (initialRotation) {
  24168. //We have to access the rigid body's properties to set the quaternion.
  24169. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  24170. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  24171. //update the internal rotation matrix
  24172. body.body.syncShapes();
  24173. }
  24174. this._registeredMeshes.push({
  24175. mesh: mesh,
  24176. body: body,
  24177. delta: deltaPosition
  24178. });
  24179. return body;
  24180. };
  24181. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24182. var types = [], sizes = [], positions = [], rotations = [];
  24183. var initialMesh = parts[0].mesh;
  24184. for (var index = 0; index < parts.length; index++) {
  24185. var part = parts[index];
  24186. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  24187. types.push(bodyParameters.type);
  24188. sizes.push.apply(sizes, bodyParameters.size);
  24189. positions.push.apply(positions, bodyParameters.pos);
  24190. rotations.push.apply(rotations, bodyParameters.rot);
  24191. }
  24192. var body = new OIMO.Body({
  24193. type: types,
  24194. size: sizes,
  24195. pos: positions,
  24196. rot: rotations,
  24197. move: options.mass != 0,
  24198. config: [options.mass, options.friction, options.restitution],
  24199. world: this._world
  24200. });
  24201. this._registeredMeshes.push({
  24202. mesh: initialMesh,
  24203. body: body
  24204. });
  24205. return body;
  24206. };
  24207. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  24208. var bodyParameters = null;
  24209. var mesh = part.mesh;
  24210. // We need the bounding box/sphere info to compute the physics body
  24211. mesh.computeWorldMatrix();
  24212. switch (part.impostor) {
  24213. case BABYLON.PhysicsEngine.SphereImpostor:
  24214. var bbox = mesh.getBoundingInfo().boundingBox;
  24215. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24216. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24217. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24218. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  24219. bodyParameters = {
  24220. type: 'sphere',
  24221. /* bug with oimo : sphere needs 3 sizes in this case */
  24222. size: [size, -1, -1],
  24223. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  24224. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  24225. };
  24226. break;
  24227. case BABYLON.PhysicsEngine.PlaneImpostor:
  24228. case BABYLON.PhysicsEngine.BoxImpostor:
  24229. bbox = mesh.getBoundingInfo().boundingBox;
  24230. var min = bbox.minimumWorld;
  24231. var max = bbox.maximumWorld;
  24232. var box = max.subtract(min);
  24233. var sizeX = this._checkWithEpsilon(box.x);
  24234. var sizeY = this._checkWithEpsilon(box.y);
  24235. var sizeZ = this._checkWithEpsilon(box.z);
  24236. var relativePosition = mesh.position;
  24237. bodyParameters = {
  24238. type: 'box',
  24239. size: [sizeX, sizeY, sizeZ],
  24240. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  24241. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  24242. };
  24243. break;
  24244. }
  24245. return bodyParameters;
  24246. };
  24247. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  24248. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24249. var registeredMesh = this._registeredMeshes[index];
  24250. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24251. if (registeredMesh.body) {
  24252. this._world.removeRigidBody(registeredMesh.body.body);
  24253. this._unbindBody(registeredMesh.body);
  24254. }
  24255. this._registeredMeshes.splice(index, 1);
  24256. return;
  24257. }
  24258. }
  24259. };
  24260. OimoJSPlugin.prototype._unbindBody = function (body) {
  24261. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24262. var registeredMesh = this._registeredMeshes[index];
  24263. if (registeredMesh.body === body) {
  24264. registeredMesh.body = null;
  24265. }
  24266. }
  24267. };
  24268. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24269. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24270. var registeredMesh = this._registeredMeshes[index];
  24271. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24272. // Get object mass to have a behaviour similar to cannon.js
  24273. var mass = registeredMesh.body.body.massInfo.mass;
  24274. // The force is scaled with the mass of object
  24275. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  24276. return;
  24277. }
  24278. }
  24279. };
  24280. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24281. var body1 = null, body2 = null;
  24282. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24283. var registeredMesh = this._registeredMeshes[index];
  24284. if (registeredMesh.mesh === mesh1) {
  24285. body1 = registeredMesh.body.body;
  24286. }
  24287. else if (registeredMesh.mesh === mesh2) {
  24288. body2 = registeredMesh.body.body;
  24289. }
  24290. }
  24291. if (!body1 || !body2) {
  24292. return false;
  24293. }
  24294. if (!options) {
  24295. options = {};
  24296. }
  24297. new OIMO.Link({
  24298. type: options.type,
  24299. body1: body1,
  24300. body2: body2,
  24301. min: options.min,
  24302. max: options.max,
  24303. axe1: options.axe1,
  24304. axe2: options.axe2,
  24305. pos1: [pivot1.x, pivot1.y, pivot1.z],
  24306. pos2: [pivot2.x, pivot2.y, pivot2.z],
  24307. collision: options.collision,
  24308. spring: options.spring,
  24309. world: this._world
  24310. });
  24311. return true;
  24312. };
  24313. OimoJSPlugin.prototype.dispose = function () {
  24314. this._world.clear();
  24315. while (this._registeredMeshes.length) {
  24316. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24317. }
  24318. };
  24319. OimoJSPlugin.prototype.isSupported = function () {
  24320. return OIMO !== undefined;
  24321. };
  24322. OimoJSPlugin.prototype._getLastShape = function (body) {
  24323. var lastShape = body.shapes;
  24324. while (lastShape.next) {
  24325. lastShape = lastShape.next;
  24326. }
  24327. return lastShape;
  24328. };
  24329. OimoJSPlugin.prototype.runOneStep = function (time) {
  24330. this._world.step();
  24331. // Update the position of all registered meshes
  24332. var i = this._registeredMeshes.length;
  24333. var m;
  24334. while (i--) {
  24335. var body = this._registeredMeshes[i].body.body;
  24336. var mesh = this._registeredMeshes[i].mesh;
  24337. var delta = this._registeredMeshes[i].delta;
  24338. if (!body.sleeping) {
  24339. if (body.shapes.next) {
  24340. var parentShape = this._getLastShape(body);
  24341. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  24342. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  24343. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  24344. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  24345. if (!mesh.rotationQuaternion) {
  24346. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24347. }
  24348. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  24349. mesh.computeWorldMatrix();
  24350. }
  24351. else {
  24352. m = body.getMatrix();
  24353. mtx = BABYLON.Matrix.FromArray(m);
  24354. // Body position
  24355. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  24356. if (!delta) {
  24357. mesh.position.x = bodyX;
  24358. mesh.position.y = bodyY;
  24359. mesh.position.z = bodyZ;
  24360. }
  24361. else {
  24362. mesh.position.x = bodyX + delta.x;
  24363. mesh.position.y = bodyY + delta.y;
  24364. mesh.position.z = bodyZ + delta.z;
  24365. }
  24366. if (!mesh.rotationQuaternion) {
  24367. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24368. }
  24369. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  24370. mesh.computeWorldMatrix();
  24371. }
  24372. }
  24373. }
  24374. };
  24375. return OimoJSPlugin;
  24376. })();
  24377. BABYLON.OimoJSPlugin = OimoJSPlugin;
  24378. })(BABYLON || (BABYLON = {}));
  24379. var BABYLON;
  24380. (function (BABYLON) {
  24381. var PhysicsEngine = (function () {
  24382. function PhysicsEngine(plugin) {
  24383. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  24384. }
  24385. PhysicsEngine.prototype._initialize = function (gravity) {
  24386. this._currentPlugin.initialize();
  24387. this._setGravity(gravity);
  24388. };
  24389. PhysicsEngine.prototype._runOneStep = function (delta) {
  24390. if (delta > 0.1) {
  24391. delta = 0.1;
  24392. }
  24393. else if (delta <= 0) {
  24394. delta = 1.0 / 60.0;
  24395. }
  24396. this._currentPlugin.runOneStep(delta);
  24397. };
  24398. PhysicsEngine.prototype._setGravity = function (gravity) {
  24399. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24400. this._currentPlugin.setGravity(this.gravity);
  24401. };
  24402. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  24403. return this._currentPlugin.registerMesh(mesh, impostor, options);
  24404. };
  24405. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  24406. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  24407. };
  24408. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  24409. this._currentPlugin.unregisterMesh(mesh);
  24410. };
  24411. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  24412. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  24413. };
  24414. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24415. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  24416. };
  24417. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  24418. this._currentPlugin.updateBodyPosition(mesh);
  24419. };
  24420. PhysicsEngine.prototype.dispose = function () {
  24421. this._currentPlugin.dispose();
  24422. };
  24423. PhysicsEngine.prototype.isSupported = function () {
  24424. return this._currentPlugin.isSupported();
  24425. };
  24426. // Statics
  24427. PhysicsEngine.NoImpostor = 0;
  24428. PhysicsEngine.SphereImpostor = 1;
  24429. PhysicsEngine.BoxImpostor = 2;
  24430. PhysicsEngine.PlaneImpostor = 3;
  24431. PhysicsEngine.MeshImpostor = 4;
  24432. PhysicsEngine.CapsuleImpostor = 5;
  24433. PhysicsEngine.ConeImpostor = 6;
  24434. PhysicsEngine.CylinderImpostor = 7;
  24435. PhysicsEngine.ConvexHullImpostor = 8;
  24436. PhysicsEngine.Epsilon = 0.001;
  24437. return PhysicsEngine;
  24438. })();
  24439. BABYLON.PhysicsEngine = PhysicsEngine;
  24440. })(BABYLON || (BABYLON = {}));
  24441. var BABYLON;
  24442. (function (BABYLON) {
  24443. var serializeLight = function (light) {
  24444. var serializationObject = {};
  24445. serializationObject.name = light.name;
  24446. serializationObject.id = light.id;
  24447. serializationObject.tags = BABYLON.Tags.GetTags(light);
  24448. if (light instanceof BABYLON.PointLight) {
  24449. serializationObject.type = 0;
  24450. serializationObject.position = (light).position.asArray();
  24451. }
  24452. else if (light instanceof BABYLON.DirectionalLight) {
  24453. serializationObject.type = 1;
  24454. var directionalLight = light;
  24455. serializationObject.position = directionalLight.position.asArray();
  24456. serializationObject.direction = directionalLight.direction.asArray();
  24457. }
  24458. else if (light instanceof BABYLON.SpotLight) {
  24459. serializationObject.type = 2;
  24460. var spotLight = light;
  24461. serializationObject.position = spotLight.position.asArray();
  24462. serializationObject.direction = spotLight.position.asArray();
  24463. serializationObject.angle = spotLight.angle;
  24464. serializationObject.exponent = spotLight.exponent;
  24465. }
  24466. else if (light instanceof BABYLON.HemisphericLight) {
  24467. serializationObject.type = 3;
  24468. var hemisphericLight = light;
  24469. serializationObject.direction = hemisphericLight.direction.asArray();
  24470. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  24471. }
  24472. if (light.intensity) {
  24473. serializationObject.intensity = light.intensity;
  24474. }
  24475. serializationObject.range = light.range;
  24476. serializationObject.diffuse = light.diffuse.asArray();
  24477. serializationObject.specular = light.specular.asArray();
  24478. return serializationObject;
  24479. };
  24480. var serializeFresnelParameter = function (fresnelParameter) {
  24481. var serializationObject = {};
  24482. serializationObject.isEnabled = fresnelParameter.isEnabled;
  24483. serializationObject.leftColor = fresnelParameter.leftColor;
  24484. serializationObject.rightColor = fresnelParameter.rightColor;
  24485. serializationObject.bias = fresnelParameter.bias;
  24486. serializationObject.power = fresnelParameter.power;
  24487. return serializationObject;
  24488. };
  24489. var serializeAnimation;
  24490. var appendAnimations = function (source, destination) {
  24491. if (source.animations) {
  24492. destination.animations = [];
  24493. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24494. var animation = source.animations[animationIndex];
  24495. destination.animations.push(serializeAnimation(animation));
  24496. }
  24497. }
  24498. };
  24499. var serializeCamera = function (camera) {
  24500. var serializationObject = {};
  24501. serializationObject.name = camera.name;
  24502. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24503. serializationObject.id = camera.id;
  24504. serializationObject.position = camera.position.asArray();
  24505. // Parent
  24506. if (camera.parent) {
  24507. serializationObject.parentId = camera.parent.id;
  24508. }
  24509. serializationObject.fov = camera.fov;
  24510. serializationObject.minZ = camera.minZ;
  24511. serializationObject.maxZ = camera.maxZ;
  24512. serializationObject.inertia = camera.inertia;
  24513. //setting the type
  24514. if (camera instanceof BABYLON.FreeCamera) {
  24515. serializationObject.type = "FreeCamera";
  24516. }
  24517. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24518. serializationObject.type = "ArcRotateCamera";
  24519. }
  24520. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24521. serializationObject.type = "AnaglyphArcRotateCamera";
  24522. }
  24523. else if (camera instanceof BABYLON.GamepadCamera) {
  24524. serializationObject.type = "GamepadCamera";
  24525. }
  24526. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24527. serializationObject.type = "AnaglyphFreeCamera";
  24528. }
  24529. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24530. serializationObject.type = "DeviceOrientationCamera";
  24531. }
  24532. else if (camera instanceof BABYLON.FollowCamera) {
  24533. serializationObject.type = "FollowCamera";
  24534. }
  24535. else if (camera instanceof BABYLON.TouchCamera) {
  24536. serializationObject.type = "TouchCamera";
  24537. }
  24538. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24539. serializationObject.type = "VirtualJoysticksCamera";
  24540. }
  24541. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24542. serializationObject.type = "WebVRFreeCamera";
  24543. }
  24544. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24545. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24546. }
  24547. //special properties of specific cameras
  24548. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24549. var arcCamera = camera;
  24550. serializationObject.alpha = arcCamera.alpha;
  24551. serializationObject.beta = arcCamera.beta;
  24552. serializationObject.radius = arcCamera.radius;
  24553. if (arcCamera.target && arcCamera.target.id) {
  24554. serializationObject.lockedTargetId = arcCamera.target.id;
  24555. }
  24556. }
  24557. else if (camera instanceof BABYLON.FollowCamera) {
  24558. var followCam = camera;
  24559. serializationObject.radius = followCam.radius;
  24560. serializationObject.heightOffset = followCam.heightOffset;
  24561. serializationObject.rotationOffset = followCam.rotationOffset;
  24562. }
  24563. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24564. //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.
  24565. if (camera['_interaxialDistance'] !== undefined) {
  24566. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24567. }
  24568. }
  24569. //general properties that not all cameras have. The [] is due to typescript's type safety
  24570. if (camera['speed'] !== undefined) {
  24571. serializationObject.speed = camera['speed'];
  24572. }
  24573. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24574. serializationObject.target = camera['target'].asArray();
  24575. }
  24576. // Target
  24577. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24578. serializationObject.rotation = camera['rotation'].asArray();
  24579. }
  24580. // Locked target
  24581. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24582. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24583. }
  24584. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24585. serializationObject.applyGravity = camera['applyGravity'] || false;
  24586. if (camera['ellipsoid']) {
  24587. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24588. }
  24589. // Animations
  24590. appendAnimations(camera, serializationObject);
  24591. // Layer mask
  24592. serializationObject.layerMask = camera.layerMask;
  24593. return serializationObject;
  24594. };
  24595. serializeAnimation = function (animation) {
  24596. var serializationObject = {};
  24597. serializationObject.name = animation.name;
  24598. serializationObject.property = animation.targetProperty;
  24599. serializationObject.framePerSecond = animation.framePerSecond;
  24600. serializationObject.dataType = animation.dataType;
  24601. serializationObject.loopBehavior = animation.loopMode;
  24602. var dataType = animation.dataType;
  24603. serializationObject.keys = [];
  24604. var keys = animation.getKeys();
  24605. for (var index = 0; index < keys.length; index++) {
  24606. var animationKey = keys[index];
  24607. var key = {};
  24608. key.frame = animationKey.frame;
  24609. switch (dataType) {
  24610. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24611. key.values = [animationKey.value];
  24612. break;
  24613. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24614. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24615. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24616. key.values = animationKey.value.asArray();
  24617. break;
  24618. }
  24619. serializationObject.keys.push(key);
  24620. }
  24621. return serializationObject;
  24622. };
  24623. var serializeMultiMaterial = function (material) {
  24624. var serializationObject = {};
  24625. serializationObject.name = material.name;
  24626. serializationObject.id = material.id;
  24627. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24628. serializationObject.materials = [];
  24629. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24630. var subMat = material.subMaterials[matIndex];
  24631. if (subMat) {
  24632. serializationObject.materials.push(subMat.id);
  24633. }
  24634. else {
  24635. serializationObject.materials.push(null);
  24636. }
  24637. }
  24638. return serializationObject;
  24639. };
  24640. var serializeTexture;
  24641. var serializeMaterial = function (material) {
  24642. var serializationObject = {};
  24643. serializationObject.name = material.name;
  24644. serializationObject.ambient = material.ambientColor.asArray();
  24645. serializationObject.diffuse = material.diffuseColor.asArray();
  24646. serializationObject.specular = material.specularColor.asArray();
  24647. serializationObject.specularPower = material.specularPower;
  24648. serializationObject.emissive = material.emissiveColor.asArray();
  24649. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24650. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24651. serializationObject.alpha = material.alpha;
  24652. serializationObject.id = material.id;
  24653. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24654. serializationObject.backFaceCulling = material.backFaceCulling;
  24655. if (material.diffuseTexture) {
  24656. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24657. }
  24658. if (material.diffuseFresnelParameters) {
  24659. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24660. }
  24661. if (material.ambientTexture) {
  24662. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24663. }
  24664. if (material.opacityTexture) {
  24665. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24666. }
  24667. if (material.opacityFresnelParameters) {
  24668. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24669. }
  24670. if (material.reflectionTexture) {
  24671. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24672. }
  24673. if (material.reflectionFresnelParameters) {
  24674. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24675. }
  24676. if (material.emissiveTexture) {
  24677. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24678. }
  24679. if (material.lightmapTexture) {
  24680. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  24681. serializationObject.lightmapThreshold = material.lightmapThreshold;
  24682. }
  24683. if (material.emissiveFresnelParameters) {
  24684. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24685. }
  24686. if (material.specularTexture) {
  24687. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24688. }
  24689. if (material.bumpTexture) {
  24690. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24691. }
  24692. return serializationObject;
  24693. };
  24694. serializeTexture = function (texture) {
  24695. var serializationObject = {};
  24696. if (!texture.name) {
  24697. return null;
  24698. }
  24699. if (texture instanceof BABYLON.CubeTexture) {
  24700. serializationObject.name = texture.name;
  24701. serializationObject.hasAlpha = texture.hasAlpha;
  24702. serializationObject.isCube = true;
  24703. serializationObject.level = texture.level;
  24704. serializationObject.coordinatesMode = texture.coordinatesMode;
  24705. return serializationObject;
  24706. }
  24707. var index;
  24708. if (texture instanceof BABYLON.MirrorTexture) {
  24709. var mirrorTexture = texture;
  24710. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24711. serializationObject.renderList = [];
  24712. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24713. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24714. }
  24715. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24716. }
  24717. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24718. var renderTargetTexture = texture;
  24719. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24720. serializationObject.renderList = [];
  24721. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24722. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24723. }
  24724. }
  24725. var regularTexture = texture;
  24726. serializationObject.name = texture.name;
  24727. serializationObject.hasAlpha = texture.hasAlpha;
  24728. serializationObject.level = texture.level;
  24729. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24730. serializationObject.coordinatesMode = texture.coordinatesMode;
  24731. serializationObject.uOffset = regularTexture.uOffset;
  24732. serializationObject.vOffset = regularTexture.vOffset;
  24733. serializationObject.uScale = regularTexture.uScale;
  24734. serializationObject.vScale = regularTexture.vScale;
  24735. serializationObject.uAng = regularTexture.uAng;
  24736. serializationObject.vAng = regularTexture.vAng;
  24737. serializationObject.wAng = regularTexture.wAng;
  24738. serializationObject.wrapU = texture.wrapU;
  24739. serializationObject.wrapV = texture.wrapV;
  24740. // Animations
  24741. appendAnimations(texture, serializationObject);
  24742. return serializationObject;
  24743. };
  24744. var serializeSkeleton = function (skeleton) {
  24745. var serializationObject = {};
  24746. serializationObject.name = skeleton.name;
  24747. serializationObject.id = skeleton.id;
  24748. serializationObject.bones = [];
  24749. for (var index = 0; index < skeleton.bones.length; index++) {
  24750. var bone = skeleton.bones[index];
  24751. var serializedBone = {
  24752. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24753. name: bone.name,
  24754. matrix: bone.getLocalMatrix().toArray()
  24755. };
  24756. serializationObject.bones.push(serializedBone);
  24757. if (bone.animations && bone.animations.length > 0) {
  24758. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24759. }
  24760. }
  24761. return serializationObject;
  24762. };
  24763. var serializeParticleSystem = function (particleSystem) {
  24764. var serializationObject = {};
  24765. serializationObject.emitterId = particleSystem.emitter.id;
  24766. serializationObject.capacity = particleSystem.getCapacity();
  24767. if (particleSystem.particleTexture) {
  24768. serializationObject.textureName = particleSystem.particleTexture.name;
  24769. }
  24770. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24771. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24772. serializationObject.minSize = particleSystem.minSize;
  24773. serializationObject.maxSize = particleSystem.maxSize;
  24774. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24775. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24776. serializationObject.emitRate = particleSystem.emitRate;
  24777. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24778. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24779. serializationObject.gravity = particleSystem.gravity.asArray();
  24780. serializationObject.direction1 = particleSystem.direction1.asArray();
  24781. serializationObject.direction2 = particleSystem.direction2.asArray();
  24782. serializationObject.color1 = particleSystem.color1.asArray();
  24783. serializationObject.color2 = particleSystem.color2.asArray();
  24784. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24785. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24786. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24787. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24788. serializationObject.blendMode = particleSystem.blendMode;
  24789. return serializationObject;
  24790. };
  24791. var serializeLensFlareSystem = function (lensFlareSystem) {
  24792. var serializationObject = {};
  24793. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24794. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24795. serializationObject.flares = [];
  24796. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24797. var flare = lensFlareSystem.lensFlares[index];
  24798. serializationObject.flares.push({
  24799. size: flare.size,
  24800. position: flare.position,
  24801. color: flare.color.asArray(),
  24802. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24803. });
  24804. }
  24805. return serializationObject;
  24806. };
  24807. var serializeShadowGenerator = function (light) {
  24808. var serializationObject = {};
  24809. var shadowGenerator = light.getShadowGenerator();
  24810. serializationObject.lightId = light.id;
  24811. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24812. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24813. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24814. serializationObject.renderList = [];
  24815. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24816. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24817. serializationObject.renderList.push(mesh.id);
  24818. }
  24819. return serializationObject;
  24820. };
  24821. var serializedGeometries = [];
  24822. var serializeVertexData;
  24823. var serializeTorusKnot;
  24824. var serializePlane;
  24825. var serializeGround;
  24826. var serializeTorus;
  24827. var serializeCylinder;
  24828. var serializeSphere;
  24829. var serializeBox;
  24830. var serializeGeometry = function (geometry, serializationGeometries) {
  24831. if (serializedGeometries[geometry.id]) {
  24832. return;
  24833. }
  24834. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24835. serializationGeometries.boxes.push(serializeBox(geometry));
  24836. }
  24837. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24838. serializationGeometries.spheres.push(serializeSphere(geometry));
  24839. }
  24840. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24841. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24842. }
  24843. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24844. serializationGeometries.toruses.push(serializeTorus(geometry));
  24845. }
  24846. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24847. serializationGeometries.grounds.push(serializeGround(geometry));
  24848. }
  24849. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24850. serializationGeometries.planes.push(serializePlane(geometry));
  24851. }
  24852. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24853. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24854. }
  24855. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24856. throw new Error("Unknown primitive type");
  24857. }
  24858. else {
  24859. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24860. }
  24861. serializedGeometries[geometry.id] = true;
  24862. };
  24863. var serializeGeometryBase = function (geometry) {
  24864. var serializationObject = {};
  24865. serializationObject.id = geometry.id;
  24866. if (BABYLON.Tags.HasTags(geometry)) {
  24867. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24868. }
  24869. return serializationObject;
  24870. };
  24871. serializeVertexData = function (vertexData) {
  24872. var serializationObject = serializeGeometryBase(vertexData);
  24873. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24874. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24875. }
  24876. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24877. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24878. }
  24879. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24880. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24881. }
  24882. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24883. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24884. }
  24885. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24886. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24887. }
  24888. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24889. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24890. }
  24891. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24892. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24893. }
  24894. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24895. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24896. }
  24897. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24898. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24899. }
  24900. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24901. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24902. serializationObject.matricesIndices._isExpanded = true;
  24903. }
  24904. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24905. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24906. }
  24907. serializationObject.indices = vertexData.getIndices();
  24908. return serializationObject;
  24909. };
  24910. var serializePrimitive = function (primitive) {
  24911. var serializationObject = serializeGeometryBase(primitive);
  24912. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24913. return serializationObject;
  24914. };
  24915. serializeBox = function (box) {
  24916. var serializationObject = serializePrimitive(box);
  24917. serializationObject.size = box.size;
  24918. return serializationObject;
  24919. };
  24920. serializeSphere = function (sphere) {
  24921. var serializationObject = serializePrimitive(sphere);
  24922. serializationObject.segments = sphere.segments;
  24923. serializationObject.diameter = sphere.diameter;
  24924. return serializationObject;
  24925. };
  24926. serializeCylinder = function (cylinder) {
  24927. var serializationObject = serializePrimitive(cylinder);
  24928. serializationObject.height = cylinder.height;
  24929. serializationObject.diameterTop = cylinder.diameterTop;
  24930. serializationObject.diameterBottom = cylinder.diameterBottom;
  24931. serializationObject.tessellation = cylinder.tessellation;
  24932. return serializationObject;
  24933. };
  24934. serializeTorus = function (torus) {
  24935. var serializationObject = serializePrimitive(torus);
  24936. serializationObject.diameter = torus.diameter;
  24937. serializationObject.thickness = torus.thickness;
  24938. serializationObject.tessellation = torus.tessellation;
  24939. return serializationObject;
  24940. };
  24941. serializeGround = function (ground) {
  24942. var serializationObject = serializePrimitive(ground);
  24943. serializationObject.width = ground.width;
  24944. serializationObject.height = ground.height;
  24945. serializationObject.subdivisions = ground.subdivisions;
  24946. return serializationObject;
  24947. };
  24948. serializePlane = function (plane) {
  24949. var serializationObject = serializePrimitive(plane);
  24950. serializationObject.size = plane.size;
  24951. return serializationObject;
  24952. };
  24953. serializeTorusKnot = function (torusKnot) {
  24954. var serializationObject = serializePrimitive(torusKnot);
  24955. serializationObject.radius = torusKnot.radius;
  24956. serializationObject.tube = torusKnot.tube;
  24957. serializationObject.radialSegments = torusKnot.radialSegments;
  24958. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24959. serializationObject.p = torusKnot.p;
  24960. serializationObject.q = torusKnot.q;
  24961. return serializationObject;
  24962. };
  24963. var serializeMesh = function (mesh, serializationScene) {
  24964. var serializationObject = {};
  24965. serializationObject.name = mesh.name;
  24966. serializationObject.id = mesh.id;
  24967. if (BABYLON.Tags.HasTags(mesh)) {
  24968. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24969. }
  24970. serializationObject.position = mesh.position.asArray();
  24971. if (mesh.rotationQuaternion) {
  24972. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24973. }
  24974. else if (mesh.rotation) {
  24975. serializationObject.rotation = mesh.rotation.asArray();
  24976. }
  24977. serializationObject.scaling = mesh.scaling.asArray();
  24978. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24979. serializationObject.isEnabled = mesh.isEnabled();
  24980. serializationObject.isVisible = mesh.isVisible;
  24981. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24982. serializationObject.pickable = mesh.isPickable;
  24983. serializationObject.receiveShadows = mesh.receiveShadows;
  24984. serializationObject.billboardMode = mesh.billboardMode;
  24985. serializationObject.visibility = mesh.visibility;
  24986. serializationObject.checkCollisions = mesh.checkCollisions;
  24987. // Parent
  24988. if (mesh.parent) {
  24989. serializationObject.parentId = mesh.parent.id;
  24990. }
  24991. // Geometry
  24992. var geometry = mesh._geometry;
  24993. if (geometry) {
  24994. var geometryId = geometry.id;
  24995. serializationObject.geometryId = geometryId;
  24996. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24997. // 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
  24998. serializeGeometry(geometry, serializationScene.geometries);
  24999. }
  25000. // SubMeshes
  25001. serializationObject.subMeshes = [];
  25002. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25003. var subMesh = mesh.subMeshes[subIndex];
  25004. serializationObject.subMeshes.push({
  25005. materialIndex: subMesh.materialIndex,
  25006. verticesStart: subMesh.verticesStart,
  25007. verticesCount: subMesh.verticesCount,
  25008. indexStart: subMesh.indexStart,
  25009. indexCount: subMesh.indexCount
  25010. });
  25011. }
  25012. }
  25013. // Material
  25014. if (mesh.material) {
  25015. serializationObject.materialId = mesh.material.id;
  25016. }
  25017. else {
  25018. mesh.material = null;
  25019. }
  25020. // Skeleton
  25021. if (mesh.skeleton) {
  25022. serializationObject.skeletonId = mesh.skeleton.id;
  25023. }
  25024. // Physics
  25025. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  25026. serializationObject.physicsMass = mesh.getPhysicsMass();
  25027. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  25028. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  25029. switch (mesh.getPhysicsImpostor()) {
  25030. case BABYLON.PhysicsEngine.BoxImpostor:
  25031. serializationObject.physicsImpostor = 1;
  25032. break;
  25033. case BABYLON.PhysicsEngine.SphereImpostor:
  25034. serializationObject.physicsImpostor = 2;
  25035. break;
  25036. }
  25037. }
  25038. // Instances
  25039. serializationObject.instances = [];
  25040. for (var index = 0; index < mesh.instances.length; index++) {
  25041. var instance = mesh.instances[index];
  25042. var serializationInstance = {
  25043. name: instance.name,
  25044. position: instance.position.asArray(),
  25045. rotation: instance.rotation.asArray(),
  25046. rotationQuaternion: instance.rotationQuaternion.asArray(),
  25047. scaling: instance.scaling.asArray()
  25048. };
  25049. serializationObject.instances.push(serializationInstance);
  25050. // Animations
  25051. appendAnimations(instance, serializationInstance);
  25052. }
  25053. // Animations
  25054. appendAnimations(mesh, serializationObject);
  25055. // Layer mask
  25056. serializationObject.layerMask = mesh.layerMask;
  25057. return serializationObject;
  25058. };
  25059. var finalizeSingleMesh = function (mesh, serializationObject) {
  25060. //only works if the mesh is already loaded
  25061. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  25062. //serialize material
  25063. if (mesh.material) {
  25064. if (mesh.material instanceof BABYLON.StandardMaterial) {
  25065. serializationObject.materials = serializationObject.materials || [];
  25066. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  25067. serializationObject.materials.push(serializeMaterial(mesh.material));
  25068. }
  25069. }
  25070. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  25071. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  25072. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  25073. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  25074. }
  25075. }
  25076. }
  25077. //serialize geometry
  25078. var geometry = mesh._geometry;
  25079. if (geometry) {
  25080. if (!serializationObject.geometries) {
  25081. serializationObject.geometries = {};
  25082. serializationObject.geometries.boxes = [];
  25083. serializationObject.geometries.spheres = [];
  25084. serializationObject.geometries.cylinders = [];
  25085. serializationObject.geometries.toruses = [];
  25086. serializationObject.geometries.grounds = [];
  25087. serializationObject.geometries.planes = [];
  25088. serializationObject.geometries.torusKnots = [];
  25089. serializationObject.geometries.vertexData = [];
  25090. }
  25091. serializeGeometry(geometry, serializationObject.geometries);
  25092. }
  25093. // Skeletons
  25094. if (mesh.skeleton) {
  25095. serializationObject.skeletons = serializationObject.skeletons || [];
  25096. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  25097. }
  25098. //serialize the actual mesh
  25099. serializationObject.meshes = serializationObject.meshes || [];
  25100. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  25101. }
  25102. };
  25103. var SceneSerializer = (function () {
  25104. function SceneSerializer() {
  25105. }
  25106. SceneSerializer.Serialize = function (scene) {
  25107. var serializationObject = {};
  25108. // Scene
  25109. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  25110. serializationObject.autoClear = scene.autoClear;
  25111. serializationObject.clearColor = scene.clearColor.asArray();
  25112. serializationObject.ambientColor = scene.ambientColor.asArray();
  25113. serializationObject.gravity = scene.gravity.asArray();
  25114. // Fog
  25115. if (scene.fogMode && scene.fogMode !== 0) {
  25116. serializationObject.fogMode = scene.fogMode;
  25117. serializationObject.fogColor = scene.fogColor.asArray();
  25118. serializationObject.fogStart = scene.fogStart;
  25119. serializationObject.fogEnd = scene.fogEnd;
  25120. serializationObject.fogDensity = scene.fogDensity;
  25121. }
  25122. // Lights
  25123. serializationObject.lights = [];
  25124. var index;
  25125. var light;
  25126. for (index = 0; index < scene.lights.length; index++) {
  25127. light = scene.lights[index];
  25128. serializationObject.lights.push(serializeLight(light));
  25129. }
  25130. // Cameras
  25131. serializationObject.cameras = [];
  25132. for (index = 0; index < scene.cameras.length; index++) {
  25133. var camera = scene.cameras[index];
  25134. serializationObject.cameras.push(serializeCamera(camera));
  25135. }
  25136. if (scene.activeCamera) {
  25137. serializationObject.activeCameraID = scene.activeCamera.id;
  25138. }
  25139. // Materials
  25140. serializationObject.materials = [];
  25141. serializationObject.multiMaterials = [];
  25142. var material;
  25143. for (index = 0; index < scene.materials.length; index++) {
  25144. material = scene.materials[index];
  25145. serializationObject.materials.push(serializeMaterial(material));
  25146. }
  25147. // MultiMaterials
  25148. serializationObject.multiMaterials = [];
  25149. for (index = 0; index < scene.multiMaterials.length; index++) {
  25150. var multiMaterial = scene.multiMaterials[index];
  25151. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  25152. }
  25153. for (index = 0; index < scene.materials.length; index++) {
  25154. material = scene.materials[index];
  25155. if (material instanceof BABYLON.StandardMaterial) {
  25156. serializationObject.materials.push(serializeMaterial(material));
  25157. }
  25158. else if (material instanceof BABYLON.MultiMaterial) {
  25159. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  25160. }
  25161. }
  25162. // Skeletons
  25163. serializationObject.skeletons = [];
  25164. for (index = 0; index < scene.skeletons.length; index++) {
  25165. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  25166. }
  25167. // Geometries
  25168. serializationObject.geometries = {};
  25169. serializationObject.geometries.boxes = [];
  25170. serializationObject.geometries.spheres = [];
  25171. serializationObject.geometries.cylinders = [];
  25172. serializationObject.geometries.toruses = [];
  25173. serializationObject.geometries.grounds = [];
  25174. serializationObject.geometries.planes = [];
  25175. serializationObject.geometries.torusKnots = [];
  25176. serializationObject.geometries.vertexData = [];
  25177. serializedGeometries = [];
  25178. var geometries = scene.getGeometries();
  25179. for (index = 0; index < geometries.length; index++) {
  25180. var geometry = geometries[index];
  25181. if (geometry.isReady()) {
  25182. serializeGeometry(geometry, serializationObject.geometries);
  25183. }
  25184. }
  25185. // Meshes
  25186. serializationObject.meshes = [];
  25187. for (index = 0; index < scene.meshes.length; index++) {
  25188. var abstractMesh = scene.meshes[index];
  25189. if (abstractMesh instanceof BABYLON.Mesh) {
  25190. var mesh = abstractMesh;
  25191. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  25192. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  25193. }
  25194. }
  25195. }
  25196. // Particles Systems
  25197. serializationObject.particleSystems = [];
  25198. for (index = 0; index < scene.particleSystems.length; index++) {
  25199. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  25200. }
  25201. // Lens flares
  25202. serializationObject.lensFlareSystems = [];
  25203. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  25204. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  25205. }
  25206. // Shadows
  25207. serializationObject.shadowGenerators = [];
  25208. for (index = 0; index < scene.lights.length; index++) {
  25209. light = scene.lights[index];
  25210. if (light.getShadowGenerator()) {
  25211. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  25212. }
  25213. }
  25214. return serializationObject;
  25215. };
  25216. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  25217. if (withParents === void 0) { withParents = false; }
  25218. if (withChildren === void 0) { withChildren = false; }
  25219. var serializationObject = {};
  25220. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  25221. if (withParents || withChildren) {
  25222. //deliberate for loop! not for each, appended should be processed as well.
  25223. for (var i = 0; i < toSerialize.length; ++i) {
  25224. if (withChildren) {
  25225. toSerialize[i].getDescendants().forEach(function (node) {
  25226. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  25227. toSerialize.push(node);
  25228. }
  25229. });
  25230. }
  25231. //make sure the array doesn't contain the object already
  25232. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  25233. toSerialize.push(toSerialize[i].parent);
  25234. }
  25235. }
  25236. }
  25237. toSerialize.forEach(function (mesh) {
  25238. finalizeSingleMesh(mesh, serializationObject);
  25239. });
  25240. return serializationObject;
  25241. };
  25242. return SceneSerializer;
  25243. })();
  25244. BABYLON.SceneSerializer = SceneSerializer;
  25245. })(BABYLON || (BABYLON = {}));
  25246. var BABYLON;
  25247. (function (BABYLON) {
  25248. // Unique ID when we import meshes from Babylon to CSG
  25249. var currentCSGMeshId = 0;
  25250. // # class Vertex
  25251. // Represents a vertex of a polygon. Use your own vertex class instead of this
  25252. // one to provide additional features like texture coordinates and vertex
  25253. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  25254. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  25255. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  25256. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  25257. // is not used anywhere else.
  25258. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  25259. var Vertex = (function () {
  25260. function Vertex(pos, normal, uv) {
  25261. this.pos = pos;
  25262. this.normal = normal;
  25263. this.uv = uv;
  25264. }
  25265. Vertex.prototype.clone = function () {
  25266. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  25267. };
  25268. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  25269. // orientation of a polygon is flipped.
  25270. Vertex.prototype.flip = function () {
  25271. this.normal = this.normal.scale(-1);
  25272. };
  25273. // Create a new vertex between this vertex and `other` by linearly
  25274. // interpolating all properties using a parameter of `t`. Subclasses should
  25275. // override this to interpolate additional properties.
  25276. Vertex.prototype.interpolate = function (other, t) {
  25277. 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));
  25278. };
  25279. return Vertex;
  25280. })();
  25281. // # class Plane
  25282. // Represents a plane in 3D space.
  25283. var Plane = (function () {
  25284. function Plane(normal, w) {
  25285. this.normal = normal;
  25286. this.w = w;
  25287. }
  25288. Plane.FromPoints = function (a, b, c) {
  25289. var v0 = c.subtract(a);
  25290. var v1 = b.subtract(a);
  25291. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  25292. return null;
  25293. }
  25294. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  25295. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  25296. };
  25297. Plane.prototype.clone = function () {
  25298. return new Plane(this.normal.clone(), this.w);
  25299. };
  25300. Plane.prototype.flip = function () {
  25301. this.normal.scaleInPlace(-1);
  25302. this.w = -this.w;
  25303. };
  25304. // Split `polygon` by this plane if needed, then put the polygon or polygon
  25305. // fragments in the appropriate lists. Coplanar polygons go into either
  25306. // `coplanarFront` or `coplanarBack` depending on their orientation with
  25307. // respect to this plane. Polygons in front or in back of this plane go into
  25308. // either `front` or `back`.
  25309. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  25310. var COPLANAR = 0;
  25311. var FRONT = 1;
  25312. var BACK = 2;
  25313. var SPANNING = 3;
  25314. // Classify each point as well as the entire polygon into one of the above
  25315. // four classes.
  25316. var polygonType = 0;
  25317. var types = [];
  25318. for (var i = 0; i < polygon.vertices.length; i++) {
  25319. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  25320. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  25321. polygonType |= type;
  25322. types.push(type);
  25323. }
  25324. // Put the polygon in the correct list, splitting it when necessary.
  25325. switch (polygonType) {
  25326. case COPLANAR:
  25327. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  25328. break;
  25329. case FRONT:
  25330. front.push(polygon);
  25331. break;
  25332. case BACK:
  25333. back.push(polygon);
  25334. break;
  25335. case SPANNING:
  25336. var f = [], b = [];
  25337. for (i = 0; i < polygon.vertices.length; i++) {
  25338. var j = (i + 1) % polygon.vertices.length;
  25339. var ti = types[i], tj = types[j];
  25340. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  25341. if (ti != BACK)
  25342. f.push(vi);
  25343. if (ti != FRONT)
  25344. b.push(ti != BACK ? vi.clone() : vi);
  25345. if ((ti | tj) == SPANNING) {
  25346. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  25347. var v = vi.interpolate(vj, t);
  25348. f.push(v);
  25349. b.push(v.clone());
  25350. }
  25351. }
  25352. if (f.length >= 3) {
  25353. var poly = new Polygon(f, polygon.shared);
  25354. if (poly.plane)
  25355. front.push(poly);
  25356. }
  25357. if (b.length >= 3) {
  25358. poly = new Polygon(b, polygon.shared);
  25359. if (poly.plane)
  25360. back.push(poly);
  25361. }
  25362. break;
  25363. }
  25364. };
  25365. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  25366. // point is on the plane.
  25367. Plane.EPSILON = 1e-5;
  25368. return Plane;
  25369. })();
  25370. // # class Polygon
  25371. // Represents a convex polygon. The vertices used to initialize a polygon must
  25372. // be coplanar and form a convex loop.
  25373. //
  25374. // Each convex polygon has a `shared` property, which is shared between all
  25375. // polygons that are clones of each other or were split from the same polygon.
  25376. // This can be used to define per-polygon properties (such as surface color).
  25377. var Polygon = (function () {
  25378. function Polygon(vertices, shared) {
  25379. this.vertices = vertices;
  25380. this.shared = shared;
  25381. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  25382. }
  25383. Polygon.prototype.clone = function () {
  25384. var vertices = this.vertices.map(function (v) { return v.clone(); });
  25385. return new Polygon(vertices, this.shared);
  25386. };
  25387. Polygon.prototype.flip = function () {
  25388. this.vertices.reverse().map(function (v) { v.flip(); });
  25389. this.plane.flip();
  25390. };
  25391. return Polygon;
  25392. })();
  25393. // # class Node
  25394. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  25395. // by picking a polygon to split along. That polygon (and all other coplanar
  25396. // polygons) are added directly to that node and the other polygons are added to
  25397. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  25398. // no distinction between internal and leaf nodes.
  25399. var Node = (function () {
  25400. function Node(polygons) {
  25401. this.plane = null;
  25402. this.front = null;
  25403. this.back = null;
  25404. this.polygons = [];
  25405. if (polygons) {
  25406. this.build(polygons);
  25407. }
  25408. }
  25409. Node.prototype.clone = function () {
  25410. var node = new Node();
  25411. node.plane = this.plane && this.plane.clone();
  25412. node.front = this.front && this.front.clone();
  25413. node.back = this.back && this.back.clone();
  25414. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  25415. return node;
  25416. };
  25417. // Convert solid space to empty space and empty space to solid space.
  25418. Node.prototype.invert = function () {
  25419. for (var i = 0; i < this.polygons.length; i++) {
  25420. this.polygons[i].flip();
  25421. }
  25422. if (this.plane) {
  25423. this.plane.flip();
  25424. }
  25425. if (this.front) {
  25426. this.front.invert();
  25427. }
  25428. if (this.back) {
  25429. this.back.invert();
  25430. }
  25431. var temp = this.front;
  25432. this.front = this.back;
  25433. this.back = temp;
  25434. };
  25435. // Recursively remove all polygons in `polygons` that are inside this BSP
  25436. // tree.
  25437. Node.prototype.clipPolygons = function (polygons) {
  25438. if (!this.plane)
  25439. return polygons.slice();
  25440. var front = [], back = [];
  25441. for (var i = 0; i < polygons.length; i++) {
  25442. this.plane.splitPolygon(polygons[i], front, back, front, back);
  25443. }
  25444. if (this.front) {
  25445. front = this.front.clipPolygons(front);
  25446. }
  25447. if (this.back) {
  25448. back = this.back.clipPolygons(back);
  25449. }
  25450. else {
  25451. back = [];
  25452. }
  25453. return front.concat(back);
  25454. };
  25455. // Remove all polygons in this BSP tree that are inside the other BSP tree
  25456. // `bsp`.
  25457. Node.prototype.clipTo = function (bsp) {
  25458. this.polygons = bsp.clipPolygons(this.polygons);
  25459. if (this.front)
  25460. this.front.clipTo(bsp);
  25461. if (this.back)
  25462. this.back.clipTo(bsp);
  25463. };
  25464. // Return a list of all polygons in this BSP tree.
  25465. Node.prototype.allPolygons = function () {
  25466. var polygons = this.polygons.slice();
  25467. if (this.front)
  25468. polygons = polygons.concat(this.front.allPolygons());
  25469. if (this.back)
  25470. polygons = polygons.concat(this.back.allPolygons());
  25471. return polygons;
  25472. };
  25473. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  25474. // new polygons are filtered down to the bottom of the tree and become new
  25475. // nodes there. Each set of polygons is partitioned using the first polygon
  25476. // (no heuristic is used to pick a good split).
  25477. Node.prototype.build = function (polygons) {
  25478. if (!polygons.length)
  25479. return;
  25480. if (!this.plane)
  25481. this.plane = polygons[0].plane.clone();
  25482. var front = [], back = [];
  25483. for (var i = 0; i < polygons.length; i++) {
  25484. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  25485. }
  25486. if (front.length) {
  25487. if (!this.front)
  25488. this.front = new Node();
  25489. this.front.build(front);
  25490. }
  25491. if (back.length) {
  25492. if (!this.back)
  25493. this.back = new Node();
  25494. this.back.build(back);
  25495. }
  25496. };
  25497. return Node;
  25498. })();
  25499. var CSG = (function () {
  25500. function CSG() {
  25501. this.polygons = new Array();
  25502. }
  25503. // Convert BABYLON.Mesh to BABYLON.CSG
  25504. CSG.FromMesh = function (mesh) {
  25505. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25506. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25507. if (mesh instanceof BABYLON.Mesh) {
  25508. mesh.computeWorldMatrix(true);
  25509. matrix = mesh.getWorldMatrix();
  25510. meshPosition = mesh.position.clone();
  25511. meshRotation = mesh.rotation.clone();
  25512. if (mesh.rotationQuaternion) {
  25513. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25514. }
  25515. meshScaling = mesh.scaling.clone();
  25516. }
  25517. else {
  25518. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25519. }
  25520. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25521. var subMeshes = mesh.subMeshes;
  25522. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25523. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25524. vertices = [];
  25525. for (var j = 0; j < 3; j++) {
  25526. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25527. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25528. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25529. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25530. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25531. vertex = new Vertex(position, normal, uv);
  25532. vertices.push(vertex);
  25533. }
  25534. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25535. // To handle the case of degenerated triangle
  25536. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25537. if (polygon.plane)
  25538. polygons.push(polygon);
  25539. }
  25540. }
  25541. var csg = CSG.FromPolygons(polygons);
  25542. csg.matrix = matrix;
  25543. csg.position = meshPosition;
  25544. csg.rotation = meshRotation;
  25545. csg.scaling = meshScaling;
  25546. csg.rotationQuaternion = meshRotationQuaternion;
  25547. currentCSGMeshId++;
  25548. return csg;
  25549. };
  25550. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25551. CSG.FromPolygons = function (polygons) {
  25552. var csg = new CSG();
  25553. csg.polygons = polygons;
  25554. return csg;
  25555. };
  25556. CSG.prototype.clone = function () {
  25557. var csg = new CSG();
  25558. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25559. csg.copyTransformAttributes(this);
  25560. return csg;
  25561. };
  25562. CSG.prototype.toPolygons = function () {
  25563. return this.polygons;
  25564. };
  25565. CSG.prototype.union = function (csg) {
  25566. var a = new Node(this.clone().polygons);
  25567. var b = new Node(csg.clone().polygons);
  25568. a.clipTo(b);
  25569. b.clipTo(a);
  25570. b.invert();
  25571. b.clipTo(a);
  25572. b.invert();
  25573. a.build(b.allPolygons());
  25574. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25575. };
  25576. CSG.prototype.unionInPlace = function (csg) {
  25577. var a = new Node(this.polygons);
  25578. var b = new Node(csg.polygons);
  25579. a.clipTo(b);
  25580. b.clipTo(a);
  25581. b.invert();
  25582. b.clipTo(a);
  25583. b.invert();
  25584. a.build(b.allPolygons());
  25585. this.polygons = a.allPolygons();
  25586. };
  25587. CSG.prototype.subtract = function (csg) {
  25588. var a = new Node(this.clone().polygons);
  25589. var b = new Node(csg.clone().polygons);
  25590. a.invert();
  25591. a.clipTo(b);
  25592. b.clipTo(a);
  25593. b.invert();
  25594. b.clipTo(a);
  25595. b.invert();
  25596. a.build(b.allPolygons());
  25597. a.invert();
  25598. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25599. };
  25600. CSG.prototype.subtractInPlace = function (csg) {
  25601. var a = new Node(this.polygons);
  25602. var b = new Node(csg.polygons);
  25603. a.invert();
  25604. a.clipTo(b);
  25605. b.clipTo(a);
  25606. b.invert();
  25607. b.clipTo(a);
  25608. b.invert();
  25609. a.build(b.allPolygons());
  25610. a.invert();
  25611. this.polygons = a.allPolygons();
  25612. };
  25613. CSG.prototype.intersect = function (csg) {
  25614. var a = new Node(this.clone().polygons);
  25615. var b = new Node(csg.clone().polygons);
  25616. a.invert();
  25617. b.clipTo(a);
  25618. b.invert();
  25619. a.clipTo(b);
  25620. b.clipTo(a);
  25621. a.build(b.allPolygons());
  25622. a.invert();
  25623. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25624. };
  25625. CSG.prototype.intersectInPlace = function (csg) {
  25626. var a = new Node(this.polygons);
  25627. var b = new Node(csg.polygons);
  25628. a.invert();
  25629. b.clipTo(a);
  25630. b.invert();
  25631. a.clipTo(b);
  25632. b.clipTo(a);
  25633. a.build(b.allPolygons());
  25634. a.invert();
  25635. this.polygons = a.allPolygons();
  25636. };
  25637. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25638. // not modified.
  25639. CSG.prototype.inverse = function () {
  25640. var csg = this.clone();
  25641. csg.inverseInPlace();
  25642. return csg;
  25643. };
  25644. CSG.prototype.inverseInPlace = function () {
  25645. this.polygons.map(function (p) { p.flip(); });
  25646. };
  25647. // This is used to keep meshes transformations so they can be restored
  25648. // when we build back a Babylon Mesh
  25649. // NB : All CSG operations are performed in world coordinates
  25650. CSG.prototype.copyTransformAttributes = function (csg) {
  25651. this.matrix = csg.matrix;
  25652. this.position = csg.position;
  25653. this.rotation = csg.rotation;
  25654. this.scaling = csg.scaling;
  25655. this.rotationQuaternion = csg.rotationQuaternion;
  25656. return this;
  25657. };
  25658. // Build Raw mesh from CSG
  25659. // Coordinates here are in world space
  25660. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25661. var matrix = this.matrix.clone();
  25662. matrix.invert();
  25663. 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;
  25664. if (keepSubMeshes) {
  25665. // Sort Polygons, since subMeshes are indices range
  25666. polygons.sort(function (a, b) {
  25667. if (a.shared.meshId === b.shared.meshId) {
  25668. return a.shared.subMeshId - b.shared.subMeshId;
  25669. }
  25670. else {
  25671. return a.shared.meshId - b.shared.meshId;
  25672. }
  25673. });
  25674. }
  25675. for (var i = 0, il = polygons.length; i < il; i++) {
  25676. polygon = polygons[i];
  25677. // Building SubMeshes
  25678. if (!subMesh_dict[polygon.shared.meshId]) {
  25679. subMesh_dict[polygon.shared.meshId] = {};
  25680. }
  25681. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25682. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25683. indexStart: +Infinity,
  25684. indexEnd: -Infinity,
  25685. materialIndex: polygon.shared.materialIndex
  25686. };
  25687. }
  25688. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25689. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25690. polygonIndices[0] = 0;
  25691. polygonIndices[1] = j - 1;
  25692. polygonIndices[2] = j;
  25693. for (var k = 0; k < 3; k++) {
  25694. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25695. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25696. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25697. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25698. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25699. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25700. // Check if 2 points can be merged
  25701. if (!(typeof vertex_idx !== 'undefined' &&
  25702. normals[vertex_idx * 3] === localNormal.x &&
  25703. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25704. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25705. uvs[vertex_idx * 2] === uv.x &&
  25706. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25707. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25708. uvs.push(uv.x, uv.y);
  25709. normals.push(normal.x, normal.y, normal.z);
  25710. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25711. }
  25712. indices.push(vertex_idx);
  25713. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25714. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25715. currentIndex++;
  25716. }
  25717. }
  25718. }
  25719. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25720. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25721. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25722. mesh.setIndices(indices);
  25723. if (keepSubMeshes) {
  25724. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25725. var materialIndexOffset = 0, materialMaxIndex;
  25726. mesh.subMeshes.length = 0;
  25727. for (var m in subMesh_dict) {
  25728. materialMaxIndex = -1;
  25729. for (var sm in subMesh_dict[m]) {
  25730. subMesh_obj = subMesh_dict[m][sm];
  25731. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25732. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25733. }
  25734. materialIndexOffset += ++materialMaxIndex;
  25735. }
  25736. }
  25737. return mesh;
  25738. };
  25739. // Build Mesh from CSG taking material and transforms into account
  25740. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25741. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25742. mesh.material = material;
  25743. mesh.position.copyFrom(this.position);
  25744. mesh.rotation.copyFrom(this.rotation);
  25745. if (this.rotationQuaternion) {
  25746. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25747. }
  25748. mesh.scaling.copyFrom(this.scaling);
  25749. mesh.computeWorldMatrix(true);
  25750. return mesh;
  25751. };
  25752. return CSG;
  25753. })();
  25754. BABYLON.CSG = CSG;
  25755. })(BABYLON || (BABYLON = {}));
  25756. var BABYLON;
  25757. (function (BABYLON) {
  25758. var VRDistortionCorrectionPostProcess = (function (_super) {
  25759. __extends(VRDistortionCorrectionPostProcess, _super);
  25760. //ANY
  25761. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25762. var _this = this;
  25763. _super.call(this, name, "vrDistortionCorrection", [
  25764. 'LensCenter',
  25765. 'Scale',
  25766. 'ScaleIn',
  25767. 'HmdWarpParam'
  25768. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25769. this._isRightEye = isRightEye;
  25770. this._distortionFactors = vrMetrics.distortionK;
  25771. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25772. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25773. this.onSizeChanged = function () {
  25774. _this.aspectRatio = _this.width * .5 / _this.height;
  25775. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25776. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25777. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25778. };
  25779. this.onApply = function (effect) {
  25780. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25781. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25782. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25783. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25784. };
  25785. }
  25786. return VRDistortionCorrectionPostProcess;
  25787. })(BABYLON.PostProcess);
  25788. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25789. })(BABYLON || (BABYLON = {}));
  25790. // Mainly based on these 2 articles :
  25791. // 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
  25792. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25793. var BABYLON;
  25794. (function (BABYLON) {
  25795. (function (JoystickAxis) {
  25796. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25797. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25798. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25799. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25800. var JoystickAxis = BABYLON.JoystickAxis;
  25801. var VirtualJoystick = (function () {
  25802. function VirtualJoystick(leftJoystick) {
  25803. var _this = this;
  25804. if (leftJoystick) {
  25805. this._leftJoystick = true;
  25806. }
  25807. else {
  25808. this._leftJoystick = false;
  25809. }
  25810. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25811. VirtualJoystick._globalJoystickIndex++;
  25812. // By default left & right arrow keys are moving the X
  25813. // and up & down keys are moving the Y
  25814. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25815. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25816. this.reverseLeftRight = false;
  25817. this.reverseUpDown = false;
  25818. // collections of pointers
  25819. this._touches = new BABYLON.SmartCollection();
  25820. this.deltaPosition = BABYLON.Vector3.Zero();
  25821. this._joystickSensibility = 25;
  25822. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25823. this._rotationSpeed = 25;
  25824. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25825. this._rotateOnAxisRelativeToMesh = false;
  25826. this._onResize = function (evt) {
  25827. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25828. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25829. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25830. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25831. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25832. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25833. };
  25834. // injecting a canvas element on top of the canvas 3D game
  25835. if (!VirtualJoystick.vjCanvas) {
  25836. window.addEventListener("resize", this._onResize, false);
  25837. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25838. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25839. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25840. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25841. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25842. VirtualJoystick.vjCanvas.style.width = "100%";
  25843. VirtualJoystick.vjCanvas.style.height = "100%";
  25844. VirtualJoystick.vjCanvas.style.position = "absolute";
  25845. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25846. VirtualJoystick.vjCanvas.style.top = "0px";
  25847. VirtualJoystick.vjCanvas.style.left = "0px";
  25848. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25849. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25850. // Support for jQuery PEP polyfill
  25851. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  25852. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25853. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25854. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25855. document.body.appendChild(VirtualJoystick.vjCanvas);
  25856. }
  25857. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25858. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25859. this.pressed = false;
  25860. // default joystick color
  25861. this._joystickColor = "cyan";
  25862. this._joystickPointerID = -1;
  25863. // current joystick position
  25864. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25865. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25866. // origin joystick position
  25867. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25868. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25869. this._onPointerDownHandlerRef = function (evt) {
  25870. _this._onPointerDown(evt);
  25871. };
  25872. this._onPointerMoveHandlerRef = function (evt) {
  25873. _this._onPointerMove(evt);
  25874. };
  25875. this._onPointerOutHandlerRef = function (evt) {
  25876. _this._onPointerUp(evt);
  25877. };
  25878. this._onPointerUpHandlerRef = function (evt) {
  25879. _this._onPointerUp(evt);
  25880. };
  25881. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25882. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25883. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25884. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25885. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25886. evt.preventDefault(); // Disables system menu
  25887. }, false);
  25888. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25889. }
  25890. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25891. this._joystickSensibility = newJoystickSensibility;
  25892. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25893. };
  25894. VirtualJoystick.prototype._onPointerDown = function (e) {
  25895. var positionOnScreenCondition;
  25896. e.preventDefault();
  25897. if (this._leftJoystick === true) {
  25898. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25899. }
  25900. else {
  25901. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25902. }
  25903. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25904. // First contact will be dedicated to the virtual joystick
  25905. this._joystickPointerID = e.pointerId;
  25906. this._joystickPointerStartPos.x = e.clientX;
  25907. this._joystickPointerStartPos.y = e.clientY;
  25908. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25909. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25910. this._deltaJoystickVector.x = 0;
  25911. this._deltaJoystickVector.y = 0;
  25912. this.pressed = true;
  25913. this._touches.add(e.pointerId.toString(), e);
  25914. }
  25915. else {
  25916. // You can only trigger the action buttons with a joystick declared
  25917. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25918. this._action();
  25919. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25920. }
  25921. }
  25922. };
  25923. VirtualJoystick.prototype._onPointerMove = function (e) {
  25924. // If the current pointer is the one associated to the joystick (first touch contact)
  25925. if (this._joystickPointerID == e.pointerId) {
  25926. this._joystickPointerPos.x = e.clientX;
  25927. this._joystickPointerPos.y = e.clientY;
  25928. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25929. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25930. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25931. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25932. switch (this._axisTargetedByLeftAndRight) {
  25933. case JoystickAxis.X:
  25934. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25935. break;
  25936. case JoystickAxis.Y:
  25937. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25938. break;
  25939. case JoystickAxis.Z:
  25940. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25941. break;
  25942. }
  25943. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25944. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25945. switch (this._axisTargetedByUpAndDown) {
  25946. case JoystickAxis.X:
  25947. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25948. break;
  25949. case JoystickAxis.Y:
  25950. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25951. break;
  25952. case JoystickAxis.Z:
  25953. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25954. break;
  25955. }
  25956. }
  25957. else {
  25958. if (this._touches.item(e.pointerId.toString())) {
  25959. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25960. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25961. }
  25962. }
  25963. };
  25964. VirtualJoystick.prototype._onPointerUp = function (e) {
  25965. if (this._joystickPointerID == e.pointerId) {
  25966. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25967. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25968. this._joystickPointerID = -1;
  25969. this.pressed = false;
  25970. }
  25971. else {
  25972. var touch = this._touches.item(e.pointerId.toString());
  25973. if (touch) {
  25974. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25975. }
  25976. }
  25977. this._deltaJoystickVector.x = 0;
  25978. this._deltaJoystickVector.y = 0;
  25979. this._touches.remove(e.pointerId.toString());
  25980. };
  25981. /**
  25982. * Change the color of the virtual joystick
  25983. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25984. */
  25985. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25986. this._joystickColor = newColor;
  25987. };
  25988. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25989. this._action = action;
  25990. };
  25991. // Define which axis you'd like to control for left & right
  25992. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25993. switch (axis) {
  25994. case JoystickAxis.X:
  25995. case JoystickAxis.Y:
  25996. case JoystickAxis.Z:
  25997. this._axisTargetedByLeftAndRight = axis;
  25998. break;
  25999. default:
  26000. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  26001. break;
  26002. }
  26003. };
  26004. // Define which axis you'd like to control for up & down
  26005. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  26006. switch (axis) {
  26007. case JoystickAxis.X:
  26008. case JoystickAxis.Y:
  26009. case JoystickAxis.Z:
  26010. this._axisTargetedByUpAndDown = axis;
  26011. break;
  26012. default:
  26013. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  26014. break;
  26015. }
  26016. };
  26017. VirtualJoystick.prototype._clearCanvas = function () {
  26018. if (this._leftJoystick) {
  26019. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  26020. }
  26021. else {
  26022. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  26023. }
  26024. };
  26025. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  26026. var _this = this;
  26027. if (this.pressed) {
  26028. this._touches.forEach(function (touch) {
  26029. if (touch.pointerId === _this._joystickPointerID) {
  26030. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  26031. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  26032. VirtualJoystick.vjCanvasContext.beginPath();
  26033. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  26034. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26035. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  26036. VirtualJoystick.vjCanvasContext.stroke();
  26037. VirtualJoystick.vjCanvasContext.closePath();
  26038. VirtualJoystick.vjCanvasContext.beginPath();
  26039. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26040. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  26041. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  26042. VirtualJoystick.vjCanvasContext.stroke();
  26043. VirtualJoystick.vjCanvasContext.closePath();
  26044. VirtualJoystick.vjCanvasContext.beginPath();
  26045. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26046. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  26047. VirtualJoystick.vjCanvasContext.stroke();
  26048. VirtualJoystick.vjCanvasContext.closePath();
  26049. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  26050. }
  26051. else {
  26052. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  26053. VirtualJoystick.vjCanvasContext.beginPath();
  26054. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  26055. VirtualJoystick.vjCanvasContext.beginPath();
  26056. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  26057. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  26058. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  26059. VirtualJoystick.vjCanvasContext.stroke();
  26060. VirtualJoystick.vjCanvasContext.closePath();
  26061. touch.prevX = touch.x;
  26062. touch.prevY = touch.y;
  26063. }
  26064. ;
  26065. });
  26066. }
  26067. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  26068. };
  26069. VirtualJoystick.prototype.releaseCanvas = function () {
  26070. if (VirtualJoystick.vjCanvas) {
  26071. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  26072. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  26073. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  26074. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  26075. window.removeEventListener("resize", this._onResize);
  26076. document.body.removeChild(VirtualJoystick.vjCanvas);
  26077. VirtualJoystick.vjCanvas = null;
  26078. }
  26079. };
  26080. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  26081. VirtualJoystick._globalJoystickIndex = 0;
  26082. return VirtualJoystick;
  26083. })();
  26084. BABYLON.VirtualJoystick = VirtualJoystick;
  26085. })(BABYLON || (BABYLON = {}));
  26086. var BABYLON;
  26087. (function (BABYLON) {
  26088. // We're mainly based on the logic defined into the FreeCamera code
  26089. var VirtualJoysticksCamera = (function (_super) {
  26090. __extends(VirtualJoysticksCamera, _super);
  26091. function VirtualJoysticksCamera(name, position, scene) {
  26092. _super.call(this, name, position, scene);
  26093. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  26094. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  26095. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  26096. this._leftjoystick.setJoystickSensibility(0.15);
  26097. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  26098. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  26099. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  26100. this._rightjoystick.reverseUpDown = true;
  26101. this._rightjoystick.setJoystickSensibility(0.05);
  26102. this._rightjoystick.setJoystickColor("yellow");
  26103. }
  26104. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  26105. return this._leftjoystick;
  26106. };
  26107. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  26108. return this._rightjoystick;
  26109. };
  26110. VirtualJoysticksCamera.prototype._checkInputs = function () {
  26111. var speed = this._computeLocalCameraSpeed() * 50;
  26112. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26113. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  26114. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26115. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  26116. if (!this._leftjoystick.pressed) {
  26117. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  26118. }
  26119. if (!this._rightjoystick.pressed) {
  26120. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  26121. }
  26122. _super.prototype._checkInputs.call(this);
  26123. };
  26124. VirtualJoysticksCamera.prototype.dispose = function () {
  26125. this._leftjoystick.releaseCanvas();
  26126. _super.prototype.dispose.call(this);
  26127. };
  26128. return VirtualJoysticksCamera;
  26129. })(BABYLON.FreeCamera);
  26130. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  26131. })(BABYLON || (BABYLON = {}));
  26132. var BABYLON;
  26133. (function (BABYLON) {
  26134. var ShaderMaterial = (function (_super) {
  26135. __extends(ShaderMaterial, _super);
  26136. function ShaderMaterial(name, scene, shaderPath, options) {
  26137. _super.call(this, name, scene);
  26138. this._textures = new Array();
  26139. this._floats = new Array();
  26140. this._floatsArrays = {};
  26141. this._colors3 = new Array();
  26142. this._colors4 = new Array();
  26143. this._vectors2 = new Array();
  26144. this._vectors3 = new Array();
  26145. this._vectors4 = new Array();
  26146. this._matrices = new Array();
  26147. this._matrices3x3 = new Array();
  26148. this._matrices2x2 = new Array();
  26149. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  26150. this._shaderPath = shaderPath;
  26151. options.needAlphaBlending = options.needAlphaBlending || false;
  26152. options.needAlphaTesting = options.needAlphaTesting || false;
  26153. options.attributes = options.attributes || ["position", "normal", "uv"];
  26154. options.uniforms = options.uniforms || ["worldViewProjection"];
  26155. options.samplers = options.samplers || [];
  26156. options.defines = options.defines || [];
  26157. this._options = options;
  26158. }
  26159. ShaderMaterial.prototype.needAlphaBlending = function () {
  26160. return this._options.needAlphaBlending;
  26161. };
  26162. ShaderMaterial.prototype.needAlphaTesting = function () {
  26163. return this._options.needAlphaTesting;
  26164. };
  26165. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  26166. if (this._options.uniforms.indexOf(uniformName) === -1) {
  26167. this._options.uniforms.push(uniformName);
  26168. }
  26169. };
  26170. ShaderMaterial.prototype.setTexture = function (name, texture) {
  26171. if (this._options.samplers.indexOf(name) === -1) {
  26172. this._options.samplers.push(name);
  26173. }
  26174. this._textures[name] = texture;
  26175. return this;
  26176. };
  26177. ShaderMaterial.prototype.setFloat = function (name, value) {
  26178. this._checkUniform(name);
  26179. this._floats[name] = value;
  26180. return this;
  26181. };
  26182. ShaderMaterial.prototype.setFloats = function (name, value) {
  26183. this._checkUniform(name);
  26184. this._floatsArrays[name] = value;
  26185. return this;
  26186. };
  26187. ShaderMaterial.prototype.setColor3 = function (name, value) {
  26188. this._checkUniform(name);
  26189. this._colors3[name] = value;
  26190. return this;
  26191. };
  26192. ShaderMaterial.prototype.setColor4 = function (name, value) {
  26193. this._checkUniform(name);
  26194. this._colors4[name] = value;
  26195. return this;
  26196. };
  26197. ShaderMaterial.prototype.setVector2 = function (name, value) {
  26198. this._checkUniform(name);
  26199. this._vectors2[name] = value;
  26200. return this;
  26201. };
  26202. ShaderMaterial.prototype.setVector3 = function (name, value) {
  26203. this._checkUniform(name);
  26204. this._vectors3[name] = value;
  26205. return this;
  26206. };
  26207. ShaderMaterial.prototype.setVector4 = function (name, value) {
  26208. this._checkUniform(name);
  26209. this._vectors4[name] = value;
  26210. return this;
  26211. };
  26212. ShaderMaterial.prototype.setMatrix = function (name, value) {
  26213. this._checkUniform(name);
  26214. this._matrices[name] = value;
  26215. return this;
  26216. };
  26217. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  26218. this._checkUniform(name);
  26219. this._matrices3x3[name] = value;
  26220. return this;
  26221. };
  26222. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  26223. this._checkUniform(name);
  26224. this._matrices2x2[name] = value;
  26225. return this;
  26226. };
  26227. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  26228. var scene = this.getScene();
  26229. var engine = scene.getEngine();
  26230. if (!this.checkReadyOnEveryCall) {
  26231. if (this._renderId === scene.getRenderId()) {
  26232. return true;
  26233. }
  26234. }
  26235. // Instances
  26236. var defines = [];
  26237. var fallbacks = new BABYLON.EffectFallbacks();
  26238. if (useInstances) {
  26239. defines.push("#define INSTANCES");
  26240. }
  26241. for (var index = 0; index < this._options.defines.length; index++) {
  26242. defines.push(this._options.defines[index]);
  26243. }
  26244. // Bones
  26245. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26246. defines.push("#define BONES");
  26247. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26248. defines.push("#define BONES4");
  26249. fallbacks.addFallback(0, "BONES4");
  26250. }
  26251. // Alpha test
  26252. if (engine.getAlphaTesting()) {
  26253. defines.push("#define ALPHATEST");
  26254. }
  26255. var previousEffect = this._effect;
  26256. var join = defines.join("\n");
  26257. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  26258. if (!this._effect.isReady()) {
  26259. return false;
  26260. }
  26261. if (previousEffect !== this._effect) {
  26262. scene.resetCachedMaterial();
  26263. }
  26264. this._renderId = scene.getRenderId();
  26265. return true;
  26266. };
  26267. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26268. var scene = this.getScene();
  26269. if (this._options.uniforms.indexOf("world") !== -1) {
  26270. this._effect.setMatrix("world", world);
  26271. }
  26272. if (this._options.uniforms.indexOf("worldView") !== -1) {
  26273. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  26274. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  26275. }
  26276. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  26277. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  26278. }
  26279. };
  26280. ShaderMaterial.prototype.bind = function (world, mesh) {
  26281. // Std values
  26282. this.bindOnlyWorldMatrix(world);
  26283. if (this.getScene().getCachedMaterial() !== this) {
  26284. if (this._options.uniforms.indexOf("view") !== -1) {
  26285. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  26286. }
  26287. if (this._options.uniforms.indexOf("projection") !== -1) {
  26288. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  26289. }
  26290. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  26291. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26292. }
  26293. // Bones
  26294. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26295. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26296. }
  26297. // Texture
  26298. for (var name in this._textures) {
  26299. this._effect.setTexture(name, this._textures[name]);
  26300. }
  26301. // Float
  26302. for (name in this._floats) {
  26303. this._effect.setFloat(name, this._floats[name]);
  26304. }
  26305. // Float s
  26306. for (name in this._floatsArrays) {
  26307. this._effect.setArray(name, this._floatsArrays[name]);
  26308. }
  26309. // Color3
  26310. for (name in this._colors3) {
  26311. this._effect.setColor3(name, this._colors3[name]);
  26312. }
  26313. // Color4
  26314. for (name in this._colors4) {
  26315. var color = this._colors4[name];
  26316. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  26317. }
  26318. // Vector2
  26319. for (name in this._vectors2) {
  26320. this._effect.setVector2(name, this._vectors2[name]);
  26321. }
  26322. // Vector3
  26323. for (name in this._vectors3) {
  26324. this._effect.setVector3(name, this._vectors3[name]);
  26325. }
  26326. // Vector4
  26327. for (name in this._vectors4) {
  26328. this._effect.setVector4(name, this._vectors4[name]);
  26329. }
  26330. // Matrix
  26331. for (name in this._matrices) {
  26332. this._effect.setMatrix(name, this._matrices[name]);
  26333. }
  26334. // Matrix 3x3
  26335. for (name in this._matrices3x3) {
  26336. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  26337. }
  26338. // Matrix 2x2
  26339. for (name in this._matrices2x2) {
  26340. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  26341. }
  26342. }
  26343. _super.prototype.bind.call(this, world, mesh);
  26344. };
  26345. ShaderMaterial.prototype.clone = function (name) {
  26346. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  26347. return newShaderMaterial;
  26348. };
  26349. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  26350. for (var name in this._textures) {
  26351. this._textures[name].dispose();
  26352. }
  26353. this._textures = [];
  26354. _super.prototype.dispose.call(this, forceDisposeEffect);
  26355. };
  26356. return ShaderMaterial;
  26357. })(BABYLON.Material);
  26358. BABYLON.ShaderMaterial = ShaderMaterial;
  26359. })(BABYLON || (BABYLON = {}));
  26360. var BABYLON;
  26361. (function (BABYLON) {
  26362. var VertexData = (function () {
  26363. function VertexData() {
  26364. }
  26365. VertexData.prototype.set = function (data, kind) {
  26366. switch (kind) {
  26367. case BABYLON.VertexBuffer.PositionKind:
  26368. this.positions = data;
  26369. break;
  26370. case BABYLON.VertexBuffer.NormalKind:
  26371. this.normals = data;
  26372. break;
  26373. case BABYLON.VertexBuffer.UVKind:
  26374. this.uvs = data;
  26375. break;
  26376. case BABYLON.VertexBuffer.UV2Kind:
  26377. this.uvs2 = data;
  26378. break;
  26379. case BABYLON.VertexBuffer.UV3Kind:
  26380. this.uvs3 = data;
  26381. break;
  26382. case BABYLON.VertexBuffer.UV4Kind:
  26383. this.uvs4 = data;
  26384. break;
  26385. case BABYLON.VertexBuffer.UV5Kind:
  26386. this.uvs5 = data;
  26387. break;
  26388. case BABYLON.VertexBuffer.UV6Kind:
  26389. this.uvs6 = data;
  26390. break;
  26391. case BABYLON.VertexBuffer.ColorKind:
  26392. this.colors = data;
  26393. break;
  26394. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26395. this.matricesIndices = data;
  26396. break;
  26397. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26398. this.matricesWeights = data;
  26399. break;
  26400. }
  26401. };
  26402. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26403. this._applyTo(mesh, updatable);
  26404. };
  26405. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26406. this._applyTo(geometry, updatable);
  26407. };
  26408. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26409. this._update(mesh);
  26410. };
  26411. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26412. this._update(geometry);
  26413. };
  26414. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26415. if (this.positions) {
  26416. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26417. }
  26418. if (this.normals) {
  26419. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26420. }
  26421. if (this.uvs) {
  26422. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26423. }
  26424. if (this.uvs2) {
  26425. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26426. }
  26427. if (this.uvs3) {
  26428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26429. }
  26430. if (this.uvs4) {
  26431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26432. }
  26433. if (this.uvs5) {
  26434. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26435. }
  26436. if (this.uvs6) {
  26437. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26438. }
  26439. if (this.colors) {
  26440. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26441. }
  26442. if (this.matricesIndices) {
  26443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26444. }
  26445. if (this.matricesWeights) {
  26446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26447. }
  26448. if (this.indices) {
  26449. meshOrGeometry.setIndices(this.indices);
  26450. }
  26451. };
  26452. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26453. if (this.positions) {
  26454. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26455. }
  26456. if (this.normals) {
  26457. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26458. }
  26459. if (this.uvs) {
  26460. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26461. }
  26462. if (this.uvs2) {
  26463. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26464. }
  26465. if (this.uvs3) {
  26466. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26467. }
  26468. if (this.uvs4) {
  26469. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26470. }
  26471. if (this.uvs5) {
  26472. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26473. }
  26474. if (this.uvs6) {
  26475. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26476. }
  26477. if (this.colors) {
  26478. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26479. }
  26480. if (this.matricesIndices) {
  26481. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26482. }
  26483. if (this.matricesWeights) {
  26484. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26485. }
  26486. if (this.indices) {
  26487. meshOrGeometry.setIndices(this.indices);
  26488. }
  26489. };
  26490. VertexData.prototype.transform = function (matrix) {
  26491. var transformed = BABYLON.Vector3.Zero();
  26492. var index;
  26493. if (this.positions) {
  26494. var position = BABYLON.Vector3.Zero();
  26495. for (index = 0; index < this.positions.length; index += 3) {
  26496. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26497. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26498. this.positions[index] = transformed.x;
  26499. this.positions[index + 1] = transformed.y;
  26500. this.positions[index + 2] = transformed.z;
  26501. }
  26502. }
  26503. if (this.normals) {
  26504. var normal = BABYLON.Vector3.Zero();
  26505. for (index = 0; index < this.normals.length; index += 3) {
  26506. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26507. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26508. this.normals[index] = transformed.x;
  26509. this.normals[index + 1] = transformed.y;
  26510. this.normals[index + 2] = transformed.z;
  26511. }
  26512. }
  26513. };
  26514. VertexData.prototype.merge = function (other) {
  26515. var index;
  26516. if (other.indices) {
  26517. if (!this.indices) {
  26518. this.indices = [];
  26519. }
  26520. var offset = this.positions ? this.positions.length / 3 : 0;
  26521. for (index = 0; index < other.indices.length; index++) {
  26522. this.indices.push(other.indices[index] + offset);
  26523. }
  26524. }
  26525. if (other.positions) {
  26526. if (!this.positions) {
  26527. this.positions = [];
  26528. }
  26529. for (index = 0; index < other.positions.length; index++) {
  26530. this.positions.push(other.positions[index]);
  26531. }
  26532. }
  26533. if (other.normals) {
  26534. if (!this.normals) {
  26535. this.normals = [];
  26536. }
  26537. for (index = 0; index < other.normals.length; index++) {
  26538. this.normals.push(other.normals[index]);
  26539. }
  26540. }
  26541. if (other.uvs) {
  26542. if (!this.uvs) {
  26543. this.uvs = [];
  26544. }
  26545. for (index = 0; index < other.uvs.length; index++) {
  26546. this.uvs.push(other.uvs[index]);
  26547. }
  26548. }
  26549. if (other.uvs2) {
  26550. if (!this.uvs2) {
  26551. this.uvs2 = [];
  26552. }
  26553. for (index = 0; index < other.uvs2.length; index++) {
  26554. this.uvs2.push(other.uvs2[index]);
  26555. }
  26556. }
  26557. if (other.uvs3) {
  26558. if (!this.uvs3) {
  26559. this.uvs3 = [];
  26560. }
  26561. for (index = 0; index < other.uvs3.length; index++) {
  26562. this.uvs3.push(other.uvs3[index]);
  26563. }
  26564. }
  26565. if (other.uvs4) {
  26566. if (!this.uvs4) {
  26567. this.uvs4 = [];
  26568. }
  26569. for (index = 0; index < other.uvs4.length; index++) {
  26570. this.uvs4.push(other.uvs4[index]);
  26571. }
  26572. }
  26573. if (other.uvs5) {
  26574. if (!this.uvs5) {
  26575. this.uvs5 = [];
  26576. }
  26577. for (index = 0; index < other.uvs5.length; index++) {
  26578. this.uvs5.push(other.uvs5[index]);
  26579. }
  26580. }
  26581. if (other.uvs6) {
  26582. if (!this.uvs6) {
  26583. this.uvs6 = [];
  26584. }
  26585. for (index = 0; index < other.uvs6.length; index++) {
  26586. this.uvs6.push(other.uvs6[index]);
  26587. }
  26588. }
  26589. if (other.matricesIndices) {
  26590. if (!this.matricesIndices) {
  26591. this.matricesIndices = [];
  26592. }
  26593. for (index = 0; index < other.matricesIndices.length; index++) {
  26594. this.matricesIndices.push(other.matricesIndices[index]);
  26595. }
  26596. }
  26597. if (other.matricesWeights) {
  26598. if (!this.matricesWeights) {
  26599. this.matricesWeights = [];
  26600. }
  26601. for (index = 0; index < other.matricesWeights.length; index++) {
  26602. this.matricesWeights.push(other.matricesWeights[index]);
  26603. }
  26604. }
  26605. if (other.colors) {
  26606. if (!this.colors) {
  26607. this.colors = [];
  26608. }
  26609. for (index = 0; index < other.colors.length; index++) {
  26610. this.colors.push(other.colors[index]);
  26611. }
  26612. }
  26613. };
  26614. // Statics
  26615. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26616. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26617. };
  26618. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26619. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26620. };
  26621. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26622. var result = new VertexData();
  26623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26624. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26625. }
  26626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26627. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26628. }
  26629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26630. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26631. }
  26632. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26633. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26634. }
  26635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26636. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26637. }
  26638. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26639. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26640. }
  26641. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26642. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26643. }
  26644. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26645. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26646. }
  26647. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26648. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26649. }
  26650. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26651. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26652. }
  26653. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26654. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26655. }
  26656. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26657. return result;
  26658. };
  26659. VertexData.CreateRibbon = function (options) {
  26660. var pathArray = options.pathArray;
  26661. var closeArray = options.closeArray || false;
  26662. var closePath = options.closePath || false;
  26663. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26664. var offset = options.offset || defaultOffset;
  26665. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26666. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26667. var positions = [];
  26668. var indices = [];
  26669. var normals = [];
  26670. var uvs = [];
  26671. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26672. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26673. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26674. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26675. var minlg; // minimal length among all paths from pathArray
  26676. var lg = []; // array of path lengths : nb of vertex per path
  26677. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26678. var p; // path iterator
  26679. var i; // point iterator
  26680. var j; // point iterator
  26681. // if single path in pathArray
  26682. if (pathArray.length < 2) {
  26683. var ar1 = [];
  26684. var ar2 = [];
  26685. for (i = 0; i < pathArray[0].length - offset; i++) {
  26686. ar1.push(pathArray[0][i]);
  26687. ar2.push(pathArray[0][i + offset]);
  26688. }
  26689. pathArray = [ar1, ar2];
  26690. }
  26691. // positions and horizontal distances (u)
  26692. var idc = 0;
  26693. var closePathCorr = (closePath) ? 1 : 0;
  26694. var path;
  26695. var l;
  26696. minlg = pathArray[0].length;
  26697. var vectlg;
  26698. var dist;
  26699. for (p = 0; p < pathArray.length; p++) {
  26700. uTotalDistance[p] = 0;
  26701. us[p] = [0];
  26702. path = pathArray[p];
  26703. l = path.length;
  26704. minlg = (minlg < l) ? minlg : l;
  26705. j = 0;
  26706. while (j < l) {
  26707. positions.push(path[j].x, path[j].y, path[j].z);
  26708. if (j > 0) {
  26709. vectlg = path[j].subtract(path[j - 1]).length();
  26710. dist = vectlg + uTotalDistance[p];
  26711. us[p].push(dist);
  26712. uTotalDistance[p] = dist;
  26713. }
  26714. j++;
  26715. }
  26716. if (closePath) {
  26717. j--;
  26718. positions.push(path[0].x, path[0].y, path[0].z);
  26719. vectlg = path[j].subtract(path[0]).length();
  26720. dist = vectlg + uTotalDistance[p];
  26721. us[p].push(dist);
  26722. uTotalDistance[p] = dist;
  26723. }
  26724. lg[p] = l + closePathCorr;
  26725. idx[p] = idc;
  26726. idc += (l + closePathCorr);
  26727. }
  26728. // vertical distances (v)
  26729. var path1;
  26730. var path2;
  26731. var vertex1;
  26732. var vertex2;
  26733. for (i = 0; i < minlg + closePathCorr; i++) {
  26734. vTotalDistance[i] = 0;
  26735. vs[i] = [0];
  26736. for (p = 0; p < pathArray.length - 1; p++) {
  26737. path1 = pathArray[p];
  26738. path2 = pathArray[p + 1];
  26739. if (i === minlg) {
  26740. vertex1 = path1[0];
  26741. vertex2 = path2[0];
  26742. }
  26743. else {
  26744. vertex1 = path1[i];
  26745. vertex2 = path2[i];
  26746. }
  26747. vectlg = vertex2.subtract(vertex1).length();
  26748. dist = vectlg + vTotalDistance[i];
  26749. vs[i].push(dist);
  26750. vTotalDistance[i] = dist;
  26751. }
  26752. if (closeArray) {
  26753. path1 = pathArray[p];
  26754. path2 = pathArray[0];
  26755. if (i === minlg) {
  26756. vertex2 = path2[0];
  26757. }
  26758. vectlg = vertex2.subtract(vertex1).length();
  26759. dist = vectlg + vTotalDistance[i];
  26760. vTotalDistance[i] = dist;
  26761. }
  26762. }
  26763. // uvs
  26764. var u;
  26765. var v;
  26766. for (p = 0; p < pathArray.length; p++) {
  26767. for (i = 0; i < minlg + closePathCorr; i++) {
  26768. u = us[p][i] / uTotalDistance[p];
  26769. v = vs[i][p] / vTotalDistance[i];
  26770. uvs.push(u, v);
  26771. }
  26772. }
  26773. // indices
  26774. p = 0; // path index
  26775. var pi = 0; // positions array index
  26776. var l1 = lg[p] - 1; // path1 length
  26777. var l2 = lg[p + 1] - 1; // path2 length
  26778. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26779. var shft = idx[1] - idx[0]; // shift
  26780. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26781. while (pi <= min && p < path1nb) {
  26782. // 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
  26783. indices.push(pi, pi + shft, pi + 1);
  26784. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26785. pi += 1;
  26786. if (pi === min) {
  26787. p++;
  26788. if (p === lg.length - 1) {
  26789. shft = idx[0] - idx[p];
  26790. l1 = lg[p] - 1;
  26791. l2 = lg[0] - 1;
  26792. }
  26793. else {
  26794. shft = idx[p + 1] - idx[p];
  26795. l1 = lg[p] - 1;
  26796. l2 = lg[p + 1] - 1;
  26797. }
  26798. pi = idx[p];
  26799. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26800. }
  26801. }
  26802. // normals
  26803. VertexData.ComputeNormals(positions, indices, normals);
  26804. if (closePath) {
  26805. var indexFirst = 0;
  26806. var indexLast = 0;
  26807. for (p = 0; p < pathArray.length; p++) {
  26808. indexFirst = idx[p] * 3;
  26809. if (p + 1 < pathArray.length) {
  26810. indexLast = (idx[p + 1] - 1) * 3;
  26811. }
  26812. else {
  26813. indexLast = normals.length - 3;
  26814. }
  26815. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26816. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26817. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26818. normals[indexLast] = normals[indexFirst];
  26819. normals[indexLast + 1] = normals[indexFirst + 1];
  26820. normals[indexLast + 2] = normals[indexFirst + 2];
  26821. }
  26822. }
  26823. // sides
  26824. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26825. // Result
  26826. var vertexData = new VertexData();
  26827. vertexData.indices = indices;
  26828. vertexData.positions = positions;
  26829. vertexData.normals = normals;
  26830. vertexData.uvs = uvs;
  26831. if (closePath) {
  26832. vertexData._idx = idx;
  26833. }
  26834. return vertexData;
  26835. };
  26836. VertexData.CreateBox = function (options) {
  26837. var normalsSource = [
  26838. new BABYLON.Vector3(0, 0, 1),
  26839. new BABYLON.Vector3(0, 0, -1),
  26840. new BABYLON.Vector3(1, 0, 0),
  26841. new BABYLON.Vector3(-1, 0, 0),
  26842. new BABYLON.Vector3(0, 1, 0),
  26843. new BABYLON.Vector3(0, -1, 0)
  26844. ];
  26845. var indices = [];
  26846. var positions = [];
  26847. var normals = [];
  26848. var uvs = [];
  26849. var width = options.width || options.size || 1;
  26850. var height = options.height || options.size || 1;
  26851. var depth = options.depth || options.size || 1;
  26852. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26853. var faceUV = options.faceUV || new Array(6);
  26854. var faceColors = options.faceColors;
  26855. var colors = [];
  26856. // default face colors and UV if undefined
  26857. for (var f = 0; f < 6; f++) {
  26858. if (faceUV[f] === undefined) {
  26859. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26860. }
  26861. if (faceColors && faceColors[f] === undefined) {
  26862. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26863. }
  26864. }
  26865. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26866. // Create each face in turn.
  26867. for (var index = 0; index < normalsSource.length; index++) {
  26868. var normal = normalsSource[index];
  26869. // Get two vectors perpendicular to the face normal and to each other.
  26870. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26871. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26872. // Six indices (two triangles) per face.
  26873. var verticesLength = positions.length / 3;
  26874. indices.push(verticesLength);
  26875. indices.push(verticesLength + 1);
  26876. indices.push(verticesLength + 2);
  26877. indices.push(verticesLength);
  26878. indices.push(verticesLength + 2);
  26879. indices.push(verticesLength + 3);
  26880. // Four vertices per face.
  26881. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26882. positions.push(vertex.x, vertex.y, vertex.z);
  26883. normals.push(normal.x, normal.y, normal.z);
  26884. uvs.push(faceUV[index].z, faceUV[index].w);
  26885. if (faceColors) {
  26886. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26887. }
  26888. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26889. positions.push(vertex.x, vertex.y, vertex.z);
  26890. normals.push(normal.x, normal.y, normal.z);
  26891. uvs.push(faceUV[index].x, faceUV[index].w);
  26892. if (faceColors) {
  26893. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26894. }
  26895. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26896. positions.push(vertex.x, vertex.y, vertex.z);
  26897. normals.push(normal.x, normal.y, normal.z);
  26898. uvs.push(faceUV[index].x, faceUV[index].y);
  26899. if (faceColors) {
  26900. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26901. }
  26902. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26903. positions.push(vertex.x, vertex.y, vertex.z);
  26904. normals.push(normal.x, normal.y, normal.z);
  26905. uvs.push(faceUV[index].z, faceUV[index].y);
  26906. if (faceColors) {
  26907. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26908. }
  26909. }
  26910. // sides
  26911. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26912. // Result
  26913. var vertexData = new VertexData();
  26914. vertexData.indices = indices;
  26915. vertexData.positions = positions;
  26916. vertexData.normals = normals;
  26917. vertexData.uvs = uvs;
  26918. if (faceColors) {
  26919. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26920. vertexData.colors = totalColors;
  26921. }
  26922. return vertexData;
  26923. };
  26924. VertexData.CreateSphere = function (options) {
  26925. var segments = options.segments || 32;
  26926. var diameterX = options.diameterX || options.diameter || 1;
  26927. var diameterY = options.diameterY || options.diameter || 1;
  26928. var diameterZ = options.diameterZ || options.diameter || 1;
  26929. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26930. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26931. var totalZRotationSteps = 2 + segments;
  26932. var totalYRotationSteps = 2 * totalZRotationSteps;
  26933. var indices = [];
  26934. var positions = [];
  26935. var normals = [];
  26936. var uvs = [];
  26937. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26938. var normalizedZ = zRotationStep / totalZRotationSteps;
  26939. var angleZ = (normalizedZ * Math.PI);
  26940. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26941. var normalizedY = yRotationStep / totalYRotationSteps;
  26942. var angleY = normalizedY * Math.PI * 2;
  26943. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26944. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26945. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26946. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26947. var vertex = complete.multiply(radius);
  26948. var normal = BABYLON.Vector3.Normalize(vertex);
  26949. positions.push(vertex.x, vertex.y, vertex.z);
  26950. normals.push(normal.x, normal.y, normal.z);
  26951. uvs.push(normalizedY, normalizedZ);
  26952. }
  26953. if (zRotationStep > 0) {
  26954. var verticesCount = positions.length / 3;
  26955. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26956. indices.push((firstIndex));
  26957. indices.push((firstIndex + 1));
  26958. indices.push(firstIndex + totalYRotationSteps + 1);
  26959. indices.push((firstIndex + totalYRotationSteps + 1));
  26960. indices.push((firstIndex + 1));
  26961. indices.push((firstIndex + totalYRotationSteps + 2));
  26962. }
  26963. }
  26964. }
  26965. // Sides
  26966. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26967. // Result
  26968. var vertexData = new VertexData();
  26969. vertexData.indices = indices;
  26970. vertexData.positions = positions;
  26971. vertexData.normals = normals;
  26972. vertexData.uvs = uvs;
  26973. return vertexData;
  26974. };
  26975. // Cylinder and cone
  26976. VertexData.CreateCylinder = function (options) {
  26977. var height = options.height || 2;
  26978. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || 1;
  26979. var diameterBottom = options.diameterBottom || 1;
  26980. var tessellation = options.tessellation || 24;
  26981. var subdivisions = options.subdivisions || 1;
  26982. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26983. var faceUV = options.faceUV || new Array(3);
  26984. var faceColors = options.faceColors;
  26985. // default face colors and UV if undefined
  26986. for (var f = 0; f < 3; f++) {
  26987. if (faceColors && faceColors[f] === undefined) {
  26988. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26989. }
  26990. if (faceUV && faceUV[f] === undefined) {
  26991. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26992. }
  26993. }
  26994. var indices = [];
  26995. var positions = [];
  26996. var normals = [];
  26997. var uvs = [];
  26998. var colors = [];
  26999. var angle_step = Math.PI * 2 / tessellation;
  27000. var angle;
  27001. var h;
  27002. var radius;
  27003. var tan = (diameterBottom - diameterTop) / 2 / height;
  27004. var ringVertex = BABYLON.Vector3.Zero();
  27005. var ringNormal = BABYLON.Vector3.Zero();
  27006. // positions, normals, uvs
  27007. var i;
  27008. var j;
  27009. for (i = 0; i <= subdivisions; i++) {
  27010. h = i / subdivisions;
  27011. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27012. for (j = 0; j <= tessellation; j++) {
  27013. angle = j * angle_step;
  27014. ringVertex.x = Math.cos(-angle) * radius;
  27015. ringVertex.y = -height / 2 + h * height;
  27016. ringVertex.z = Math.sin(-angle) * radius;
  27017. if (diameterTop === 0 && i === subdivisions) {
  27018. // if no top cap, reuse former normals
  27019. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27020. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27021. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27022. }
  27023. else {
  27024. ringNormal.x = ringVertex.x;
  27025. ringNormal.z = ringVertex.z;
  27026. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27027. ringNormal.normalize();
  27028. }
  27029. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27030. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27031. uvs.push(faceUV[0].x + (faceUV[0].z - faceUV[0].x) * j / tessellation, faceUV[0].y + (faceUV[0].w - faceUV[0].y) * h);
  27032. if (faceColors) {
  27033. colors.push(faceColors[0].r, faceColors[0].g, faceColors[0].b, faceColors[0].a);
  27034. }
  27035. }
  27036. }
  27037. // indices
  27038. for (i = 0; i < subdivisions; i++) {
  27039. for (j = 0; j < tessellation; j++) {
  27040. var i0 = i * (tessellation + 1) + j;
  27041. var i1 = (i + 1) * (tessellation + 1) + j;
  27042. var i2 = i * (tessellation + 1) + (j + 1);
  27043. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  27044. indices.push(i0, i1, i2);
  27045. indices.push(i3, i2, i1);
  27046. }
  27047. }
  27048. // Caps
  27049. var createCylinderCap = function (isTop) {
  27050. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27051. if (radius === 0) {
  27052. return;
  27053. }
  27054. var vbase = positions.length / 3;
  27055. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  27056. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27057. // Cap positions, normals & uvs
  27058. var angle;
  27059. var circleVector;
  27060. var i;
  27061. var u = (isTop) ? faceUV[1] : faceUV[2];
  27062. var c;
  27063. if (faceColors) {
  27064. c = (isTop) ? faceColors[1] : faceColors[2];
  27065. }
  27066. for (i = 0; i < tessellation; i++) {
  27067. angle = Math.PI * 2 * i / tessellation;
  27068. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  27069. var position = circleVector.scale(radius).add(offset);
  27070. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  27071. positions.push(position.x, position.y, position.z);
  27072. normals.push(0, isTop ? 1 : -1, 0);
  27073. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27074. if (faceColors) {
  27075. colors.push(c.r, c.g, c.b, c.a);
  27076. }
  27077. }
  27078. // Cap indices
  27079. for (i = 0; i < tessellation - 2; i++) {
  27080. if (!isTop) {
  27081. indices.push(vbase);
  27082. indices.push(vbase + (i + 1) % tessellation);
  27083. indices.push(vbase + (i + 2) % tessellation);
  27084. }
  27085. else {
  27086. indices.push(vbase);
  27087. indices.push(vbase + (i + 2) % tessellation);
  27088. indices.push(vbase + (i + 1) % tessellation);
  27089. }
  27090. }
  27091. };
  27092. // add caps to geometry
  27093. createCylinderCap(true);
  27094. createCylinderCap(false);
  27095. // Sides
  27096. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27097. var vertexData = new VertexData();
  27098. vertexData.indices = indices;
  27099. vertexData.positions = positions;
  27100. vertexData.normals = normals;
  27101. vertexData.uvs = uvs;
  27102. if (faceColors) {
  27103. vertexData.colors = colors;
  27104. }
  27105. return vertexData;
  27106. };
  27107. VertexData.CreateTorus = function (options) {
  27108. var indices = [];
  27109. var positions = [];
  27110. var normals = [];
  27111. var uvs = [];
  27112. var diameter = options.diameter || 1;
  27113. var thickness = options.thickness || 0.5;
  27114. var tessellation = options.tessellation || 16;
  27115. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27116. var stride = tessellation + 1;
  27117. for (var i = 0; i <= tessellation; i++) {
  27118. var u = i / tessellation;
  27119. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27120. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27121. for (var j = 0; j <= tessellation; j++) {
  27122. var v = 1 - j / tessellation;
  27123. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27124. var dx = Math.cos(innerAngle);
  27125. var dy = Math.sin(innerAngle);
  27126. // Create a vertex.
  27127. var normal = new BABYLON.Vector3(dx, dy, 0);
  27128. var position = normal.scale(thickness / 2);
  27129. var textureCoordinate = new BABYLON.Vector2(u, v);
  27130. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27131. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27132. positions.push(position.x, position.y, position.z);
  27133. normals.push(normal.x, normal.y, normal.z);
  27134. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27135. // And create indices for two triangles.
  27136. var nextI = (i + 1) % stride;
  27137. var nextJ = (j + 1) % stride;
  27138. indices.push(i * stride + j);
  27139. indices.push(i * stride + nextJ);
  27140. indices.push(nextI * stride + j);
  27141. indices.push(i * stride + nextJ);
  27142. indices.push(nextI * stride + nextJ);
  27143. indices.push(nextI * stride + j);
  27144. }
  27145. }
  27146. // Sides
  27147. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27148. // Result
  27149. var vertexData = new VertexData();
  27150. vertexData.indices = indices;
  27151. vertexData.positions = positions;
  27152. vertexData.normals = normals;
  27153. vertexData.uvs = uvs;
  27154. return vertexData;
  27155. };
  27156. VertexData.CreateLines = function (options) {
  27157. var indices = [];
  27158. var positions = [];
  27159. var points = options.points;
  27160. for (var index = 0; index < points.length; index++) {
  27161. positions.push(points[index].x, points[index].y, points[index].z);
  27162. if (index > 0) {
  27163. indices.push(index - 1);
  27164. indices.push(index);
  27165. }
  27166. }
  27167. // Result
  27168. var vertexData = new VertexData();
  27169. vertexData.indices = indices;
  27170. vertexData.positions = positions;
  27171. return vertexData;
  27172. };
  27173. VertexData.CreateDashedLines = function (options) {
  27174. var dashSize = options.dashSize || 3;
  27175. var gapSize = options.gapSize || 1;
  27176. var dashNb = options.dashNb || 200;
  27177. var points = options.points;
  27178. var positions = new Array();
  27179. var indices = new Array();
  27180. var curvect = BABYLON.Vector3.Zero();
  27181. var lg = 0;
  27182. var nb = 0;
  27183. var shft = 0;
  27184. var dashshft = 0;
  27185. var curshft = 0;
  27186. var idx = 0;
  27187. var i = 0;
  27188. for (i = 0; i < points.length - 1; i++) {
  27189. points[i + 1].subtractToRef(points[i], curvect);
  27190. lg += curvect.length();
  27191. }
  27192. shft = lg / dashNb;
  27193. dashshft = dashSize * shft / (dashSize + gapSize);
  27194. for (i = 0; i < points.length - 1; i++) {
  27195. points[i + 1].subtractToRef(points[i], curvect);
  27196. nb = Math.floor(curvect.length() / shft);
  27197. curvect.normalize();
  27198. for (var j = 0; j < nb; j++) {
  27199. curshft = shft * j;
  27200. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27201. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27202. indices.push(idx, idx + 1);
  27203. idx += 2;
  27204. }
  27205. }
  27206. // Result
  27207. var vertexData = new VertexData();
  27208. vertexData.positions = positions;
  27209. vertexData.indices = indices;
  27210. return vertexData;
  27211. };
  27212. VertexData.CreateGround = function (options) {
  27213. var indices = [];
  27214. var positions = [];
  27215. var normals = [];
  27216. var uvs = [];
  27217. var row, col;
  27218. var width = options.width || 1;
  27219. var height = options.height || 1;
  27220. var subdivisions = options.subdivisions || 1;
  27221. for (row = 0; row <= subdivisions; row++) {
  27222. for (col = 0; col <= subdivisions; col++) {
  27223. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  27224. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27225. positions.push(position.x, position.y, position.z);
  27226. normals.push(normal.x, normal.y, normal.z);
  27227. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  27228. }
  27229. }
  27230. for (row = 0; row < subdivisions; row++) {
  27231. for (col = 0; col < subdivisions; col++) {
  27232. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27233. indices.push(col + 1 + row * (subdivisions + 1));
  27234. indices.push(col + row * (subdivisions + 1));
  27235. indices.push(col + (row + 1) * (subdivisions + 1));
  27236. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27237. indices.push(col + row * (subdivisions + 1));
  27238. }
  27239. }
  27240. // Result
  27241. var vertexData = new VertexData();
  27242. vertexData.indices = indices;
  27243. vertexData.positions = positions;
  27244. vertexData.normals = normals;
  27245. vertexData.uvs = uvs;
  27246. return vertexData;
  27247. };
  27248. VertexData.CreateTiledGround = function (options) {
  27249. var xmin = options.xmin;
  27250. var zmin = options.zmin;
  27251. var xmax = options.xmax;
  27252. var zmax = options.zmax;
  27253. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27254. var precision = options.precision || { w: 1, h: 1 };
  27255. var indices = [];
  27256. var positions = [];
  27257. var normals = [];
  27258. var uvs = [];
  27259. var row, col, tileRow, tileCol;
  27260. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  27261. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27262. precision.w = (precision.w < 1) ? 1 : precision.w;
  27263. precision.h = (precision.h < 1) ? 1 : precision.h;
  27264. var tileSize = {
  27265. 'w': (xmax - xmin) / subdivisions.w,
  27266. 'h': (zmax - zmin) / subdivisions.h
  27267. };
  27268. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27269. // Indices
  27270. var base = positions.length / 3;
  27271. var rowLength = precision.w + 1;
  27272. for (row = 0; row < precision.h; row++) {
  27273. for (col = 0; col < precision.w; col++) {
  27274. var square = [
  27275. base + col + row * rowLength,
  27276. base + (col + 1) + row * rowLength,
  27277. base + (col + 1) + (row + 1) * rowLength,
  27278. base + col + (row + 1) * rowLength
  27279. ];
  27280. indices.push(square[1]);
  27281. indices.push(square[2]);
  27282. indices.push(square[3]);
  27283. indices.push(square[0]);
  27284. indices.push(square[1]);
  27285. indices.push(square[3]);
  27286. }
  27287. }
  27288. // Position, normals and uvs
  27289. var position = BABYLON.Vector3.Zero();
  27290. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27291. for (row = 0; row <= precision.h; row++) {
  27292. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27293. for (col = 0; col <= precision.w; col++) {
  27294. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27295. position.y = 0;
  27296. positions.push(position.x, position.y, position.z);
  27297. normals.push(normal.x, normal.y, normal.z);
  27298. uvs.push(col / precision.w, row / precision.h);
  27299. }
  27300. }
  27301. }
  27302. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27303. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27304. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27305. }
  27306. }
  27307. // Result
  27308. var vertexData = new VertexData();
  27309. vertexData.indices = indices;
  27310. vertexData.positions = positions;
  27311. vertexData.normals = normals;
  27312. vertexData.uvs = uvs;
  27313. return vertexData;
  27314. };
  27315. VertexData.CreateGroundFromHeightMap = function (options) {
  27316. var indices = [];
  27317. var positions = [];
  27318. var normals = [];
  27319. var uvs = [];
  27320. var row, col;
  27321. // Vertices
  27322. for (row = 0; row <= options.subdivisions; row++) {
  27323. for (col = 0; col <= options.subdivisions; col++) {
  27324. 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));
  27325. // Compute height
  27326. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27327. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27328. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27329. var r = options.buffer[pos] / 255.0;
  27330. var g = options.buffer[pos + 1] / 255.0;
  27331. var b = options.buffer[pos + 2] / 255.0;
  27332. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27333. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27334. // Add vertex
  27335. positions.push(position.x, position.y, position.z);
  27336. normals.push(0, 0, 0);
  27337. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27338. }
  27339. }
  27340. // Indices
  27341. for (row = 0; row < options.subdivisions; row++) {
  27342. for (col = 0; col < options.subdivisions; col++) {
  27343. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27344. indices.push(col + 1 + row * (options.subdivisions + 1));
  27345. indices.push(col + row * (options.subdivisions + 1));
  27346. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27347. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27348. indices.push(col + row * (options.subdivisions + 1));
  27349. }
  27350. }
  27351. // Normals
  27352. VertexData.ComputeNormals(positions, indices, normals);
  27353. // Result
  27354. var vertexData = new VertexData();
  27355. vertexData.indices = indices;
  27356. vertexData.positions = positions;
  27357. vertexData.normals = normals;
  27358. vertexData.uvs = uvs;
  27359. return vertexData;
  27360. };
  27361. VertexData.CreatePlane = function (options) {
  27362. var indices = [];
  27363. var positions = [];
  27364. var normals = [];
  27365. var uvs = [];
  27366. var width = options.width || options.size || 1;
  27367. var height = options.height || options.size || 1;
  27368. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27369. // Vertices
  27370. var halfWidth = width / 2.0;
  27371. var halfHeight = height / 2.0;
  27372. positions.push(-halfWidth, -halfHeight, 0);
  27373. normals.push(0, 0, -1.0);
  27374. uvs.push(0.0, 0.0);
  27375. positions.push(halfWidth, -halfHeight, 0);
  27376. normals.push(0, 0, -1.0);
  27377. uvs.push(1.0, 0.0);
  27378. positions.push(halfWidth, halfHeight, 0);
  27379. normals.push(0, 0, -1.0);
  27380. uvs.push(1.0, 1.0);
  27381. positions.push(-halfWidth, halfHeight, 0);
  27382. normals.push(0, 0, -1.0);
  27383. uvs.push(0.0, 1.0);
  27384. // Indices
  27385. indices.push(0);
  27386. indices.push(1);
  27387. indices.push(2);
  27388. indices.push(0);
  27389. indices.push(2);
  27390. indices.push(3);
  27391. // Sides
  27392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27393. // Result
  27394. var vertexData = new VertexData();
  27395. vertexData.indices = indices;
  27396. vertexData.positions = positions;
  27397. vertexData.normals = normals;
  27398. vertexData.uvs = uvs;
  27399. return vertexData;
  27400. };
  27401. VertexData.CreateDisc = function (options) {
  27402. var positions = [];
  27403. var indices = [];
  27404. var normals = [];
  27405. var uvs = [];
  27406. var radius = options.radius || 0.5;
  27407. var tessellation = options.tessellation || 64;
  27408. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27409. // positions and uvs
  27410. positions.push(0, 0, 0); // disc center first
  27411. uvs.push(0.5, 0.5);
  27412. var step = Math.PI * 2 / tessellation;
  27413. for (var a = 0; a < Math.PI * 2; a += step) {
  27414. var x = Math.cos(a);
  27415. var y = Math.sin(a);
  27416. var u = (x + 1) / 2;
  27417. var v = (1 - y) / 2;
  27418. positions.push(radius * x, radius * y, 0);
  27419. uvs.push(u, v);
  27420. }
  27421. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27422. uvs.push(uvs[2], uvs[3]);
  27423. //indices
  27424. var vertexNb = positions.length / 3;
  27425. for (var i = 1; i < vertexNb - 1; i++) {
  27426. indices.push(i + 1, 0, i);
  27427. }
  27428. // result
  27429. VertexData.ComputeNormals(positions, indices, normals);
  27430. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27431. var vertexData = new VertexData();
  27432. vertexData.indices = indices;
  27433. vertexData.positions = positions;
  27434. vertexData.normals = normals;
  27435. vertexData.uvs = uvs;
  27436. return vertexData;
  27437. };
  27438. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27439. VertexData.CreateTorusKnot = function (options) {
  27440. var indices = [];
  27441. var positions = [];
  27442. var normals = [];
  27443. var uvs = [];
  27444. var radius = options.radius || 2;
  27445. var tube = options.tube || 0.5;
  27446. var radialSegments = options.radialSegments || 32;
  27447. var tubularSegments = options.tubularSegments || 32;
  27448. var p = options.p || 2;
  27449. var q = options.q || 3;
  27450. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27451. // Helper
  27452. var getPos = function (angle) {
  27453. var cu = Math.cos(angle);
  27454. var su = Math.sin(angle);
  27455. var quOverP = q / p * angle;
  27456. var cs = Math.cos(quOverP);
  27457. var tx = radius * (2 + cs) * 0.5 * cu;
  27458. var ty = radius * (2 + cs) * su * 0.5;
  27459. var tz = radius * Math.sin(quOverP) * 0.5;
  27460. return new BABYLON.Vector3(tx, ty, tz);
  27461. };
  27462. // Vertices
  27463. var i;
  27464. var j;
  27465. for (i = 0; i <= radialSegments; i++) {
  27466. var modI = i % radialSegments;
  27467. var u = modI / radialSegments * 2 * p * Math.PI;
  27468. var p1 = getPos(u);
  27469. var p2 = getPos(u + 0.01);
  27470. var tang = p2.subtract(p1);
  27471. var n = p2.add(p1);
  27472. var bitan = BABYLON.Vector3.Cross(tang, n);
  27473. n = BABYLON.Vector3.Cross(bitan, tang);
  27474. bitan.normalize();
  27475. n.normalize();
  27476. for (j = 0; j < tubularSegments; j++) {
  27477. var modJ = j % tubularSegments;
  27478. var v = modJ / tubularSegments * 2 * Math.PI;
  27479. var cx = -tube * Math.cos(v);
  27480. var cy = tube * Math.sin(v);
  27481. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27482. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27483. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27484. uvs.push(i / radialSegments);
  27485. uvs.push(j / tubularSegments);
  27486. }
  27487. }
  27488. for (i = 0; i < radialSegments; i++) {
  27489. for (j = 0; j < tubularSegments; j++) {
  27490. var jNext = (j + 1) % tubularSegments;
  27491. var a = i * tubularSegments + j;
  27492. var b = (i + 1) * tubularSegments + j;
  27493. var c = (i + 1) * tubularSegments + jNext;
  27494. var d = i * tubularSegments + jNext;
  27495. indices.push(d);
  27496. indices.push(b);
  27497. indices.push(a);
  27498. indices.push(d);
  27499. indices.push(c);
  27500. indices.push(b);
  27501. }
  27502. }
  27503. // Normals
  27504. VertexData.ComputeNormals(positions, indices, normals);
  27505. // Sides
  27506. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27507. // Result
  27508. var vertexData = new VertexData();
  27509. vertexData.indices = indices;
  27510. vertexData.positions = positions;
  27511. vertexData.normals = normals;
  27512. vertexData.uvs = uvs;
  27513. return vertexData;
  27514. };
  27515. // Tools
  27516. /**
  27517. * @param {any} - positions (number[] or Float32Array)
  27518. * @param {any} - indices (number[] or Uint16Array)
  27519. * @param {any} - normals (number[] or Float32Array)
  27520. */
  27521. VertexData.ComputeNormals = function (positions, indices, normals) {
  27522. var index = 0;
  27523. // temp Vector3
  27524. var p1p2 = BABYLON.Vector3.Zero();
  27525. var p3p2 = BABYLON.Vector3.Zero();
  27526. var faceNormal = BABYLON.Vector3.Zero();
  27527. var vertexNormali1 = BABYLON.Vector3.Zero();
  27528. for (index = 0; index < positions.length; index++) {
  27529. normals[index] = 0.0;
  27530. }
  27531. // indice triplet = 1 face
  27532. var nbFaces = indices.length / 3;
  27533. for (index = 0; index < nbFaces; index++) {
  27534. var i1 = indices[index * 3];
  27535. var i2 = indices[index * 3 + 1];
  27536. var i3 = indices[index * 3 + 2];
  27537. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27538. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27539. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27540. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27541. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27542. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27543. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27544. faceNormal.normalize();
  27545. normals[i1 * 3] += faceNormal.x;
  27546. normals[i1 * 3 + 1] += faceNormal.y;
  27547. normals[i1 * 3 + 2] += faceNormal.z;
  27548. normals[i2 * 3] += faceNormal.x;
  27549. normals[i2 * 3 + 1] += faceNormal.y;
  27550. normals[i2 * 3 + 2] += faceNormal.z;
  27551. normals[i3 * 3] += faceNormal.x;
  27552. normals[i3 * 3 + 1] += faceNormal.y;
  27553. normals[i3 * 3 + 2] += faceNormal.z;
  27554. }
  27555. // last normalization
  27556. for (index = 0; index < normals.length / 3; index++) {
  27557. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27558. vertexNormali1.normalize();
  27559. normals[index * 3] = vertexNormali1.x;
  27560. normals[index * 3 + 1] = vertexNormali1.y;
  27561. normals[index * 3 + 2] = vertexNormali1.z;
  27562. }
  27563. };
  27564. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27565. var li = indices.length;
  27566. var ln = normals.length;
  27567. var i;
  27568. var n;
  27569. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27570. switch (sideOrientation) {
  27571. case BABYLON.Mesh.FRONTSIDE:
  27572. // nothing changed
  27573. break;
  27574. case BABYLON.Mesh.BACKSIDE:
  27575. var tmp;
  27576. // indices
  27577. for (i = 0; i < li; i += 3) {
  27578. tmp = indices[i];
  27579. indices[i] = indices[i + 2];
  27580. indices[i + 2] = tmp;
  27581. }
  27582. // normals
  27583. for (n = 0; n < ln; n++) {
  27584. normals[n] = -normals[n];
  27585. }
  27586. break;
  27587. case BABYLON.Mesh.DOUBLESIDE:
  27588. // positions
  27589. var lp = positions.length;
  27590. var l = lp / 3;
  27591. for (var p = 0; p < lp; p++) {
  27592. positions[lp + p] = positions[p];
  27593. }
  27594. // indices
  27595. for (i = 0; i < li; i += 3) {
  27596. indices[i + li] = indices[i + 2] + l;
  27597. indices[i + 1 + li] = indices[i + 1] + l;
  27598. indices[i + 2 + li] = indices[i] + l;
  27599. }
  27600. // normals
  27601. for (n = 0; n < ln; n++) {
  27602. normals[ln + n] = -normals[n];
  27603. }
  27604. // uvs
  27605. var lu = uvs.length;
  27606. for (var u = 0; u < lu; u++) {
  27607. uvs[u + lu] = uvs[u];
  27608. }
  27609. break;
  27610. }
  27611. };
  27612. return VertexData;
  27613. })();
  27614. BABYLON.VertexData = VertexData;
  27615. })(BABYLON || (BABYLON = {}));
  27616. var BABYLON;
  27617. (function (BABYLON) {
  27618. var AnaglyphPostProcess = (function (_super) {
  27619. __extends(AnaglyphPostProcess, _super);
  27620. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27621. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27622. }
  27623. return AnaglyphPostProcess;
  27624. })(BABYLON.PostProcess);
  27625. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27626. })(BABYLON || (BABYLON = {}));
  27627. var BABYLON;
  27628. (function (BABYLON) {
  27629. var Tags = (function () {
  27630. function Tags() {
  27631. }
  27632. Tags.EnableFor = function (obj) {
  27633. obj._tags = obj._tags || {};
  27634. obj.hasTags = function () {
  27635. return Tags.HasTags(obj);
  27636. };
  27637. obj.addTags = function (tagsString) {
  27638. return Tags.AddTagsTo(obj, tagsString);
  27639. };
  27640. obj.removeTags = function (tagsString) {
  27641. return Tags.RemoveTagsFrom(obj, tagsString);
  27642. };
  27643. obj.matchesTagsQuery = function (tagsQuery) {
  27644. return Tags.MatchesQuery(obj, tagsQuery);
  27645. };
  27646. };
  27647. Tags.DisableFor = function (obj) {
  27648. delete obj._tags;
  27649. delete obj.hasTags;
  27650. delete obj.addTags;
  27651. delete obj.removeTags;
  27652. delete obj.matchesTagsQuery;
  27653. };
  27654. Tags.HasTags = function (obj) {
  27655. if (!obj._tags) {
  27656. return false;
  27657. }
  27658. return !BABYLON.Tools.IsEmpty(obj._tags);
  27659. };
  27660. Tags.GetTags = function (obj) {
  27661. if (!obj._tags) {
  27662. return null;
  27663. }
  27664. return obj._tags;
  27665. };
  27666. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27667. // a tag cannot start with '||', '&&', and '!'
  27668. // it cannot contain whitespaces
  27669. Tags.AddTagsTo = function (obj, tagsString) {
  27670. if (!tagsString) {
  27671. return;
  27672. }
  27673. var tags = tagsString.split(" ");
  27674. for (var t in tags) {
  27675. Tags._AddTagTo(obj, tags[t]);
  27676. }
  27677. };
  27678. Tags._AddTagTo = function (obj, tag) {
  27679. tag = tag.trim();
  27680. if (tag === "" || tag === "true" || tag === "false") {
  27681. return;
  27682. }
  27683. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27684. return;
  27685. }
  27686. Tags.EnableFor(obj);
  27687. obj._tags[tag] = true;
  27688. };
  27689. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27690. if (!Tags.HasTags(obj)) {
  27691. return;
  27692. }
  27693. var tags = tagsString.split(" ");
  27694. for (var t in tags) {
  27695. Tags._RemoveTagFrom(obj, tags[t]);
  27696. }
  27697. };
  27698. Tags._RemoveTagFrom = function (obj, tag) {
  27699. delete obj._tags[tag];
  27700. };
  27701. Tags.MatchesQuery = function (obj, tagsQuery) {
  27702. if (tagsQuery === undefined) {
  27703. return true;
  27704. }
  27705. if (tagsQuery === "") {
  27706. return Tags.HasTags(obj);
  27707. }
  27708. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27709. };
  27710. return Tags;
  27711. })();
  27712. BABYLON.Tags = Tags;
  27713. })(BABYLON || (BABYLON = {}));
  27714. var BABYLON;
  27715. (function (BABYLON) {
  27716. var Internals;
  27717. (function (Internals) {
  27718. var AndOrNotEvaluator = (function () {
  27719. function AndOrNotEvaluator() {
  27720. }
  27721. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27722. if (!query.match(/\([^\(\)]*\)/g)) {
  27723. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27724. }
  27725. else {
  27726. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27727. // remove parenthesis
  27728. r = r.slice(1, r.length - 1);
  27729. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27730. });
  27731. }
  27732. if (query === "true") {
  27733. return true;
  27734. }
  27735. if (query === "false") {
  27736. return false;
  27737. }
  27738. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27739. };
  27740. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27741. evaluateCallback = evaluateCallback || (function (r) {
  27742. return r === "true" ? true : false;
  27743. });
  27744. var result;
  27745. var or = parenthesisContent.split("||");
  27746. for (var i in or) {
  27747. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27748. var and = ori.split("&&");
  27749. if (and.length > 1) {
  27750. for (var j = 0; j < and.length; ++j) {
  27751. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27752. if (andj !== "true" && andj !== "false") {
  27753. if (andj[0] === "!") {
  27754. result = !evaluateCallback(andj.substring(1));
  27755. }
  27756. else {
  27757. result = evaluateCallback(andj);
  27758. }
  27759. }
  27760. else {
  27761. result = andj === "true" ? true : false;
  27762. }
  27763. if (!result) {
  27764. ori = "false";
  27765. break;
  27766. }
  27767. }
  27768. }
  27769. if (result || ori === "true") {
  27770. result = true;
  27771. break;
  27772. }
  27773. // result equals false (or undefined)
  27774. if (ori !== "true" && ori !== "false") {
  27775. if (ori[0] === "!") {
  27776. result = !evaluateCallback(ori.substring(1));
  27777. }
  27778. else {
  27779. result = evaluateCallback(ori);
  27780. }
  27781. }
  27782. else {
  27783. result = ori === "true" ? true : false;
  27784. }
  27785. }
  27786. // the whole parenthesis scope is replaced by 'true' or 'false'
  27787. return result ? "true" : "false";
  27788. };
  27789. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27790. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27791. // remove whitespaces
  27792. r = r.replace(/[\s]/g, function () { return ""; });
  27793. return r.length % 2 ? "!" : "";
  27794. });
  27795. booleanString = booleanString.trim();
  27796. if (booleanString === "!true") {
  27797. booleanString = "false";
  27798. }
  27799. else if (booleanString === "!false") {
  27800. booleanString = "true";
  27801. }
  27802. return booleanString;
  27803. };
  27804. return AndOrNotEvaluator;
  27805. })();
  27806. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27807. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27808. })(BABYLON || (BABYLON = {}));
  27809. var BABYLON;
  27810. (function (BABYLON) {
  27811. var PostProcessRenderPass = (function () {
  27812. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27813. this._enabled = true;
  27814. this._refCount = 0;
  27815. this._name = name;
  27816. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27817. this.setRenderList(renderList);
  27818. this._renderTexture.onBeforeRender = beforeRender;
  27819. this._renderTexture.onAfterRender = afterRender;
  27820. this._scene = scene;
  27821. this._renderList = renderList;
  27822. }
  27823. // private
  27824. PostProcessRenderPass.prototype._incRefCount = function () {
  27825. if (this._refCount === 0) {
  27826. this._scene.customRenderTargets.push(this._renderTexture);
  27827. }
  27828. return ++this._refCount;
  27829. };
  27830. PostProcessRenderPass.prototype._decRefCount = function () {
  27831. this._refCount--;
  27832. if (this._refCount <= 0) {
  27833. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27834. }
  27835. return this._refCount;
  27836. };
  27837. PostProcessRenderPass.prototype._update = function () {
  27838. this.setRenderList(this._renderList);
  27839. };
  27840. // public
  27841. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27842. this._renderTexture.renderList = renderList;
  27843. };
  27844. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27845. return this._renderTexture;
  27846. };
  27847. return PostProcessRenderPass;
  27848. })();
  27849. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27850. })(BABYLON || (BABYLON = {}));
  27851. var BABYLON;
  27852. (function (BABYLON) {
  27853. var PostProcessRenderEffect = (function () {
  27854. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27855. this._engine = engine;
  27856. this._name = name;
  27857. this._singleInstance = singleInstance || true;
  27858. this._getPostProcess = getPostProcess;
  27859. this._cameras = [];
  27860. this._indicesForCamera = [];
  27861. this._postProcesses = {};
  27862. this._renderPasses = {};
  27863. this._renderEffectAsPasses = {};
  27864. }
  27865. PostProcessRenderEffect.prototype._update = function () {
  27866. for (var renderPassName in this._renderPasses) {
  27867. this._renderPasses[renderPassName]._update();
  27868. }
  27869. };
  27870. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27871. this._renderPasses[renderPass._name] = renderPass;
  27872. this._linkParameters();
  27873. };
  27874. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27875. delete this._renderPasses[renderPass._name];
  27876. this._linkParameters();
  27877. };
  27878. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27879. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27880. this._linkParameters();
  27881. };
  27882. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27883. for (var renderPassName in this._renderPasses) {
  27884. if (renderPassName === passName) {
  27885. return this._renderPasses[passName];
  27886. }
  27887. }
  27888. };
  27889. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27890. this._renderPasses = {};
  27891. this._linkParameters();
  27892. };
  27893. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27894. var cameraKey;
  27895. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27896. for (var i = 0; i < _cam.length; i++) {
  27897. var camera = _cam[i];
  27898. var cameraName = camera.name;
  27899. if (this._singleInstance) {
  27900. cameraKey = 0;
  27901. }
  27902. else {
  27903. cameraKey = cameraName;
  27904. }
  27905. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27906. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27907. if (!this._indicesForCamera[cameraName]) {
  27908. this._indicesForCamera[cameraName] = [];
  27909. }
  27910. this._indicesForCamera[cameraName].push(index);
  27911. if (this._cameras.indexOf(camera) === -1) {
  27912. this._cameras[cameraName] = camera;
  27913. }
  27914. for (var passName in this._renderPasses) {
  27915. this._renderPasses[passName]._incRefCount();
  27916. }
  27917. }
  27918. this._linkParameters();
  27919. };
  27920. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27921. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27922. for (var i = 0; i < _cam.length; i++) {
  27923. var camera = _cam[i];
  27924. var cameraName = camera.name;
  27925. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27926. var index = this._cameras.indexOf(cameraName);
  27927. this._indicesForCamera.splice(index, 1);
  27928. this._cameras.splice(index, 1);
  27929. for (var passName in this._renderPasses) {
  27930. this._renderPasses[passName]._decRefCount();
  27931. }
  27932. }
  27933. };
  27934. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27935. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27936. for (var i = 0; i < _cam.length; i++) {
  27937. var camera = _cam[i];
  27938. var cameraName = camera.name;
  27939. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27940. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27941. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27942. }
  27943. }
  27944. for (var passName in this._renderPasses) {
  27945. this._renderPasses[passName]._incRefCount();
  27946. }
  27947. }
  27948. };
  27949. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27950. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27951. for (var i = 0; i < _cam.length; i++) {
  27952. var camera = _cam[i];
  27953. var cameraName = camera.Name;
  27954. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27955. for (var passName in this._renderPasses) {
  27956. this._renderPasses[passName]._decRefCount();
  27957. }
  27958. }
  27959. };
  27960. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27961. if (this._singleInstance) {
  27962. return this._postProcesses[0];
  27963. }
  27964. else {
  27965. return this._postProcesses[camera.name];
  27966. }
  27967. };
  27968. PostProcessRenderEffect.prototype._linkParameters = function () {
  27969. var _this = this;
  27970. for (var index in this._postProcesses) {
  27971. if (this.applyParameters) {
  27972. this.applyParameters(this._postProcesses[index]);
  27973. }
  27974. this._postProcesses[index].onBeforeRender = function (effect) {
  27975. _this._linkTextures(effect);
  27976. };
  27977. }
  27978. };
  27979. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27980. for (var renderPassName in this._renderPasses) {
  27981. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27982. }
  27983. for (var renderEffectName in this._renderEffectAsPasses) {
  27984. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27985. }
  27986. };
  27987. return PostProcessRenderEffect;
  27988. })();
  27989. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27990. })(BABYLON || (BABYLON = {}));
  27991. var BABYLON;
  27992. (function (BABYLON) {
  27993. var PostProcessRenderPipeline = (function () {
  27994. function PostProcessRenderPipeline(engine, name) {
  27995. this._engine = engine;
  27996. this._name = name;
  27997. this._renderEffects = {};
  27998. this._renderEffectsForIsolatedPass = {};
  27999. this._cameras = [];
  28000. }
  28001. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  28002. this._renderEffects[renderEffect._name] = renderEffect;
  28003. };
  28004. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  28005. var renderEffects = this._renderEffects[renderEffectName];
  28006. if (!renderEffects) {
  28007. return;
  28008. }
  28009. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28010. };
  28011. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  28012. var renderEffects = this._renderEffects[renderEffectName];
  28013. if (!renderEffects) {
  28014. return;
  28015. }
  28016. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28017. };
  28018. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  28019. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28020. var indicesToDelete = [];
  28021. for (var i = 0; i < _cam.length; i++) {
  28022. var camera = _cam[i];
  28023. var cameraName = camera.name;
  28024. if (this._cameras.indexOf(camera) === -1) {
  28025. this._cameras[cameraName] = camera;
  28026. }
  28027. else if (unique) {
  28028. indicesToDelete.push(i);
  28029. }
  28030. }
  28031. for (var i = 0; i < indicesToDelete.length; i++) {
  28032. cameras.splice(indicesToDelete[i], 1);
  28033. }
  28034. for (var renderEffectName in this._renderEffects) {
  28035. this._renderEffects[renderEffectName]._attachCameras(_cam);
  28036. }
  28037. };
  28038. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  28039. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28040. for (var renderEffectName in this._renderEffects) {
  28041. this._renderEffects[renderEffectName]._detachCameras(_cam);
  28042. }
  28043. for (var i = 0; i < _cam.length; i++) {
  28044. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  28045. }
  28046. };
  28047. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  28048. var _this = this;
  28049. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28050. var pass = null;
  28051. for (var renderEffectName in this._renderEffects) {
  28052. pass = this._renderEffects[renderEffectName].getPass(passName);
  28053. if (pass != null) {
  28054. break;
  28055. }
  28056. }
  28057. if (pass === null) {
  28058. return;
  28059. }
  28060. for (var renderEffectName in this._renderEffects) {
  28061. this._renderEffects[renderEffectName]._disable(_cam);
  28062. }
  28063. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  28064. for (var i = 0; i < _cam.length; i++) {
  28065. var camera = _cam[i];
  28066. var cameraName = camera.name;
  28067. 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); });
  28068. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  28069. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  28070. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  28071. }
  28072. };
  28073. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  28074. var _this = this;
  28075. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28076. for (var i = 0; i < _cam.length; i++) {
  28077. var camera = _cam[i];
  28078. var cameraName = camera.name;
  28079. 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); });
  28080. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  28081. }
  28082. for (var renderEffectName in this._renderEffects) {
  28083. this._renderEffects[renderEffectName]._enable(_cam);
  28084. }
  28085. };
  28086. PostProcessRenderPipeline.prototype._update = function () {
  28087. for (var renderEffectName in this._renderEffects) {
  28088. this._renderEffects[renderEffectName]._update();
  28089. }
  28090. for (var i = 0; i < this._cameras.length; i++) {
  28091. var cameraName = this._cameras[i].name;
  28092. if (this._renderEffectsForIsolatedPass[cameraName]) {
  28093. this._renderEffectsForIsolatedPass[cameraName]._update();
  28094. }
  28095. }
  28096. };
  28097. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  28098. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  28099. return PostProcessRenderPipeline;
  28100. })();
  28101. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  28102. })(BABYLON || (BABYLON = {}));
  28103. var BABYLON;
  28104. (function (BABYLON) {
  28105. var PostProcessRenderPipelineManager = (function () {
  28106. function PostProcessRenderPipelineManager() {
  28107. this._renderPipelines = {};
  28108. }
  28109. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  28110. this._renderPipelines[renderPipeline._name] = renderPipeline;
  28111. };
  28112. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  28113. var renderPipeline = this._renderPipelines[renderPipelineName];
  28114. if (!renderPipeline) {
  28115. return;
  28116. }
  28117. renderPipeline._attachCameras(cameras, unique);
  28118. };
  28119. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  28120. var renderPipeline = this._renderPipelines[renderPipelineName];
  28121. if (!renderPipeline) {
  28122. return;
  28123. }
  28124. renderPipeline._detachCameras(cameras);
  28125. };
  28126. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28127. var renderPipeline = this._renderPipelines[renderPipelineName];
  28128. if (!renderPipeline) {
  28129. return;
  28130. }
  28131. renderPipeline._enableEffect(renderEffectName, cameras);
  28132. };
  28133. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28134. var renderPipeline = this._renderPipelines[renderPipelineName];
  28135. if (!renderPipeline) {
  28136. return;
  28137. }
  28138. renderPipeline._disableEffect(renderEffectName, cameras);
  28139. };
  28140. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  28141. var renderPipeline = this._renderPipelines[renderPipelineName];
  28142. if (!renderPipeline) {
  28143. return;
  28144. }
  28145. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  28146. };
  28147. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  28148. var renderPipeline = this._renderPipelines[renderPipelineName];
  28149. if (!renderPipeline) {
  28150. return;
  28151. }
  28152. renderPipeline._disableDisplayOnlyPass(cameras);
  28153. };
  28154. PostProcessRenderPipelineManager.prototype.update = function () {
  28155. for (var renderPipelineName in this._renderPipelines) {
  28156. this._renderPipelines[renderPipelineName]._update();
  28157. }
  28158. };
  28159. return PostProcessRenderPipelineManager;
  28160. })();
  28161. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  28162. })(BABYLON || (BABYLON = {}));
  28163. var BABYLON;
  28164. (function (BABYLON) {
  28165. var DisplayPassPostProcess = (function (_super) {
  28166. __extends(DisplayPassPostProcess, _super);
  28167. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28168. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28169. }
  28170. return DisplayPassPostProcess;
  28171. })(BABYLON.PostProcess);
  28172. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28173. })(BABYLON || (BABYLON = {}));
  28174. var BABYLON;
  28175. (function (BABYLON) {
  28176. var BoundingBoxRenderer = (function () {
  28177. function BoundingBoxRenderer(scene) {
  28178. this.frontColor = new BABYLON.Color3(1, 1, 1);
  28179. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  28180. this.showBackLines = true;
  28181. this.renderList = new BABYLON.SmartArray(32);
  28182. this._scene = scene;
  28183. }
  28184. BoundingBoxRenderer.prototype._prepareRessources = function () {
  28185. if (this._colorShader) {
  28186. return;
  28187. }
  28188. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  28189. attributes: ["position"],
  28190. uniforms: ["worldViewProjection", "color"]
  28191. });
  28192. var engine = this._scene.getEngine();
  28193. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  28194. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  28195. 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]);
  28196. };
  28197. BoundingBoxRenderer.prototype.reset = function () {
  28198. this.renderList.reset();
  28199. };
  28200. BoundingBoxRenderer.prototype.render = function () {
  28201. if (this.renderList.length === 0) {
  28202. return;
  28203. }
  28204. this._prepareRessources();
  28205. if (!this._colorShader.isReady()) {
  28206. return;
  28207. }
  28208. var engine = this._scene.getEngine();
  28209. engine.setDepthWrite(false);
  28210. this._colorShader._preBind();
  28211. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  28212. var boundingBox = this.renderList.data[boundingBoxIndex];
  28213. var min = boundingBox.minimum;
  28214. var max = boundingBox.maximum;
  28215. var diff = max.subtract(min);
  28216. var median = min.add(diff.scale(0.5));
  28217. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  28218. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  28219. .multiply(boundingBox.getWorldMatrix());
  28220. // VBOs
  28221. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  28222. if (this.showBackLines) {
  28223. // Back
  28224. engine.setDepthFunctionToGreaterOrEqual();
  28225. this._scene.resetCachedMaterial();
  28226. this._colorShader.setColor4("color", this.backColor.toColor4());
  28227. this._colorShader.bind(worldMatrix);
  28228. // Draw order
  28229. engine.draw(false, 0, 24);
  28230. }
  28231. // Front
  28232. engine.setDepthFunctionToLess();
  28233. this._scene.resetCachedMaterial();
  28234. this._colorShader.setColor4("color", this.frontColor.toColor4());
  28235. this._colorShader.bind(worldMatrix);
  28236. // Draw order
  28237. engine.draw(false, 0, 24);
  28238. }
  28239. this._colorShader.unbind();
  28240. engine.setDepthFunctionToLessOrEqual();
  28241. engine.setDepthWrite(true);
  28242. };
  28243. BoundingBoxRenderer.prototype.dispose = function () {
  28244. if (!this._colorShader) {
  28245. return;
  28246. }
  28247. this._colorShader.dispose();
  28248. this._vb.dispose();
  28249. this._scene.getEngine()._releaseBuffer(this._ib);
  28250. };
  28251. return BoundingBoxRenderer;
  28252. })();
  28253. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  28254. })(BABYLON || (BABYLON = {}));
  28255. var BABYLON;
  28256. (function (BABYLON) {
  28257. var Condition = (function () {
  28258. function Condition(actionManager) {
  28259. this._actionManager = actionManager;
  28260. }
  28261. Condition.prototype.isValid = function () {
  28262. return true;
  28263. };
  28264. Condition.prototype._getProperty = function (propertyPath) {
  28265. return this._actionManager._getProperty(propertyPath);
  28266. };
  28267. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  28268. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28269. };
  28270. return Condition;
  28271. })();
  28272. BABYLON.Condition = Condition;
  28273. var ValueCondition = (function (_super) {
  28274. __extends(ValueCondition, _super);
  28275. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  28276. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  28277. _super.call(this, actionManager);
  28278. this.propertyPath = propertyPath;
  28279. this.value = value;
  28280. this.operator = operator;
  28281. this._target = this._getEffectiveTarget(target, this.propertyPath);
  28282. this._property = this._getProperty(this.propertyPath);
  28283. }
  28284. Object.defineProperty(ValueCondition, "IsEqual", {
  28285. get: function () {
  28286. return ValueCondition._IsEqual;
  28287. },
  28288. enumerable: true,
  28289. configurable: true
  28290. });
  28291. Object.defineProperty(ValueCondition, "IsDifferent", {
  28292. get: function () {
  28293. return ValueCondition._IsDifferent;
  28294. },
  28295. enumerable: true,
  28296. configurable: true
  28297. });
  28298. Object.defineProperty(ValueCondition, "IsGreater", {
  28299. get: function () {
  28300. return ValueCondition._IsGreater;
  28301. },
  28302. enumerable: true,
  28303. configurable: true
  28304. });
  28305. Object.defineProperty(ValueCondition, "IsLesser", {
  28306. get: function () {
  28307. return ValueCondition._IsLesser;
  28308. },
  28309. enumerable: true,
  28310. configurable: true
  28311. });
  28312. // Methods
  28313. ValueCondition.prototype.isValid = function () {
  28314. switch (this.operator) {
  28315. case ValueCondition.IsGreater:
  28316. return this._target[this._property] > this.value;
  28317. case ValueCondition.IsLesser:
  28318. return this._target[this._property] < this.value;
  28319. case ValueCondition.IsEqual:
  28320. case ValueCondition.IsDifferent:
  28321. var check;
  28322. if (this.value.equals) {
  28323. check = this.value.equals(this._target[this._property]);
  28324. }
  28325. else {
  28326. check = this.value === this._target[this._property];
  28327. }
  28328. return this.operator === ValueCondition.IsEqual ? check : !check;
  28329. }
  28330. return false;
  28331. };
  28332. // Statics
  28333. ValueCondition._IsEqual = 0;
  28334. ValueCondition._IsDifferent = 1;
  28335. ValueCondition._IsGreater = 2;
  28336. ValueCondition._IsLesser = 3;
  28337. return ValueCondition;
  28338. })(Condition);
  28339. BABYLON.ValueCondition = ValueCondition;
  28340. var PredicateCondition = (function (_super) {
  28341. __extends(PredicateCondition, _super);
  28342. function PredicateCondition(actionManager, predicate) {
  28343. _super.call(this, actionManager);
  28344. this.predicate = predicate;
  28345. }
  28346. PredicateCondition.prototype.isValid = function () {
  28347. return this.predicate();
  28348. };
  28349. return PredicateCondition;
  28350. })(Condition);
  28351. BABYLON.PredicateCondition = PredicateCondition;
  28352. var StateCondition = (function (_super) {
  28353. __extends(StateCondition, _super);
  28354. function StateCondition(actionManager, target, value) {
  28355. _super.call(this, actionManager);
  28356. this.value = value;
  28357. this._target = target;
  28358. }
  28359. // Methods
  28360. StateCondition.prototype.isValid = function () {
  28361. return this._target.state === this.value;
  28362. };
  28363. return StateCondition;
  28364. })(Condition);
  28365. BABYLON.StateCondition = StateCondition;
  28366. })(BABYLON || (BABYLON = {}));
  28367. var BABYLON;
  28368. (function (BABYLON) {
  28369. var Action = (function () {
  28370. function Action(triggerOptions, condition) {
  28371. this.triggerOptions = triggerOptions;
  28372. if (triggerOptions.parameter) {
  28373. this.trigger = triggerOptions.trigger;
  28374. this._triggerParameter = triggerOptions.parameter;
  28375. }
  28376. else {
  28377. this.trigger = triggerOptions;
  28378. }
  28379. this._nextActiveAction = this;
  28380. this._condition = condition;
  28381. }
  28382. // Methods
  28383. Action.prototype._prepare = function () {
  28384. };
  28385. Action.prototype.getTriggerParameter = function () {
  28386. return this._triggerParameter;
  28387. };
  28388. Action.prototype._executeCurrent = function (evt) {
  28389. if (this._nextActiveAction._condition) {
  28390. var condition = this._nextActiveAction._condition;
  28391. var currentRenderId = this._actionManager.getScene().getRenderId();
  28392. // We cache the current evaluation for the current frame
  28393. if (condition._evaluationId === currentRenderId) {
  28394. if (!condition._currentResult) {
  28395. return;
  28396. }
  28397. }
  28398. else {
  28399. condition._evaluationId = currentRenderId;
  28400. if (!condition.isValid()) {
  28401. condition._currentResult = false;
  28402. return;
  28403. }
  28404. condition._currentResult = true;
  28405. }
  28406. }
  28407. this._nextActiveAction.execute(evt);
  28408. if (this._nextActiveAction._child) {
  28409. if (!this._nextActiveAction._child._actionManager) {
  28410. this._nextActiveAction._child._actionManager = this._actionManager;
  28411. }
  28412. this._nextActiveAction = this._nextActiveAction._child;
  28413. }
  28414. else {
  28415. this._nextActiveAction = this;
  28416. }
  28417. };
  28418. Action.prototype.execute = function (evt) {
  28419. };
  28420. Action.prototype.then = function (action) {
  28421. this._child = action;
  28422. action._actionManager = this._actionManager;
  28423. action._prepare();
  28424. return action;
  28425. };
  28426. Action.prototype._getProperty = function (propertyPath) {
  28427. return this._actionManager._getProperty(propertyPath);
  28428. };
  28429. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28430. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28431. };
  28432. return Action;
  28433. })();
  28434. BABYLON.Action = Action;
  28435. })(BABYLON || (BABYLON = {}));
  28436. var BABYLON;
  28437. (function (BABYLON) {
  28438. /**
  28439. * ActionEvent is the event beint sent when an action is triggered.
  28440. */
  28441. var ActionEvent = (function () {
  28442. /**
  28443. * @constructor
  28444. * @param source The mesh that triggered the action.
  28445. * @param pointerX the X mouse cursor position at the time of the event
  28446. * @param pointerY the Y mouse cursor position at the time of the event
  28447. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28448. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28449. */
  28450. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28451. this.source = source;
  28452. this.pointerX = pointerX;
  28453. this.pointerY = pointerY;
  28454. this.meshUnderPointer = meshUnderPointer;
  28455. this.sourceEvent = sourceEvent;
  28456. this.additionalData = additionalData;
  28457. }
  28458. /**
  28459. * Helper function to auto-create an ActionEvent from a source mesh.
  28460. * @param source the source mesh that triggered the event
  28461. * @param evt {Event} The original (browser) event
  28462. */
  28463. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28464. var scene = source.getScene();
  28465. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28466. };
  28467. /**
  28468. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28469. * @param scene the scene where the event occurred
  28470. * @param evt {Event} The original (browser) event
  28471. */
  28472. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28473. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28474. };
  28475. return ActionEvent;
  28476. })();
  28477. BABYLON.ActionEvent = ActionEvent;
  28478. /**
  28479. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28480. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28481. */
  28482. var ActionManager = (function () {
  28483. function ActionManager(scene) {
  28484. // Members
  28485. this.actions = new Array();
  28486. this._scene = scene;
  28487. scene._actionManagers.push(this);
  28488. }
  28489. Object.defineProperty(ActionManager, "NothingTrigger", {
  28490. get: function () {
  28491. return ActionManager._NothingTrigger;
  28492. },
  28493. enumerable: true,
  28494. configurable: true
  28495. });
  28496. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28497. get: function () {
  28498. return ActionManager._OnPickTrigger;
  28499. },
  28500. enumerable: true,
  28501. configurable: true
  28502. });
  28503. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28504. get: function () {
  28505. return ActionManager._OnLeftPickTrigger;
  28506. },
  28507. enumerable: true,
  28508. configurable: true
  28509. });
  28510. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28511. get: function () {
  28512. return ActionManager._OnRightPickTrigger;
  28513. },
  28514. enumerable: true,
  28515. configurable: true
  28516. });
  28517. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28518. get: function () {
  28519. return ActionManager._OnCenterPickTrigger;
  28520. },
  28521. enumerable: true,
  28522. configurable: true
  28523. });
  28524. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28525. get: function () {
  28526. return ActionManager._OnPointerOverTrigger;
  28527. },
  28528. enumerable: true,
  28529. configurable: true
  28530. });
  28531. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28532. get: function () {
  28533. return ActionManager._OnPointerOutTrigger;
  28534. },
  28535. enumerable: true,
  28536. configurable: true
  28537. });
  28538. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28539. get: function () {
  28540. return ActionManager._OnEveryFrameTrigger;
  28541. },
  28542. enumerable: true,
  28543. configurable: true
  28544. });
  28545. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28546. get: function () {
  28547. return ActionManager._OnIntersectionEnterTrigger;
  28548. },
  28549. enumerable: true,
  28550. configurable: true
  28551. });
  28552. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28553. get: function () {
  28554. return ActionManager._OnIntersectionExitTrigger;
  28555. },
  28556. enumerable: true,
  28557. configurable: true
  28558. });
  28559. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28560. get: function () {
  28561. return ActionManager._OnKeyDownTrigger;
  28562. },
  28563. enumerable: true,
  28564. configurable: true
  28565. });
  28566. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28567. get: function () {
  28568. return ActionManager._OnKeyUpTrigger;
  28569. },
  28570. enumerable: true,
  28571. configurable: true
  28572. });
  28573. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28574. get: function () {
  28575. return ActionManager._OnPickUpTrigger;
  28576. },
  28577. enumerable: true,
  28578. configurable: true
  28579. });
  28580. // Methods
  28581. ActionManager.prototype.dispose = function () {
  28582. var index = this._scene._actionManagers.indexOf(this);
  28583. if (index > -1) {
  28584. this._scene._actionManagers.splice(index, 1);
  28585. }
  28586. };
  28587. ActionManager.prototype.getScene = function () {
  28588. return this._scene;
  28589. };
  28590. /**
  28591. * Does this action manager handles actions of any of the given triggers
  28592. * @param {number[]} triggers - the triggers to be tested
  28593. * @return {boolean} whether one (or more) of the triggers is handeled
  28594. */
  28595. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28596. for (var index = 0; index < this.actions.length; index++) {
  28597. var action = this.actions[index];
  28598. if (triggers.indexOf(action.trigger) > -1) {
  28599. return true;
  28600. }
  28601. }
  28602. return false;
  28603. };
  28604. /**
  28605. * Does this action manager handles actions of a given trigger
  28606. * @param {number} trigger - the trigger to be tested
  28607. * @return {boolean} whether the trigger is handeled
  28608. */
  28609. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28610. for (var index = 0; index < this.actions.length; index++) {
  28611. var action = this.actions[index];
  28612. if (action.trigger === trigger) {
  28613. return true;
  28614. }
  28615. }
  28616. return false;
  28617. };
  28618. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28619. /**
  28620. * Does this action manager has pointer triggers
  28621. * @return {boolean} whether or not it has pointer triggers
  28622. */
  28623. get: function () {
  28624. for (var index = 0; index < this.actions.length; index++) {
  28625. var action = this.actions[index];
  28626. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28627. return true;
  28628. }
  28629. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28630. return true;
  28631. }
  28632. }
  28633. return false;
  28634. },
  28635. enumerable: true,
  28636. configurable: true
  28637. });
  28638. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28639. /**
  28640. * Does this action manager has pick triggers
  28641. * @return {boolean} whether or not it has pick triggers
  28642. */
  28643. get: function () {
  28644. for (var index = 0; index < this.actions.length; index++) {
  28645. var action = this.actions[index];
  28646. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28647. return true;
  28648. }
  28649. }
  28650. return false;
  28651. },
  28652. enumerable: true,
  28653. configurable: true
  28654. });
  28655. /**
  28656. * Registers an action to this action manager
  28657. * @param {BABYLON.Action} action - the action to be registered
  28658. * @return {BABYLON.Action} the action amended (prepared) after registration
  28659. */
  28660. ActionManager.prototype.registerAction = function (action) {
  28661. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28662. if (this.getScene().actionManager !== this) {
  28663. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28664. return null;
  28665. }
  28666. }
  28667. this.actions.push(action);
  28668. action._actionManager = this;
  28669. action._prepare();
  28670. return action;
  28671. };
  28672. /**
  28673. * Process a specific trigger
  28674. * @param {number} trigger - the trigger to process
  28675. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28676. */
  28677. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28678. for (var index = 0; index < this.actions.length; index++) {
  28679. var action = this.actions[index];
  28680. if (action.trigger === trigger) {
  28681. if (trigger === ActionManager.OnKeyUpTrigger
  28682. || trigger === ActionManager.OnKeyDownTrigger) {
  28683. var parameter = action.getTriggerParameter();
  28684. if (parameter) {
  28685. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28686. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28687. if (actualkey !== parameter.toLowerCase()) {
  28688. continue;
  28689. }
  28690. }
  28691. }
  28692. action._executeCurrent(evt);
  28693. }
  28694. }
  28695. };
  28696. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28697. var properties = propertyPath.split(".");
  28698. for (var index = 0; index < properties.length - 1; index++) {
  28699. target = target[properties[index]];
  28700. }
  28701. return target;
  28702. };
  28703. ActionManager.prototype._getProperty = function (propertyPath) {
  28704. var properties = propertyPath.split(".");
  28705. return properties[properties.length - 1];
  28706. };
  28707. // Statics
  28708. ActionManager._NothingTrigger = 0;
  28709. ActionManager._OnPickTrigger = 1;
  28710. ActionManager._OnLeftPickTrigger = 2;
  28711. ActionManager._OnRightPickTrigger = 3;
  28712. ActionManager._OnCenterPickTrigger = 4;
  28713. ActionManager._OnPointerOverTrigger = 5;
  28714. ActionManager._OnPointerOutTrigger = 6;
  28715. ActionManager._OnEveryFrameTrigger = 7;
  28716. ActionManager._OnIntersectionEnterTrigger = 8;
  28717. ActionManager._OnIntersectionExitTrigger = 9;
  28718. ActionManager._OnKeyDownTrigger = 10;
  28719. ActionManager._OnKeyUpTrigger = 11;
  28720. ActionManager._OnPickUpTrigger = 12;
  28721. return ActionManager;
  28722. })();
  28723. BABYLON.ActionManager = ActionManager;
  28724. })(BABYLON || (BABYLON = {}));
  28725. var BABYLON;
  28726. (function (BABYLON) {
  28727. var InterpolateValueAction = (function (_super) {
  28728. __extends(InterpolateValueAction, _super);
  28729. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  28730. if (duration === void 0) { duration = 1000; }
  28731. _super.call(this, triggerOptions, condition);
  28732. this.propertyPath = propertyPath;
  28733. this.value = value;
  28734. this.duration = duration;
  28735. this.stopOtherAnimations = stopOtherAnimations;
  28736. this.onInterpolationDone = onInterpolationDone;
  28737. this._target = target;
  28738. }
  28739. InterpolateValueAction.prototype._prepare = function () {
  28740. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28741. this._property = this._getProperty(this.propertyPath);
  28742. };
  28743. InterpolateValueAction.prototype.execute = function () {
  28744. var scene = this._actionManager.getScene();
  28745. var keys = [
  28746. {
  28747. frame: 0,
  28748. value: this._target[this._property]
  28749. }, {
  28750. frame: 100,
  28751. value: this.value
  28752. }
  28753. ];
  28754. var dataType;
  28755. if (typeof this.value === "number") {
  28756. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28757. }
  28758. else if (this.value instanceof BABYLON.Color3) {
  28759. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28760. }
  28761. else if (this.value instanceof BABYLON.Vector3) {
  28762. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28763. }
  28764. else if (this.value instanceof BABYLON.Matrix) {
  28765. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28766. }
  28767. else if (this.value instanceof BABYLON.Quaternion) {
  28768. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28769. }
  28770. else {
  28771. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28772. return;
  28773. }
  28774. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28775. animation.setKeys(keys);
  28776. if (this.stopOtherAnimations) {
  28777. scene.stopAnimation(this._target);
  28778. }
  28779. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  28780. };
  28781. return InterpolateValueAction;
  28782. })(BABYLON.Action);
  28783. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28784. })(BABYLON || (BABYLON = {}));
  28785. var BABYLON;
  28786. (function (BABYLON) {
  28787. var SwitchBooleanAction = (function (_super) {
  28788. __extends(SwitchBooleanAction, _super);
  28789. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28790. _super.call(this, triggerOptions, condition);
  28791. this.propertyPath = propertyPath;
  28792. this._target = target;
  28793. }
  28794. SwitchBooleanAction.prototype._prepare = function () {
  28795. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28796. this._property = this._getProperty(this.propertyPath);
  28797. };
  28798. SwitchBooleanAction.prototype.execute = function () {
  28799. this._target[this._property] = !this._target[this._property];
  28800. };
  28801. return SwitchBooleanAction;
  28802. })(BABYLON.Action);
  28803. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28804. var SetStateAction = (function (_super) {
  28805. __extends(SetStateAction, _super);
  28806. function SetStateAction(triggerOptions, target, value, condition) {
  28807. _super.call(this, triggerOptions, condition);
  28808. this.value = value;
  28809. this._target = target;
  28810. }
  28811. SetStateAction.prototype.execute = function () {
  28812. this._target.state = this.value;
  28813. };
  28814. return SetStateAction;
  28815. })(BABYLON.Action);
  28816. BABYLON.SetStateAction = SetStateAction;
  28817. var SetValueAction = (function (_super) {
  28818. __extends(SetValueAction, _super);
  28819. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28820. _super.call(this, triggerOptions, condition);
  28821. this.propertyPath = propertyPath;
  28822. this.value = value;
  28823. this._target = target;
  28824. }
  28825. SetValueAction.prototype._prepare = function () {
  28826. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28827. this._property = this._getProperty(this.propertyPath);
  28828. };
  28829. SetValueAction.prototype.execute = function () {
  28830. this._target[this._property] = this.value;
  28831. };
  28832. return SetValueAction;
  28833. })(BABYLON.Action);
  28834. BABYLON.SetValueAction = SetValueAction;
  28835. var IncrementValueAction = (function (_super) {
  28836. __extends(IncrementValueAction, _super);
  28837. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28838. _super.call(this, triggerOptions, condition);
  28839. this.propertyPath = propertyPath;
  28840. this.value = value;
  28841. this._target = target;
  28842. }
  28843. IncrementValueAction.prototype._prepare = function () {
  28844. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28845. this._property = this._getProperty(this.propertyPath);
  28846. if (typeof this._target[this._property] !== "number") {
  28847. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28848. }
  28849. };
  28850. IncrementValueAction.prototype.execute = function () {
  28851. this._target[this._property] += this.value;
  28852. };
  28853. return IncrementValueAction;
  28854. })(BABYLON.Action);
  28855. BABYLON.IncrementValueAction = IncrementValueAction;
  28856. var PlayAnimationAction = (function (_super) {
  28857. __extends(PlayAnimationAction, _super);
  28858. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28859. _super.call(this, triggerOptions, condition);
  28860. this.from = from;
  28861. this.to = to;
  28862. this.loop = loop;
  28863. this._target = target;
  28864. }
  28865. PlayAnimationAction.prototype._prepare = function () {
  28866. };
  28867. PlayAnimationAction.prototype.execute = function () {
  28868. var scene = this._actionManager.getScene();
  28869. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28870. };
  28871. return PlayAnimationAction;
  28872. })(BABYLON.Action);
  28873. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28874. var StopAnimationAction = (function (_super) {
  28875. __extends(StopAnimationAction, _super);
  28876. function StopAnimationAction(triggerOptions, target, condition) {
  28877. _super.call(this, triggerOptions, condition);
  28878. this._target = target;
  28879. }
  28880. StopAnimationAction.prototype._prepare = function () {
  28881. };
  28882. StopAnimationAction.prototype.execute = function () {
  28883. var scene = this._actionManager.getScene();
  28884. scene.stopAnimation(this._target);
  28885. };
  28886. return StopAnimationAction;
  28887. })(BABYLON.Action);
  28888. BABYLON.StopAnimationAction = StopAnimationAction;
  28889. var DoNothingAction = (function (_super) {
  28890. __extends(DoNothingAction, _super);
  28891. function DoNothingAction(triggerOptions, condition) {
  28892. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28893. _super.call(this, triggerOptions, condition);
  28894. }
  28895. DoNothingAction.prototype.execute = function () {
  28896. };
  28897. return DoNothingAction;
  28898. })(BABYLON.Action);
  28899. BABYLON.DoNothingAction = DoNothingAction;
  28900. var CombineAction = (function (_super) {
  28901. __extends(CombineAction, _super);
  28902. function CombineAction(triggerOptions, children, condition) {
  28903. _super.call(this, triggerOptions, condition);
  28904. this.children = children;
  28905. }
  28906. CombineAction.prototype._prepare = function () {
  28907. for (var index = 0; index < this.children.length; index++) {
  28908. this.children[index]._actionManager = this._actionManager;
  28909. this.children[index]._prepare();
  28910. }
  28911. };
  28912. CombineAction.prototype.execute = function (evt) {
  28913. for (var index = 0; index < this.children.length; index++) {
  28914. this.children[index].execute(evt);
  28915. }
  28916. };
  28917. return CombineAction;
  28918. })(BABYLON.Action);
  28919. BABYLON.CombineAction = CombineAction;
  28920. var ExecuteCodeAction = (function (_super) {
  28921. __extends(ExecuteCodeAction, _super);
  28922. function ExecuteCodeAction(triggerOptions, func, condition) {
  28923. _super.call(this, triggerOptions, condition);
  28924. this.func = func;
  28925. }
  28926. ExecuteCodeAction.prototype.execute = function (evt) {
  28927. this.func(evt);
  28928. };
  28929. return ExecuteCodeAction;
  28930. })(BABYLON.Action);
  28931. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28932. var SetParentAction = (function (_super) {
  28933. __extends(SetParentAction, _super);
  28934. function SetParentAction(triggerOptions, target, parent, condition) {
  28935. _super.call(this, triggerOptions, condition);
  28936. this._target = target;
  28937. this._parent = parent;
  28938. }
  28939. SetParentAction.prototype._prepare = function () {
  28940. };
  28941. SetParentAction.prototype.execute = function () {
  28942. if (this._target.parent === this._parent) {
  28943. return;
  28944. }
  28945. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28946. invertParentWorldMatrix.invert();
  28947. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28948. this._target.parent = this._parent;
  28949. };
  28950. return SetParentAction;
  28951. })(BABYLON.Action);
  28952. BABYLON.SetParentAction = SetParentAction;
  28953. var PlaySoundAction = (function (_super) {
  28954. __extends(PlaySoundAction, _super);
  28955. function PlaySoundAction(triggerOptions, sound, condition) {
  28956. _super.call(this, triggerOptions, condition);
  28957. this._sound = sound;
  28958. }
  28959. PlaySoundAction.prototype._prepare = function () {
  28960. };
  28961. PlaySoundAction.prototype.execute = function () {
  28962. if (this._sound !== undefined)
  28963. this._sound.play();
  28964. };
  28965. return PlaySoundAction;
  28966. })(BABYLON.Action);
  28967. BABYLON.PlaySoundAction = PlaySoundAction;
  28968. var StopSoundAction = (function (_super) {
  28969. __extends(StopSoundAction, _super);
  28970. function StopSoundAction(triggerOptions, sound, condition) {
  28971. _super.call(this, triggerOptions, condition);
  28972. this._sound = sound;
  28973. }
  28974. StopSoundAction.prototype._prepare = function () {
  28975. };
  28976. StopSoundAction.prototype.execute = function () {
  28977. if (this._sound !== undefined)
  28978. this._sound.stop();
  28979. };
  28980. return StopSoundAction;
  28981. })(BABYLON.Action);
  28982. BABYLON.StopSoundAction = StopSoundAction;
  28983. })(BABYLON || (BABYLON = {}));
  28984. var BABYLON;
  28985. (function (BABYLON) {
  28986. var Geometry = (function () {
  28987. function Geometry(id, scene, vertexData, updatable, mesh) {
  28988. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28989. this._totalVertices = 0;
  28990. this._indices = [];
  28991. this._isDisposed = false;
  28992. this.id = id;
  28993. this._engine = scene.getEngine();
  28994. this._meshes = [];
  28995. this._scene = scene;
  28996. // vertexData
  28997. if (vertexData) {
  28998. this.setAllVerticesData(vertexData, updatable);
  28999. }
  29000. else {
  29001. this._totalVertices = 0;
  29002. this._indices = [];
  29003. }
  29004. // applyToMesh
  29005. if (mesh) {
  29006. this.applyToMesh(mesh);
  29007. mesh.computeWorldMatrix(true);
  29008. }
  29009. }
  29010. Geometry.prototype.getScene = function () {
  29011. return this._scene;
  29012. };
  29013. Geometry.prototype.getEngine = function () {
  29014. return this._engine;
  29015. };
  29016. Geometry.prototype.isReady = function () {
  29017. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29018. };
  29019. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29020. vertexData.applyToGeometry(this, updatable);
  29021. this.notifyUpdate();
  29022. };
  29023. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29024. this._vertexBuffers = this._vertexBuffers || {};
  29025. if (this._vertexBuffers[kind]) {
  29026. this._vertexBuffers[kind].dispose();
  29027. }
  29028. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29029. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29030. stride = this._vertexBuffers[kind].getStrideSize();
  29031. this._totalVertices = data.length / stride;
  29032. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29033. var meshes = this._meshes;
  29034. var numOfMeshes = meshes.length;
  29035. for (var index = 0; index < numOfMeshes; index++) {
  29036. var mesh = meshes[index];
  29037. mesh._resetPointsArrayCache();
  29038. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29039. mesh._createGlobalSubMesh();
  29040. mesh.computeWorldMatrix(true);
  29041. }
  29042. }
  29043. this.notifyUpdate(kind);
  29044. };
  29045. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29046. var vertexBuffer = this.getVertexBuffer(kind);
  29047. if (!vertexBuffer) {
  29048. return;
  29049. }
  29050. vertexBuffer.updateDirectly(data, offset);
  29051. this.notifyUpdate(kind);
  29052. };
  29053. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29054. var vertexBuffer = this.getVertexBuffer(kind);
  29055. if (!vertexBuffer) {
  29056. return;
  29057. }
  29058. vertexBuffer.update(data);
  29059. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29060. var extend;
  29061. var stride = vertexBuffer.getStrideSize();
  29062. this._totalVertices = data.length / stride;
  29063. if (updateExtends) {
  29064. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29065. }
  29066. var meshes = this._meshes;
  29067. var numOfMeshes = meshes.length;
  29068. for (var index = 0; index < numOfMeshes; index++) {
  29069. var mesh = meshes[index];
  29070. mesh._resetPointsArrayCache();
  29071. if (updateExtends) {
  29072. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29073. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29074. var subMesh = mesh.subMeshes[subIndex];
  29075. subMesh.refreshBoundingInfo();
  29076. }
  29077. }
  29078. }
  29079. }
  29080. this.notifyUpdate(kind);
  29081. };
  29082. Geometry.prototype.getTotalVertices = function () {
  29083. if (!this.isReady()) {
  29084. return 0;
  29085. }
  29086. return this._totalVertices;
  29087. };
  29088. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  29089. var vertexBuffer = this.getVertexBuffer(kind);
  29090. if (!vertexBuffer) {
  29091. return null;
  29092. }
  29093. var orig = vertexBuffer.getData();
  29094. if (!copyWhenShared || this._meshes.length === 1) {
  29095. return orig;
  29096. }
  29097. else {
  29098. var len = orig.length;
  29099. var copy = [];
  29100. for (var i = 0; i < len; i++) {
  29101. copy.push(orig[i]);
  29102. }
  29103. return copy;
  29104. }
  29105. };
  29106. Geometry.prototype.getVertexBuffer = function (kind) {
  29107. if (!this.isReady()) {
  29108. return null;
  29109. }
  29110. return this._vertexBuffers[kind];
  29111. };
  29112. Geometry.prototype.getVertexBuffers = function () {
  29113. if (!this.isReady()) {
  29114. return null;
  29115. }
  29116. return this._vertexBuffers;
  29117. };
  29118. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29119. if (!this._vertexBuffers) {
  29120. if (this._delayInfo) {
  29121. return this._delayInfo.indexOf(kind) !== -1;
  29122. }
  29123. return false;
  29124. }
  29125. return this._vertexBuffers[kind] !== undefined;
  29126. };
  29127. Geometry.prototype.getVerticesDataKinds = function () {
  29128. var result = [];
  29129. if (!this._vertexBuffers && this._delayInfo) {
  29130. for (var kind in this._delayInfo) {
  29131. result.push(kind);
  29132. }
  29133. }
  29134. else {
  29135. for (kind in this._vertexBuffers) {
  29136. result.push(kind);
  29137. }
  29138. }
  29139. return result;
  29140. };
  29141. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29142. if (this._indexBuffer) {
  29143. this._engine._releaseBuffer(this._indexBuffer);
  29144. }
  29145. this._indices = indices;
  29146. if (this._meshes.length !== 0 && this._indices) {
  29147. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29148. }
  29149. if (totalVertices !== undefined) {
  29150. this._totalVertices = totalVertices;
  29151. }
  29152. var meshes = this._meshes;
  29153. var numOfMeshes = meshes.length;
  29154. for (var index = 0; index < numOfMeshes; index++) {
  29155. meshes[index]._createGlobalSubMesh();
  29156. }
  29157. this.notifyUpdate();
  29158. };
  29159. Geometry.prototype.getTotalIndices = function () {
  29160. if (!this.isReady()) {
  29161. return 0;
  29162. }
  29163. return this._indices.length;
  29164. };
  29165. Geometry.prototype.getIndices = function (copyWhenShared) {
  29166. if (!this.isReady()) {
  29167. return null;
  29168. }
  29169. var orig = this._indices;
  29170. if (!copyWhenShared || this._meshes.length === 1) {
  29171. return orig;
  29172. }
  29173. else {
  29174. var len = orig.length;
  29175. var copy = [];
  29176. for (var i = 0; i < len; i++) {
  29177. copy.push(orig[i]);
  29178. }
  29179. return copy;
  29180. }
  29181. };
  29182. Geometry.prototype.getIndexBuffer = function () {
  29183. if (!this.isReady()) {
  29184. return null;
  29185. }
  29186. return this._indexBuffer;
  29187. };
  29188. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29189. var meshes = this._meshes;
  29190. var index = meshes.indexOf(mesh);
  29191. if (index === -1) {
  29192. return;
  29193. }
  29194. for (var kind in this._vertexBuffers) {
  29195. this._vertexBuffers[kind].dispose();
  29196. }
  29197. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  29198. this._indexBuffer = null;
  29199. }
  29200. meshes.splice(index, 1);
  29201. mesh._geometry = null;
  29202. if (meshes.length === 0 && shouldDispose) {
  29203. this.dispose();
  29204. }
  29205. };
  29206. Geometry.prototype.applyToMesh = function (mesh) {
  29207. if (mesh._geometry === this) {
  29208. return;
  29209. }
  29210. var previousGeometry = mesh._geometry;
  29211. if (previousGeometry) {
  29212. previousGeometry.releaseForMesh(mesh);
  29213. }
  29214. var meshes = this._meshes;
  29215. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29216. mesh._geometry = this;
  29217. this._scene.pushGeometry(this);
  29218. meshes.push(mesh);
  29219. if (this.isReady()) {
  29220. this._applyToMesh(mesh);
  29221. }
  29222. else {
  29223. mesh._boundingInfo = this._boundingInfo;
  29224. }
  29225. };
  29226. Geometry.prototype._applyToMesh = function (mesh) {
  29227. var numOfMeshes = this._meshes.length;
  29228. // vertexBuffers
  29229. for (var kind in this._vertexBuffers) {
  29230. if (numOfMeshes === 1) {
  29231. this._vertexBuffers[kind].create();
  29232. }
  29233. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  29234. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29235. mesh._resetPointsArrayCache();
  29236. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  29237. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29238. mesh._createGlobalSubMesh();
  29239. //bounding info was just created again, world matrix should be applied again.
  29240. mesh._updateBoundingInfo();
  29241. }
  29242. }
  29243. // indexBuffer
  29244. if (numOfMeshes === 1 && this._indices) {
  29245. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29246. }
  29247. if (this._indexBuffer) {
  29248. this._indexBuffer.references = numOfMeshes;
  29249. }
  29250. };
  29251. Geometry.prototype.notifyUpdate = function (kind) {
  29252. if (this.onGeometryUpdated) {
  29253. this.onGeometryUpdated(this, kind);
  29254. }
  29255. };
  29256. Geometry.prototype.load = function (scene, onLoaded) {
  29257. var _this = this;
  29258. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29259. return;
  29260. }
  29261. if (this.isReady()) {
  29262. if (onLoaded) {
  29263. onLoaded();
  29264. }
  29265. return;
  29266. }
  29267. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29268. scene._addPendingData(this);
  29269. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29270. _this._delayLoadingFunction(JSON.parse(data), _this);
  29271. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29272. _this._delayInfo = [];
  29273. scene._removePendingData(_this);
  29274. var meshes = _this._meshes;
  29275. var numOfMeshes = meshes.length;
  29276. for (var index = 0; index < numOfMeshes; index++) {
  29277. _this._applyToMesh(meshes[index]);
  29278. }
  29279. if (onLoaded) {
  29280. onLoaded();
  29281. }
  29282. }, function () { }, scene.database);
  29283. };
  29284. Geometry.prototype.isDisposed = function () {
  29285. return this._isDisposed;
  29286. };
  29287. Geometry.prototype.dispose = function () {
  29288. var meshes = this._meshes;
  29289. var numOfMeshes = meshes.length;
  29290. var index;
  29291. for (index = 0; index < numOfMeshes; index++) {
  29292. this.releaseForMesh(meshes[index]);
  29293. }
  29294. this._meshes = [];
  29295. for (var kind in this._vertexBuffers) {
  29296. this._vertexBuffers[kind].dispose();
  29297. }
  29298. this._vertexBuffers = [];
  29299. this._totalVertices = 0;
  29300. if (this._indexBuffer) {
  29301. this._engine._releaseBuffer(this._indexBuffer);
  29302. }
  29303. this._indexBuffer = null;
  29304. this._indices = [];
  29305. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29306. this.delayLoadingFile = null;
  29307. this._delayLoadingFunction = null;
  29308. this._delayInfo = [];
  29309. this._boundingInfo = null; // todo: .dispose()
  29310. this._scene.removeGeometry(this);
  29311. this._isDisposed = true;
  29312. };
  29313. Geometry.prototype.copy = function (id) {
  29314. var vertexData = new BABYLON.VertexData();
  29315. vertexData.indices = [];
  29316. var indices = this.getIndices();
  29317. for (var index = 0; index < indices.length; index++) {
  29318. vertexData.indices.push(indices[index]);
  29319. }
  29320. var updatable = false;
  29321. var stopChecking = false;
  29322. var kind;
  29323. for (kind in this._vertexBuffers) {
  29324. // using slice() to make a copy of the array and not just reference it
  29325. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  29326. if (!stopChecking) {
  29327. updatable = this.getVertexBuffer(kind).isUpdatable();
  29328. stopChecking = !updatable;
  29329. }
  29330. }
  29331. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29332. geometry.delayLoadState = this.delayLoadState;
  29333. geometry.delayLoadingFile = this.delayLoadingFile;
  29334. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29335. for (kind in this._delayInfo) {
  29336. geometry._delayInfo = geometry._delayInfo || [];
  29337. geometry._delayInfo.push(kind);
  29338. }
  29339. // Bounding info
  29340. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  29341. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29342. return geometry;
  29343. };
  29344. // Statics
  29345. Geometry.ExtractFromMesh = function (mesh, id) {
  29346. var geometry = mesh._geometry;
  29347. if (!geometry) {
  29348. return null;
  29349. }
  29350. return geometry.copy(id);
  29351. };
  29352. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29353. // be aware Math.random() could cause collisions
  29354. Geometry.RandomId = function () {
  29355. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  29356. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  29357. return v.toString(16);
  29358. });
  29359. };
  29360. return Geometry;
  29361. })();
  29362. BABYLON.Geometry = Geometry;
  29363. /////// Primitives //////////////////////////////////////////////
  29364. var Geometry;
  29365. (function (Geometry) {
  29366. var Primitives;
  29367. (function (Primitives) {
  29368. /// Abstract class
  29369. var _Primitive = (function (_super) {
  29370. __extends(_Primitive, _super);
  29371. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  29372. this._beingRegenerated = true;
  29373. this._canBeRegenerated = canBeRegenerated;
  29374. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  29375. this._beingRegenerated = false;
  29376. }
  29377. _Primitive.prototype.canBeRegenerated = function () {
  29378. return this._canBeRegenerated;
  29379. };
  29380. _Primitive.prototype.regenerate = function () {
  29381. if (!this._canBeRegenerated) {
  29382. return;
  29383. }
  29384. this._beingRegenerated = true;
  29385. this.setAllVerticesData(this._regenerateVertexData(), false);
  29386. this._beingRegenerated = false;
  29387. };
  29388. _Primitive.prototype.asNewGeometry = function (id) {
  29389. return _super.prototype.copy.call(this, id);
  29390. };
  29391. // overrides
  29392. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29393. if (!this._beingRegenerated) {
  29394. return;
  29395. }
  29396. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29397. };
  29398. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29399. if (!this._beingRegenerated) {
  29400. return;
  29401. }
  29402. _super.prototype.setVerticesData.call(this, kind, data, false);
  29403. };
  29404. // to override
  29405. // protected
  29406. _Primitive.prototype._regenerateVertexData = function () {
  29407. throw new Error("Abstract method");
  29408. };
  29409. _Primitive.prototype.copy = function (id) {
  29410. throw new Error("Must be overriden in sub-classes.");
  29411. };
  29412. return _Primitive;
  29413. })(Geometry);
  29414. Primitives._Primitive = _Primitive;
  29415. var Ribbon = (function (_super) {
  29416. __extends(Ribbon, _super);
  29417. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29418. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29419. this.pathArray = pathArray;
  29420. this.closeArray = closeArray;
  29421. this.closePath = closePath;
  29422. this.offset = offset;
  29423. this.side = side;
  29424. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29425. }
  29426. Ribbon.prototype._regenerateVertexData = function () {
  29427. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29428. };
  29429. Ribbon.prototype.copy = function (id) {
  29430. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29431. };
  29432. return Ribbon;
  29433. })(_Primitive);
  29434. Primitives.Ribbon = Ribbon;
  29435. var Box = (function (_super) {
  29436. __extends(Box, _super);
  29437. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29438. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29439. this.size = size;
  29440. this.side = side;
  29441. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29442. }
  29443. Box.prototype._regenerateVertexData = function () {
  29444. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29445. };
  29446. Box.prototype.copy = function (id) {
  29447. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29448. };
  29449. return Box;
  29450. })(_Primitive);
  29451. Primitives.Box = Box;
  29452. var Sphere = (function (_super) {
  29453. __extends(Sphere, _super);
  29454. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29455. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29456. this.segments = segments;
  29457. this.diameter = diameter;
  29458. this.side = side;
  29459. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29460. }
  29461. Sphere.prototype._regenerateVertexData = function () {
  29462. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29463. };
  29464. Sphere.prototype.copy = function (id) {
  29465. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29466. };
  29467. return Sphere;
  29468. })(_Primitive);
  29469. Primitives.Sphere = Sphere;
  29470. var Disc = (function (_super) {
  29471. __extends(Disc, _super);
  29472. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29473. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29474. this.radius = radius;
  29475. this.tessellation = tessellation;
  29476. this.side = side;
  29477. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29478. }
  29479. Disc.prototype._regenerateVertexData = function () {
  29480. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29481. };
  29482. Disc.prototype.copy = function (id) {
  29483. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29484. };
  29485. return Disc;
  29486. })(_Primitive);
  29487. Primitives.Disc = Disc;
  29488. var Cylinder = (function (_super) {
  29489. __extends(Cylinder, _super);
  29490. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29491. if (subdivisions === void 0) { subdivisions = 1; }
  29492. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29493. this.height = height;
  29494. this.diameterTop = diameterTop;
  29495. this.diameterBottom = diameterBottom;
  29496. this.tessellation = tessellation;
  29497. this.subdivisions = subdivisions;
  29498. this.side = side;
  29499. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29500. }
  29501. Cylinder.prototype._regenerateVertexData = function () {
  29502. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29503. };
  29504. Cylinder.prototype.copy = function (id) {
  29505. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29506. };
  29507. return Cylinder;
  29508. })(_Primitive);
  29509. Primitives.Cylinder = Cylinder;
  29510. var Torus = (function (_super) {
  29511. __extends(Torus, _super);
  29512. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29513. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29514. this.diameter = diameter;
  29515. this.thickness = thickness;
  29516. this.tessellation = tessellation;
  29517. this.side = side;
  29518. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29519. }
  29520. Torus.prototype._regenerateVertexData = function () {
  29521. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29522. };
  29523. Torus.prototype.copy = function (id) {
  29524. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29525. };
  29526. return Torus;
  29527. })(_Primitive);
  29528. Primitives.Torus = Torus;
  29529. var Ground = (function (_super) {
  29530. __extends(Ground, _super);
  29531. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29532. this.width = width;
  29533. this.height = height;
  29534. this.subdivisions = subdivisions;
  29535. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29536. }
  29537. Ground.prototype._regenerateVertexData = function () {
  29538. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29539. };
  29540. Ground.prototype.copy = function (id) {
  29541. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29542. };
  29543. return Ground;
  29544. })(_Primitive);
  29545. Primitives.Ground = Ground;
  29546. var TiledGround = (function (_super) {
  29547. __extends(TiledGround, _super);
  29548. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29549. this.xmin = xmin;
  29550. this.zmin = zmin;
  29551. this.xmax = xmax;
  29552. this.zmax = zmax;
  29553. this.subdivisions = subdivisions;
  29554. this.precision = precision;
  29555. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29556. }
  29557. TiledGround.prototype._regenerateVertexData = function () {
  29558. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29559. };
  29560. TiledGround.prototype.copy = function (id) {
  29561. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29562. };
  29563. return TiledGround;
  29564. })(_Primitive);
  29565. Primitives.TiledGround = TiledGround;
  29566. var Plane = (function (_super) {
  29567. __extends(Plane, _super);
  29568. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29569. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29570. this.size = size;
  29571. this.side = side;
  29572. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29573. }
  29574. Plane.prototype._regenerateVertexData = function () {
  29575. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29576. };
  29577. Plane.prototype.copy = function (id) {
  29578. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29579. };
  29580. return Plane;
  29581. })(_Primitive);
  29582. Primitives.Plane = Plane;
  29583. var TorusKnot = (function (_super) {
  29584. __extends(TorusKnot, _super);
  29585. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29586. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29587. this.radius = radius;
  29588. this.tube = tube;
  29589. this.radialSegments = radialSegments;
  29590. this.tubularSegments = tubularSegments;
  29591. this.p = p;
  29592. this.q = q;
  29593. this.side = side;
  29594. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29595. }
  29596. TorusKnot.prototype._regenerateVertexData = function () {
  29597. 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 });
  29598. };
  29599. TorusKnot.prototype.copy = function (id) {
  29600. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29601. };
  29602. return TorusKnot;
  29603. })(_Primitive);
  29604. Primitives.TorusKnot = TorusKnot;
  29605. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29606. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29607. })(BABYLON || (BABYLON = {}));
  29608. var BABYLON;
  29609. (function (BABYLON) {
  29610. var GroundMesh = (function (_super) {
  29611. __extends(GroundMesh, _super);
  29612. function GroundMesh(name, scene) {
  29613. _super.call(this, name, scene);
  29614. this.generateOctree = false;
  29615. this._worldInverse = new BABYLON.Matrix();
  29616. }
  29617. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29618. get: function () {
  29619. return this._subdivisions;
  29620. },
  29621. enumerable: true,
  29622. configurable: true
  29623. });
  29624. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29625. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29626. this._subdivisions = chunksCount;
  29627. this.subdivide(this._subdivisions);
  29628. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29629. };
  29630. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29631. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29632. this.getWorldMatrix().invertToRef(this._worldInverse);
  29633. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29634. var pickInfo = this.intersects(ray);
  29635. if (pickInfo.hit) {
  29636. return pickInfo.pickedPoint.y;
  29637. }
  29638. return 0;
  29639. };
  29640. return GroundMesh;
  29641. })(BABYLON.Mesh);
  29642. BABYLON.GroundMesh = GroundMesh;
  29643. })(BABYLON || (BABYLON = {}));
  29644. var BABYLON;
  29645. (function (BABYLON) {
  29646. var LinesMesh = (function (_super) {
  29647. __extends(LinesMesh, _super);
  29648. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29649. if (parent === void 0) { parent = null; }
  29650. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29651. this.color = new BABYLON.Color3(1, 1, 1);
  29652. this.alpha = 1;
  29653. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29654. attributes: ["position"],
  29655. uniforms: ["worldViewProjection", "color"],
  29656. needAlphaBlending: true
  29657. });
  29658. }
  29659. Object.defineProperty(LinesMesh.prototype, "material", {
  29660. get: function () {
  29661. return this._colorShader;
  29662. },
  29663. enumerable: true,
  29664. configurable: true
  29665. });
  29666. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29667. get: function () {
  29668. return false;
  29669. },
  29670. enumerable: true,
  29671. configurable: true
  29672. });
  29673. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29674. get: function () {
  29675. return false;
  29676. },
  29677. enumerable: true,
  29678. configurable: true
  29679. });
  29680. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29681. var engine = this.getScene().getEngine();
  29682. var indexToBind = this._geometry.getIndexBuffer();
  29683. // VBOs
  29684. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29685. // Color
  29686. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29687. };
  29688. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29689. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29690. return;
  29691. }
  29692. var engine = this.getScene().getEngine();
  29693. // Draw order
  29694. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29695. };
  29696. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29697. return null;
  29698. };
  29699. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29700. this._colorShader.dispose();
  29701. _super.prototype.dispose.call(this, doNotRecurse);
  29702. };
  29703. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29704. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29705. };
  29706. return LinesMesh;
  29707. })(BABYLON.Mesh);
  29708. BABYLON.LinesMesh = LinesMesh;
  29709. })(BABYLON || (BABYLON = {}));
  29710. var BABYLON;
  29711. (function (BABYLON) {
  29712. var OutlineRenderer = (function () {
  29713. function OutlineRenderer(scene) {
  29714. this._scene = scene;
  29715. }
  29716. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29717. var _this = this;
  29718. if (useOverlay === void 0) { useOverlay = false; }
  29719. var scene = this._scene;
  29720. var engine = this._scene.getEngine();
  29721. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29722. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29723. return;
  29724. }
  29725. var mesh = subMesh.getRenderingMesh();
  29726. var material = subMesh.getMaterial();
  29727. engine.enableEffect(this._effect);
  29728. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29729. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29730. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29731. // Bones
  29732. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29733. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29734. }
  29735. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29736. // Alpha test
  29737. if (material && material.needAlphaTesting()) {
  29738. var alphaTexture = material.getAlphaTestTexture();
  29739. this._effect.setTexture("diffuseSampler", alphaTexture);
  29740. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29741. }
  29742. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29743. };
  29744. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29745. var defines = [];
  29746. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29747. var mesh = subMesh.getMesh();
  29748. var material = subMesh.getMaterial();
  29749. // Alpha test
  29750. if (material && material.needAlphaTesting()) {
  29751. defines.push("#define ALPHATEST");
  29752. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29753. attribs.push(BABYLON.VertexBuffer.UVKind);
  29754. defines.push("#define UV1");
  29755. }
  29756. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29757. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29758. defines.push("#define UV2");
  29759. }
  29760. }
  29761. // Bones
  29762. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29763. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29764. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29765. defines.push("#define BONES");
  29766. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29767. }
  29768. // Instances
  29769. if (useInstances) {
  29770. defines.push("#define INSTANCES");
  29771. attribs.push("world0");
  29772. attribs.push("world1");
  29773. attribs.push("world2");
  29774. attribs.push("world3");
  29775. }
  29776. // Get correct effect
  29777. var join = defines.join("\n");
  29778. if (this._cachedDefines !== join) {
  29779. this._cachedDefines = join;
  29780. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29781. }
  29782. return this._effect.isReady();
  29783. };
  29784. return OutlineRenderer;
  29785. })();
  29786. BABYLON.OutlineRenderer = OutlineRenderer;
  29787. })(BABYLON || (BABYLON = {}));
  29788. var BABYLON;
  29789. (function (BABYLON) {
  29790. var MeshAssetTask = (function () {
  29791. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29792. this.name = name;
  29793. this.meshesNames = meshesNames;
  29794. this.rootUrl = rootUrl;
  29795. this.sceneFilename = sceneFilename;
  29796. this.isCompleted = false;
  29797. }
  29798. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29799. var _this = this;
  29800. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29801. _this.loadedMeshes = meshes;
  29802. _this.loadedParticleSystems = particleSystems;
  29803. _this.loadedSkeletons = skeletons;
  29804. _this.isCompleted = true;
  29805. if (_this.onSuccess) {
  29806. _this.onSuccess(_this);
  29807. }
  29808. onSuccess();
  29809. }, null, function () {
  29810. if (_this.onError) {
  29811. _this.onError(_this);
  29812. }
  29813. onError();
  29814. });
  29815. };
  29816. return MeshAssetTask;
  29817. })();
  29818. BABYLON.MeshAssetTask = MeshAssetTask;
  29819. var TextFileAssetTask = (function () {
  29820. function TextFileAssetTask(name, url) {
  29821. this.name = name;
  29822. this.url = url;
  29823. this.isCompleted = false;
  29824. }
  29825. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29826. var _this = this;
  29827. BABYLON.Tools.LoadFile(this.url, function (data) {
  29828. _this.text = data;
  29829. _this.isCompleted = true;
  29830. if (_this.onSuccess) {
  29831. _this.onSuccess(_this);
  29832. }
  29833. onSuccess();
  29834. }, null, scene.database, false, function () {
  29835. if (_this.onError) {
  29836. _this.onError(_this);
  29837. }
  29838. onError();
  29839. });
  29840. };
  29841. return TextFileAssetTask;
  29842. })();
  29843. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29844. var BinaryFileAssetTask = (function () {
  29845. function BinaryFileAssetTask(name, url) {
  29846. this.name = name;
  29847. this.url = url;
  29848. this.isCompleted = false;
  29849. }
  29850. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29851. var _this = this;
  29852. BABYLON.Tools.LoadFile(this.url, function (data) {
  29853. _this.data = data;
  29854. _this.isCompleted = true;
  29855. if (_this.onSuccess) {
  29856. _this.onSuccess(_this);
  29857. }
  29858. onSuccess();
  29859. }, null, scene.database, true, function () {
  29860. if (_this.onError) {
  29861. _this.onError(_this);
  29862. }
  29863. onError();
  29864. });
  29865. };
  29866. return BinaryFileAssetTask;
  29867. })();
  29868. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29869. var ImageAssetTask = (function () {
  29870. function ImageAssetTask(name, url) {
  29871. this.name = name;
  29872. this.url = url;
  29873. this.isCompleted = false;
  29874. }
  29875. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29876. var _this = this;
  29877. var img = new Image();
  29878. img.onload = function () {
  29879. _this.image = img;
  29880. _this.isCompleted = true;
  29881. if (_this.onSuccess) {
  29882. _this.onSuccess(_this);
  29883. }
  29884. onSuccess();
  29885. };
  29886. img.onerror = function () {
  29887. if (_this.onError) {
  29888. _this.onError(_this);
  29889. }
  29890. onError();
  29891. };
  29892. img.src = this.url;
  29893. };
  29894. return ImageAssetTask;
  29895. })();
  29896. BABYLON.ImageAssetTask = ImageAssetTask;
  29897. var TextureAssetTask = (function () {
  29898. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29899. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29900. this.name = name;
  29901. this.url = url;
  29902. this.noMipmap = noMipmap;
  29903. this.invertY = invertY;
  29904. this.samplingMode = samplingMode;
  29905. this.isCompleted = false;
  29906. }
  29907. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29908. var _this = this;
  29909. var onload = function () {
  29910. _this.isCompleted = true;
  29911. if (_this.onSuccess) {
  29912. _this.onSuccess(_this);
  29913. }
  29914. onSuccess();
  29915. };
  29916. var onerror = function () {
  29917. if (_this.onError) {
  29918. _this.onError(_this);
  29919. }
  29920. onError();
  29921. };
  29922. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29923. };
  29924. return TextureAssetTask;
  29925. })();
  29926. BABYLON.TextureAssetTask = TextureAssetTask;
  29927. var AssetsManager = (function () {
  29928. function AssetsManager(scene) {
  29929. this._tasks = new Array();
  29930. this._waitingTasksCount = 0;
  29931. this.useDefaultLoadingScreen = true;
  29932. this._scene = scene;
  29933. }
  29934. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29935. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29936. this._tasks.push(task);
  29937. return task;
  29938. };
  29939. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29940. var task = new TextFileAssetTask(taskName, url);
  29941. this._tasks.push(task);
  29942. return task;
  29943. };
  29944. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29945. var task = new BinaryFileAssetTask(taskName, url);
  29946. this._tasks.push(task);
  29947. return task;
  29948. };
  29949. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29950. var task = new ImageAssetTask(taskName, url);
  29951. this._tasks.push(task);
  29952. return task;
  29953. };
  29954. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29955. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29956. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29957. this._tasks.push(task);
  29958. return task;
  29959. };
  29960. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29961. this._waitingTasksCount--;
  29962. if (this._waitingTasksCount === 0) {
  29963. if (this.onFinish) {
  29964. this.onFinish(this._tasks);
  29965. }
  29966. this._scene.getEngine().hideLoadingUI();
  29967. }
  29968. };
  29969. AssetsManager.prototype._runTask = function (task) {
  29970. var _this = this;
  29971. task.run(this._scene, function () {
  29972. if (_this.onTaskSuccess) {
  29973. _this.onTaskSuccess(task);
  29974. }
  29975. _this._decreaseWaitingTasksCount();
  29976. }, function () {
  29977. if (_this.onTaskError) {
  29978. _this.onTaskError(task);
  29979. }
  29980. _this._decreaseWaitingTasksCount();
  29981. });
  29982. };
  29983. AssetsManager.prototype.reset = function () {
  29984. this._tasks = new Array();
  29985. return this;
  29986. };
  29987. AssetsManager.prototype.load = function () {
  29988. this._waitingTasksCount = this._tasks.length;
  29989. if (this._waitingTasksCount === 0) {
  29990. if (this.onFinish) {
  29991. this.onFinish(this._tasks);
  29992. }
  29993. return this;
  29994. }
  29995. if (this.useDefaultLoadingScreen) {
  29996. this._scene.getEngine().displayLoadingUI();
  29997. }
  29998. for (var index = 0; index < this._tasks.length; index++) {
  29999. var task = this._tasks[index];
  30000. this._runTask(task);
  30001. }
  30002. return this;
  30003. };
  30004. return AssetsManager;
  30005. })();
  30006. BABYLON.AssetsManager = AssetsManager;
  30007. })(BABYLON || (BABYLON = {}));
  30008. var BABYLON;
  30009. (function (BABYLON) {
  30010. var VRDeviceOrientationFreeCamera = (function (_super) {
  30011. __extends(VRDeviceOrientationFreeCamera, _super);
  30012. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  30013. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  30014. _super.call(this, name, position, scene);
  30015. this._alpha = 0;
  30016. this._beta = 0;
  30017. this._gamma = 0;
  30018. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30019. metrics.compensateDistorsion = compensateDistorsion;
  30020. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30021. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  30022. }
  30023. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  30024. this._alpha = +evt.alpha | 0;
  30025. this._beta = +evt.beta | 0;
  30026. this._gamma = +evt.gamma | 0;
  30027. if (this._gamma < 0) {
  30028. this._gamma = 90 + this._gamma;
  30029. }
  30030. else {
  30031. // Incline it in the correct angle.
  30032. this._gamma = 270 - this._gamma;
  30033. }
  30034. this.rotation.x = this._gamma / 180.0 * Math.PI;
  30035. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  30036. this.rotation.z = this._beta / 180.0 * Math.PI;
  30037. };
  30038. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30039. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30040. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  30041. };
  30042. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  30043. _super.prototype.detachControl.call(this, element);
  30044. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  30045. };
  30046. return VRDeviceOrientationFreeCamera;
  30047. })(BABYLON.FreeCamera);
  30048. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  30049. })(BABYLON || (BABYLON = {}));
  30050. var BABYLON;
  30051. (function (BABYLON) {
  30052. var WebVRFreeCamera = (function (_super) {
  30053. __extends(WebVRFreeCamera, _super);
  30054. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  30055. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  30056. _super.call(this, name, position, scene);
  30057. this._hmdDevice = null;
  30058. this._sensorDevice = null;
  30059. this._cacheState = null;
  30060. this._cacheQuaternion = new BABYLON.Quaternion();
  30061. this._cacheRotation = BABYLON.Vector3.Zero();
  30062. this._vrEnabled = false;
  30063. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30064. metrics.compensateDistorsion = compensateDistorsion;
  30065. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30066. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  30067. }
  30068. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  30069. var size = devices.length;
  30070. var i = 0;
  30071. // Reset devices.
  30072. this._sensorDevice = null;
  30073. this._hmdDevice = null;
  30074. // Search for a HmdDevice.
  30075. while (i < size && this._hmdDevice === null) {
  30076. if (devices[i] instanceof HMDVRDevice) {
  30077. this._hmdDevice = devices[i];
  30078. }
  30079. i++;
  30080. }
  30081. i = 0;
  30082. while (i < size && this._sensorDevice === null) {
  30083. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  30084. this._sensorDevice = devices[i];
  30085. }
  30086. i++;
  30087. }
  30088. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  30089. };
  30090. WebVRFreeCamera.prototype._checkInputs = function () {
  30091. if (this._vrEnabled) {
  30092. this._cacheState = this._sensorDevice.getState();
  30093. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  30094. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  30095. this.rotation.x = -this._cacheRotation.z;
  30096. this.rotation.y = -this._cacheRotation.y;
  30097. this.rotation.z = this._cacheRotation.x;
  30098. }
  30099. _super.prototype._checkInputs.call(this);
  30100. };
  30101. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30102. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30103. if (navigator.getVRDevices) {
  30104. navigator.getVRDevices().then(this._getWebVRDevices);
  30105. }
  30106. else if (navigator.mozGetVRDevices) {
  30107. navigator.mozGetVRDevices(this._getWebVRDevices);
  30108. }
  30109. };
  30110. WebVRFreeCamera.prototype.detachControl = function (element) {
  30111. _super.prototype.detachControl.call(this, element);
  30112. this._vrEnabled = false;
  30113. };
  30114. return WebVRFreeCamera;
  30115. })(BABYLON.FreeCamera);
  30116. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  30117. })(BABYLON || (BABYLON = {}));
  30118. var BABYLON;
  30119. (function (BABYLON) {
  30120. // Standard optimizations
  30121. var SceneOptimization = (function () {
  30122. function SceneOptimization(priority) {
  30123. if (priority === void 0) { priority = 0; }
  30124. this.priority = priority;
  30125. this.apply = function (scene) {
  30126. return true; // Return true if everything that can be done was applied
  30127. };
  30128. }
  30129. return SceneOptimization;
  30130. })();
  30131. BABYLON.SceneOptimization = SceneOptimization;
  30132. var TextureOptimization = (function (_super) {
  30133. __extends(TextureOptimization, _super);
  30134. function TextureOptimization(priority, maximumSize) {
  30135. var _this = this;
  30136. if (priority === void 0) { priority = 0; }
  30137. if (maximumSize === void 0) { maximumSize = 1024; }
  30138. _super.call(this, priority);
  30139. this.priority = priority;
  30140. this.maximumSize = maximumSize;
  30141. this.apply = function (scene) {
  30142. var allDone = true;
  30143. for (var index = 0; index < scene.textures.length; index++) {
  30144. var texture = scene.textures[index];
  30145. if (!texture.canRescale) {
  30146. continue;
  30147. }
  30148. var currentSize = texture.getSize();
  30149. var maxDimension = Math.max(currentSize.width, currentSize.height);
  30150. if (maxDimension > _this.maximumSize) {
  30151. texture.scale(0.5);
  30152. allDone = false;
  30153. }
  30154. }
  30155. return allDone;
  30156. };
  30157. }
  30158. return TextureOptimization;
  30159. })(SceneOptimization);
  30160. BABYLON.TextureOptimization = TextureOptimization;
  30161. var HardwareScalingOptimization = (function (_super) {
  30162. __extends(HardwareScalingOptimization, _super);
  30163. function HardwareScalingOptimization(priority, maximumScale) {
  30164. var _this = this;
  30165. if (priority === void 0) { priority = 0; }
  30166. if (maximumScale === void 0) { maximumScale = 2; }
  30167. _super.call(this, priority);
  30168. this.priority = priority;
  30169. this.maximumScale = maximumScale;
  30170. this._currentScale = 1;
  30171. this.apply = function (scene) {
  30172. _this._currentScale++;
  30173. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  30174. return _this._currentScale >= _this.maximumScale;
  30175. };
  30176. }
  30177. return HardwareScalingOptimization;
  30178. })(SceneOptimization);
  30179. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  30180. var ShadowsOptimization = (function (_super) {
  30181. __extends(ShadowsOptimization, _super);
  30182. function ShadowsOptimization() {
  30183. _super.apply(this, arguments);
  30184. this.apply = function (scene) {
  30185. scene.shadowsEnabled = false;
  30186. return true;
  30187. };
  30188. }
  30189. return ShadowsOptimization;
  30190. })(SceneOptimization);
  30191. BABYLON.ShadowsOptimization = ShadowsOptimization;
  30192. var PostProcessesOptimization = (function (_super) {
  30193. __extends(PostProcessesOptimization, _super);
  30194. function PostProcessesOptimization() {
  30195. _super.apply(this, arguments);
  30196. this.apply = function (scene) {
  30197. scene.postProcessesEnabled = false;
  30198. return true;
  30199. };
  30200. }
  30201. return PostProcessesOptimization;
  30202. })(SceneOptimization);
  30203. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  30204. var LensFlaresOptimization = (function (_super) {
  30205. __extends(LensFlaresOptimization, _super);
  30206. function LensFlaresOptimization() {
  30207. _super.apply(this, arguments);
  30208. this.apply = function (scene) {
  30209. scene.lensFlaresEnabled = false;
  30210. return true;
  30211. };
  30212. }
  30213. return LensFlaresOptimization;
  30214. })(SceneOptimization);
  30215. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  30216. var ParticlesOptimization = (function (_super) {
  30217. __extends(ParticlesOptimization, _super);
  30218. function ParticlesOptimization() {
  30219. _super.apply(this, arguments);
  30220. this.apply = function (scene) {
  30221. scene.particlesEnabled = false;
  30222. return true;
  30223. };
  30224. }
  30225. return ParticlesOptimization;
  30226. })(SceneOptimization);
  30227. BABYLON.ParticlesOptimization = ParticlesOptimization;
  30228. var RenderTargetsOptimization = (function (_super) {
  30229. __extends(RenderTargetsOptimization, _super);
  30230. function RenderTargetsOptimization() {
  30231. _super.apply(this, arguments);
  30232. this.apply = function (scene) {
  30233. scene.renderTargetsEnabled = false;
  30234. return true;
  30235. };
  30236. }
  30237. return RenderTargetsOptimization;
  30238. })(SceneOptimization);
  30239. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  30240. var MergeMeshesOptimization = (function (_super) {
  30241. __extends(MergeMeshesOptimization, _super);
  30242. function MergeMeshesOptimization() {
  30243. var _this = this;
  30244. _super.apply(this, arguments);
  30245. this._canBeMerged = function (abstractMesh) {
  30246. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  30247. return false;
  30248. }
  30249. var mesh = abstractMesh;
  30250. if (!mesh.isVisible || !mesh.isEnabled()) {
  30251. return false;
  30252. }
  30253. if (mesh.instances.length > 0) {
  30254. return false;
  30255. }
  30256. if (mesh.skeleton || mesh.hasLODLevels) {
  30257. return false;
  30258. }
  30259. return true;
  30260. };
  30261. this.apply = function (scene, updateSelectionTree) {
  30262. var globalPool = scene.meshes.slice(0);
  30263. var globalLength = globalPool.length;
  30264. for (var index = 0; index < globalLength; index++) {
  30265. var currentPool = new Array();
  30266. var current = globalPool[index];
  30267. // Checks
  30268. if (!_this._canBeMerged(current)) {
  30269. continue;
  30270. }
  30271. currentPool.push(current);
  30272. // Find compatible meshes
  30273. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  30274. var otherMesh = globalPool[subIndex];
  30275. if (!_this._canBeMerged(otherMesh)) {
  30276. continue;
  30277. }
  30278. if (otherMesh.material !== current.material) {
  30279. continue;
  30280. }
  30281. if (otherMesh.checkCollisions !== current.checkCollisions) {
  30282. continue;
  30283. }
  30284. currentPool.push(otherMesh);
  30285. globalLength--;
  30286. globalPool.splice(subIndex, 1);
  30287. subIndex--;
  30288. }
  30289. if (currentPool.length < 2) {
  30290. continue;
  30291. }
  30292. // Merge meshes
  30293. BABYLON.Mesh.MergeMeshes(currentPool);
  30294. }
  30295. if (updateSelectionTree != undefined) {
  30296. if (updateSelectionTree) {
  30297. scene.createOrUpdateSelectionOctree();
  30298. }
  30299. }
  30300. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  30301. scene.createOrUpdateSelectionOctree();
  30302. }
  30303. return true;
  30304. };
  30305. }
  30306. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  30307. get: function () {
  30308. return MergeMeshesOptimization._UpdateSelectionTree;
  30309. },
  30310. set: function (value) {
  30311. MergeMeshesOptimization._UpdateSelectionTree = value;
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. MergeMeshesOptimization._UpdateSelectionTree = false;
  30317. return MergeMeshesOptimization;
  30318. })(SceneOptimization);
  30319. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  30320. // Options
  30321. var SceneOptimizerOptions = (function () {
  30322. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  30323. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  30324. if (trackerDuration === void 0) { trackerDuration = 2000; }
  30325. this.targetFrameRate = targetFrameRate;
  30326. this.trackerDuration = trackerDuration;
  30327. this.optimizations = new Array();
  30328. }
  30329. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  30330. var result = new SceneOptimizerOptions(targetFrameRate);
  30331. var priority = 0;
  30332. result.optimizations.push(new MergeMeshesOptimization(priority));
  30333. result.optimizations.push(new ShadowsOptimization(priority));
  30334. result.optimizations.push(new LensFlaresOptimization(priority));
  30335. // Next priority
  30336. priority++;
  30337. result.optimizations.push(new PostProcessesOptimization(priority));
  30338. result.optimizations.push(new ParticlesOptimization(priority));
  30339. // Next priority
  30340. priority++;
  30341. result.optimizations.push(new TextureOptimization(priority, 1024));
  30342. return result;
  30343. };
  30344. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  30345. var result = new SceneOptimizerOptions(targetFrameRate);
  30346. var priority = 0;
  30347. result.optimizations.push(new MergeMeshesOptimization(priority));
  30348. result.optimizations.push(new ShadowsOptimization(priority));
  30349. result.optimizations.push(new LensFlaresOptimization(priority));
  30350. // Next priority
  30351. priority++;
  30352. result.optimizations.push(new PostProcessesOptimization(priority));
  30353. result.optimizations.push(new ParticlesOptimization(priority));
  30354. // Next priority
  30355. priority++;
  30356. result.optimizations.push(new TextureOptimization(priority, 512));
  30357. // Next priority
  30358. priority++;
  30359. result.optimizations.push(new RenderTargetsOptimization(priority));
  30360. // Next priority
  30361. priority++;
  30362. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  30363. return result;
  30364. };
  30365. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  30366. var result = new SceneOptimizerOptions(targetFrameRate);
  30367. var priority = 0;
  30368. result.optimizations.push(new MergeMeshesOptimization(priority));
  30369. result.optimizations.push(new ShadowsOptimization(priority));
  30370. result.optimizations.push(new LensFlaresOptimization(priority));
  30371. // Next priority
  30372. priority++;
  30373. result.optimizations.push(new PostProcessesOptimization(priority));
  30374. result.optimizations.push(new ParticlesOptimization(priority));
  30375. // Next priority
  30376. priority++;
  30377. result.optimizations.push(new TextureOptimization(priority, 256));
  30378. // Next priority
  30379. priority++;
  30380. result.optimizations.push(new RenderTargetsOptimization(priority));
  30381. // Next priority
  30382. priority++;
  30383. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  30384. return result;
  30385. };
  30386. return SceneOptimizerOptions;
  30387. })();
  30388. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  30389. // Scene optimizer tool
  30390. var SceneOptimizer = (function () {
  30391. function SceneOptimizer() {
  30392. }
  30393. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  30394. // TODO: add an epsilon
  30395. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  30396. if (onSuccess) {
  30397. onSuccess();
  30398. }
  30399. return;
  30400. }
  30401. // Apply current level of optimizations
  30402. var allDone = true;
  30403. var noOptimizationApplied = true;
  30404. for (var index = 0; index < options.optimizations.length; index++) {
  30405. var optimization = options.optimizations[index];
  30406. if (optimization.priority === currentPriorityLevel) {
  30407. noOptimizationApplied = false;
  30408. allDone = allDone && optimization.apply(scene);
  30409. }
  30410. }
  30411. // If no optimization was applied, this is a failure :(
  30412. if (noOptimizationApplied) {
  30413. if (onFailure) {
  30414. onFailure();
  30415. }
  30416. return;
  30417. }
  30418. // If all optimizations were done, move to next level
  30419. if (allDone) {
  30420. currentPriorityLevel++;
  30421. }
  30422. // Let's the system running for a specific amount of time before checking FPS
  30423. scene.executeWhenReady(function () {
  30424. setTimeout(function () {
  30425. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  30426. }, options.trackerDuration);
  30427. });
  30428. };
  30429. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  30430. if (!options) {
  30431. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  30432. }
  30433. // Let's the system running for a specific amount of time before checking FPS
  30434. scene.executeWhenReady(function () {
  30435. setTimeout(function () {
  30436. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  30437. }, options.trackerDuration);
  30438. });
  30439. };
  30440. return SceneOptimizer;
  30441. })();
  30442. BABYLON.SceneOptimizer = SceneOptimizer;
  30443. })(BABYLON || (BABYLON = {}));
  30444. var BABYLON;
  30445. (function (BABYLON) {
  30446. var Internals;
  30447. (function (Internals) {
  30448. var MeshLODLevel = (function () {
  30449. function MeshLODLevel(distance, mesh) {
  30450. this.distance = distance;
  30451. this.mesh = mesh;
  30452. }
  30453. return MeshLODLevel;
  30454. })();
  30455. Internals.MeshLODLevel = MeshLODLevel;
  30456. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30457. })(BABYLON || (BABYLON = {}));
  30458. var BABYLON;
  30459. (function (BABYLON) {
  30460. var AudioEngine = (function () {
  30461. function AudioEngine() {
  30462. this._audioContext = null;
  30463. this._audioContextInitialized = false;
  30464. this.canUseWebAudio = false;
  30465. this.WarnedWebAudioUnsupported = false;
  30466. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  30467. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  30468. this.canUseWebAudio = true;
  30469. }
  30470. }
  30471. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  30472. get: function () {
  30473. if (!this._audioContextInitialized) {
  30474. this._initializeAudioContext();
  30475. }
  30476. return this._audioContext;
  30477. },
  30478. enumerable: true,
  30479. configurable: true
  30480. });
  30481. AudioEngine.prototype._initializeAudioContext = function () {
  30482. try {
  30483. if (this.canUseWebAudio) {
  30484. this._audioContext = new AudioContext();
  30485. // create a global volume gain node
  30486. this.masterGain = this._audioContext.createGain();
  30487. this.masterGain.gain.value = 1;
  30488. this.masterGain.connect(this._audioContext.destination);
  30489. this._audioContextInitialized = true;
  30490. }
  30491. }
  30492. catch (e) {
  30493. this.canUseWebAudio = false;
  30494. BABYLON.Tools.Error("Web Audio: " + e.message);
  30495. }
  30496. };
  30497. AudioEngine.prototype.dispose = function () {
  30498. if (this.canUseWebAudio && this._audioContextInitialized) {
  30499. if (this._connectedAnalyser) {
  30500. this._connectedAnalyser.stopDebugCanvas();
  30501. this._connectedAnalyser.dispose();
  30502. this.masterGain.disconnect();
  30503. this.masterGain.connect(this._audioContext.destination);
  30504. this._connectedAnalyser = null;
  30505. }
  30506. this.masterGain.gain.value = 1;
  30507. }
  30508. this.WarnedWebAudioUnsupported = false;
  30509. };
  30510. AudioEngine.prototype.getGlobalVolume = function () {
  30511. if (this.canUseWebAudio && this._audioContextInitialized) {
  30512. return this.masterGain.gain.value;
  30513. }
  30514. else {
  30515. return -1;
  30516. }
  30517. };
  30518. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  30519. if (this.canUseWebAudio && this._audioContextInitialized) {
  30520. this.masterGain.gain.value = newVolume;
  30521. }
  30522. };
  30523. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  30524. if (this._connectedAnalyser) {
  30525. this._connectedAnalyser.stopDebugCanvas();
  30526. }
  30527. if (this.canUseWebAudio && this._audioContextInitialized) {
  30528. this._connectedAnalyser = analyser;
  30529. this.masterGain.disconnect();
  30530. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  30531. }
  30532. };
  30533. return AudioEngine;
  30534. })();
  30535. BABYLON.AudioEngine = AudioEngine;
  30536. })(BABYLON || (BABYLON = {}));
  30537. var BABYLON;
  30538. (function (BABYLON) {
  30539. var Sound = (function () {
  30540. /**
  30541. * Create a sound and attach it to a scene
  30542. * @param name Name of your sound
  30543. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  30544. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  30545. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  30546. */
  30547. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  30548. var _this = this;
  30549. this.autoplay = false;
  30550. this.loop = false;
  30551. this.useCustomAttenuation = false;
  30552. this.spatialSound = false;
  30553. this.refDistance = 1;
  30554. this.rolloffFactor = 1;
  30555. this.maxDistance = 100;
  30556. this.distanceModel = "linear";
  30557. this._panningModel = "equalpower";
  30558. this._playbackRate = 1;
  30559. this._startTime = 0;
  30560. this._startOffset = 0;
  30561. this._position = BABYLON.Vector3.Zero();
  30562. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30563. this._volume = 1;
  30564. this._isLoaded = false;
  30565. this._isReadyToPlay = false;
  30566. this.isPlaying = false;
  30567. this.isPaused = false;
  30568. this._isDirectional = false;
  30569. // Used if you'd like to create a directional sound.
  30570. // If not set, the sound will be omnidirectional
  30571. this._coneInnerAngle = 360;
  30572. this._coneOuterAngle = 360;
  30573. this._coneOuterGain = 0;
  30574. this._isOutputConnected = false;
  30575. this.name = name;
  30576. this._scene = scene;
  30577. this._readyToPlayCallback = readyToPlayCallback;
  30578. // Default custom attenuation function is a linear attenuation
  30579. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30580. if (currentDistance < maxDistance) {
  30581. return currentVolume * (1 - currentDistance / maxDistance);
  30582. }
  30583. else {
  30584. return 0;
  30585. }
  30586. };
  30587. if (options) {
  30588. this.autoplay = options.autoplay || false;
  30589. this.loop = options.loop || false;
  30590. // if volume === 0, we need another way to check this option
  30591. if (options.volume !== undefined) {
  30592. this._volume = options.volume;
  30593. }
  30594. this.spatialSound = options.spatialSound || false;
  30595. this.maxDistance = options.maxDistance || 100;
  30596. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30597. this.rolloffFactor = options.rolloffFactor || 1;
  30598. this.refDistance = options.refDistance || 1;
  30599. this.distanceModel = options.distanceModel || "linear";
  30600. this._playbackRate = options.playbackRate || 1;
  30601. }
  30602. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30603. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30604. this._soundGain.gain.value = this._volume;
  30605. this._inputAudioNode = this._soundGain;
  30606. this._ouputAudioNode = this._soundGain;
  30607. if (this.spatialSound) {
  30608. this._createSpatialParameters();
  30609. }
  30610. this._scene.mainSoundTrack.AddSound(this);
  30611. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30612. if (urlOrArrayBuffer) {
  30613. // If it's an URL
  30614. if (typeof (urlOrArrayBuffer) === "string") {
  30615. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30616. }
  30617. else {
  30618. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30619. this._soundLoaded(urlOrArrayBuffer);
  30620. }
  30621. else {
  30622. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30623. }
  30624. }
  30625. }
  30626. }
  30627. else {
  30628. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30629. this._scene.mainSoundTrack.AddSound(this);
  30630. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30631. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30632. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30633. }
  30634. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30635. if (this._readyToPlayCallback) {
  30636. window.setTimeout(function () {
  30637. _this._readyToPlayCallback();
  30638. }, 1000);
  30639. }
  30640. }
  30641. }
  30642. Sound.prototype.dispose = function () {
  30643. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30644. if (this.isPlaying) {
  30645. this.stop();
  30646. }
  30647. this._isReadyToPlay = false;
  30648. if (this.soundTrackId === -1) {
  30649. this._scene.mainSoundTrack.RemoveSound(this);
  30650. }
  30651. else {
  30652. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30653. }
  30654. if (this._soundGain) {
  30655. this._soundGain.disconnect();
  30656. this._soundGain = null;
  30657. }
  30658. if (this._soundPanner) {
  30659. this._soundPanner.disconnect();
  30660. this._soundPanner = null;
  30661. }
  30662. if (this._soundSource) {
  30663. this._soundSource.disconnect();
  30664. this._soundSource = null;
  30665. }
  30666. this._audioBuffer = null;
  30667. if (this._connectedMesh) {
  30668. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30669. this._connectedMesh = null;
  30670. }
  30671. }
  30672. };
  30673. Sound.prototype._soundLoaded = function (audioData) {
  30674. var _this = this;
  30675. this._isLoaded = true;
  30676. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30677. _this._audioBuffer = buffer;
  30678. _this._isReadyToPlay = true;
  30679. if (_this.autoplay) {
  30680. _this.play();
  30681. }
  30682. if (_this._readyToPlayCallback) {
  30683. _this._readyToPlayCallback();
  30684. }
  30685. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30686. };
  30687. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30688. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30689. this._audioBuffer = audioBuffer;
  30690. this._isReadyToPlay = true;
  30691. }
  30692. };
  30693. Sound.prototype.updateOptions = function (options) {
  30694. if (options) {
  30695. this.loop = options.loop || this.loop;
  30696. this.maxDistance = options.maxDistance || this.maxDistance;
  30697. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30698. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30699. this.refDistance = options.refDistance || this.refDistance;
  30700. this.distanceModel = options.distanceModel || this.distanceModel;
  30701. this._playbackRate = options.playbackRate || this._playbackRate;
  30702. this._updateSpatialParameters();
  30703. if (this.isPlaying) {
  30704. this._soundSource.playbackRate.value = this._playbackRate;
  30705. }
  30706. }
  30707. };
  30708. Sound.prototype._createSpatialParameters = function () {
  30709. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30710. if (this._scene.headphone) {
  30711. this._panningModel = "HRTF";
  30712. }
  30713. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30714. this._updateSpatialParameters();
  30715. this._soundPanner.connect(this._ouputAudioNode);
  30716. this._inputAudioNode = this._soundPanner;
  30717. }
  30718. };
  30719. Sound.prototype._updateSpatialParameters = function () {
  30720. if (this.spatialSound) {
  30721. if (this.useCustomAttenuation) {
  30722. // Tricks to disable in a way embedded Web Audio attenuation
  30723. this._soundPanner.distanceModel = "linear";
  30724. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30725. this._soundPanner.refDistance = 1;
  30726. this._soundPanner.rolloffFactor = 1;
  30727. this._soundPanner.panningModel = this._panningModel;
  30728. }
  30729. else {
  30730. this._soundPanner.distanceModel = this.distanceModel;
  30731. this._soundPanner.maxDistance = this.maxDistance;
  30732. this._soundPanner.refDistance = this.refDistance;
  30733. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30734. this._soundPanner.panningModel = this._panningModel;
  30735. }
  30736. }
  30737. };
  30738. Sound.prototype.switchPanningModelToHRTF = function () {
  30739. this._panningModel = "HRTF";
  30740. this._switchPanningModel();
  30741. };
  30742. Sound.prototype.switchPanningModelToEqualPower = function () {
  30743. this._panningModel = "equalpower";
  30744. this._switchPanningModel();
  30745. };
  30746. Sound.prototype._switchPanningModel = function () {
  30747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30748. this._soundPanner.panningModel = this._panningModel;
  30749. }
  30750. };
  30751. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30752. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30753. if (this._isOutputConnected) {
  30754. this._ouputAudioNode.disconnect();
  30755. }
  30756. this._ouputAudioNode.connect(soundTrackAudioNode);
  30757. this._isOutputConnected = true;
  30758. }
  30759. };
  30760. /**
  30761. * Transform this sound into a directional source
  30762. * @param coneInnerAngle Size of the inner cone in degree
  30763. * @param coneOuterAngle Size of the outer cone in degree
  30764. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30765. */
  30766. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30767. if (coneOuterAngle < coneInnerAngle) {
  30768. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30769. return;
  30770. }
  30771. this._coneInnerAngle = coneInnerAngle;
  30772. this._coneOuterAngle = coneOuterAngle;
  30773. this._coneOuterGain = coneOuterGain;
  30774. this._isDirectional = true;
  30775. if (this.isPlaying && this.loop) {
  30776. this.stop();
  30777. this.play();
  30778. }
  30779. };
  30780. Sound.prototype.setPosition = function (newPosition) {
  30781. this._position = newPosition;
  30782. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30783. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30784. }
  30785. };
  30786. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30787. this._localDirection = newLocalDirection;
  30788. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30789. this._updateDirection();
  30790. }
  30791. };
  30792. Sound.prototype._updateDirection = function () {
  30793. var mat = this._connectedMesh.getWorldMatrix();
  30794. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30795. direction.normalize();
  30796. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30797. };
  30798. Sound.prototype.updateDistanceFromListener = function () {
  30799. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30800. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30801. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30802. }
  30803. };
  30804. Sound.prototype.setAttenuationFunction = function (callback) {
  30805. this._customAttenuationFunction = callback;
  30806. };
  30807. /**
  30808. * Play the sound
  30809. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30810. */
  30811. Sound.prototype.play = function (time) {
  30812. var _this = this;
  30813. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30814. try {
  30815. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30816. if (!this._soundSource) {
  30817. if (this.spatialSound) {
  30818. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30819. if (this._isDirectional) {
  30820. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30821. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30822. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30823. if (this._connectedMesh) {
  30824. this._updateDirection();
  30825. }
  30826. else {
  30827. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30828. }
  30829. }
  30830. }
  30831. }
  30832. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30833. this._soundSource.buffer = this._audioBuffer;
  30834. this._soundSource.connect(this._inputAudioNode);
  30835. this._soundSource.loop = this.loop;
  30836. this._soundSource.playbackRate.value = this._playbackRate;
  30837. this._startTime = startTime;
  30838. this._soundSource.onended = function () { _this._onended(); };
  30839. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30840. this.isPlaying = true;
  30841. this.isPaused = false;
  30842. }
  30843. catch (ex) {
  30844. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30845. }
  30846. }
  30847. };
  30848. Sound.prototype._onended = function () {
  30849. this.isPlaying = false;
  30850. if (this.onended) {
  30851. this.onended();
  30852. }
  30853. };
  30854. /**
  30855. * Stop the sound
  30856. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30857. */
  30858. Sound.prototype.stop = function (time) {
  30859. if (this.isPlaying) {
  30860. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30861. this._soundSource.stop(stopTime);
  30862. this.isPlaying = false;
  30863. }
  30864. };
  30865. Sound.prototype.pause = function () {
  30866. if (this.isPlaying) {
  30867. this.stop(0);
  30868. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30869. this.isPaused = true;
  30870. }
  30871. };
  30872. Sound.prototype.setVolume = function (newVolume, time) {
  30873. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30874. if (time) {
  30875. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30876. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30877. }
  30878. else {
  30879. this._soundGain.gain.value = newVolume;
  30880. }
  30881. }
  30882. this._volume = newVolume;
  30883. };
  30884. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30885. this._playbackRate = newPlaybackRate;
  30886. if (this.isPlaying) {
  30887. this._soundSource.playbackRate.value = this._playbackRate;
  30888. }
  30889. };
  30890. Sound.prototype.getVolume = function () {
  30891. return this._volume;
  30892. };
  30893. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30894. var _this = this;
  30895. this._connectedMesh = meshToConnectTo;
  30896. if (!this.spatialSound) {
  30897. this.spatialSound = true;
  30898. this._createSpatialParameters();
  30899. if (this.isPlaying && this.loop) {
  30900. this.stop();
  30901. this.play();
  30902. }
  30903. }
  30904. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30905. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30906. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30907. };
  30908. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30909. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30910. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30911. this._updateDirection();
  30912. }
  30913. };
  30914. return Sound;
  30915. })();
  30916. BABYLON.Sound = Sound;
  30917. })(BABYLON || (BABYLON = {}));
  30918. var BABYLON;
  30919. (function (BABYLON) {
  30920. var SoundTrack = (function () {
  30921. function SoundTrack(scene, options) {
  30922. this.id = -1;
  30923. this._isMainTrack = false;
  30924. this._scene = scene;
  30925. this._audioEngine = BABYLON.Engine.audioEngine;
  30926. this.soundCollection = new Array();
  30927. if (this._audioEngine.canUseWebAudio) {
  30928. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30929. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30930. if (options) {
  30931. if (options.volume) {
  30932. this._outputAudioNode.gain.value = options.volume;
  30933. }
  30934. if (options.mainTrack) {
  30935. this._isMainTrack = options.mainTrack;
  30936. }
  30937. }
  30938. }
  30939. if (!this._isMainTrack) {
  30940. this._scene.soundTracks.push(this);
  30941. this.id = this._scene.soundTracks.length - 1;
  30942. }
  30943. }
  30944. SoundTrack.prototype.dispose = function () {
  30945. if (this._audioEngine.canUseWebAudio) {
  30946. if (this._connectedAnalyser) {
  30947. this._connectedAnalyser.stopDebugCanvas();
  30948. }
  30949. while (this.soundCollection.length) {
  30950. this.soundCollection[0].dispose();
  30951. }
  30952. if (this._outputAudioNode) {
  30953. this._outputAudioNode.disconnect();
  30954. }
  30955. this._outputAudioNode = null;
  30956. }
  30957. };
  30958. SoundTrack.prototype.AddSound = function (sound) {
  30959. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30960. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30961. }
  30962. if (sound.soundTrackId) {
  30963. if (sound.soundTrackId === -1) {
  30964. this._scene.mainSoundTrack.RemoveSound(sound);
  30965. }
  30966. else {
  30967. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30968. }
  30969. }
  30970. this.soundCollection.push(sound);
  30971. sound.soundTrackId = this.id;
  30972. };
  30973. SoundTrack.prototype.RemoveSound = function (sound) {
  30974. var index = this.soundCollection.indexOf(sound);
  30975. if (index !== -1) {
  30976. this.soundCollection.splice(index, 1);
  30977. }
  30978. };
  30979. SoundTrack.prototype.setVolume = function (newVolume) {
  30980. if (this._audioEngine.canUseWebAudio) {
  30981. this._outputAudioNode.gain.value = newVolume;
  30982. }
  30983. };
  30984. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30985. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30986. for (var i = 0; i < this.soundCollection.length; i++) {
  30987. this.soundCollection[i].switchPanningModelToHRTF();
  30988. }
  30989. }
  30990. };
  30991. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30992. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30993. for (var i = 0; i < this.soundCollection.length; i++) {
  30994. this.soundCollection[i].switchPanningModelToEqualPower();
  30995. }
  30996. }
  30997. };
  30998. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30999. if (this._connectedAnalyser) {
  31000. this._connectedAnalyser.stopDebugCanvas();
  31001. }
  31002. this._connectedAnalyser = analyser;
  31003. if (this._audioEngine.canUseWebAudio) {
  31004. this._outputAudioNode.disconnect();
  31005. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  31006. }
  31007. };
  31008. return SoundTrack;
  31009. })();
  31010. BABYLON.SoundTrack = SoundTrack;
  31011. })(BABYLON || (BABYLON = {}));
  31012. var BABYLON;
  31013. (function (BABYLON) {
  31014. var DebugLayer = (function () {
  31015. function DebugLayer(scene) {
  31016. var _this = this;
  31017. this._transformationMatrix = BABYLON.Matrix.Identity();
  31018. this._enabled = false;
  31019. this._labelsEnabled = false;
  31020. this._displayStatistics = true;
  31021. this._displayTree = false;
  31022. this._displayLogs = false;
  31023. this._identityMatrix = BABYLON.Matrix.Identity();
  31024. this.axisRatio = 0.02;
  31025. this.accentColor = "orange";
  31026. this._scene = scene;
  31027. this._syncPositions = function () {
  31028. var engine = _this._scene.getEngine();
  31029. var canvasRect = engine.getRenderingCanvasClientRect();
  31030. if (_this._showUI) {
  31031. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  31032. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  31033. _this._statsDiv.style.width = "400px";
  31034. _this._statsDiv.style.height = "auto";
  31035. _this._statsSubsetDiv.style.maxHeight = "240px";
  31036. _this._optionsDiv.style.left = "0px";
  31037. _this._optionsDiv.style.top = "10px";
  31038. _this._optionsDiv.style.width = "200px";
  31039. _this._optionsDiv.style.height = "auto";
  31040. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  31041. _this._logDiv.style.left = "0px";
  31042. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  31043. _this._logDiv.style.width = "600px";
  31044. _this._logDiv.style.height = "160px";
  31045. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  31046. _this._treeDiv.style.top = "10px";
  31047. _this._treeDiv.style.width = "300px";
  31048. _this._treeDiv.style.height = "auto";
  31049. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  31050. }
  31051. _this._globalDiv.style.left = canvasRect.left + "px";
  31052. _this._globalDiv.style.top = canvasRect.top + "px";
  31053. _this._drawingCanvas.style.left = "0px";
  31054. _this._drawingCanvas.style.top = "0px";
  31055. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  31056. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  31057. var devicePixelRatio = window.devicePixelRatio || 1;
  31058. var context = _this._drawingContext;
  31059. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  31060. context.mozBackingStorePixelRatio ||
  31061. context.msBackingStorePixelRatio ||
  31062. context.oBackingStorePixelRatio ||
  31063. context.backingStorePixelRatio || 1;
  31064. _this._ratio = devicePixelRatio / backingStoreRatio;
  31065. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  31066. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  31067. };
  31068. this._onCanvasClick = function (evt) {
  31069. _this._clickPosition = {
  31070. x: evt.clientX * _this._ratio,
  31071. y: evt.clientY * _this._ratio
  31072. };
  31073. };
  31074. this._syncUI = function () {
  31075. if (_this._showUI) {
  31076. if (_this._displayStatistics) {
  31077. _this._displayStats();
  31078. _this._statsDiv.style.display = "";
  31079. }
  31080. else {
  31081. _this._statsDiv.style.display = "none";
  31082. }
  31083. if (_this._displayLogs) {
  31084. _this._logDiv.style.display = "";
  31085. }
  31086. else {
  31087. _this._logDiv.style.display = "none";
  31088. }
  31089. if (_this._displayTree) {
  31090. _this._treeDiv.style.display = "";
  31091. if (_this._needToRefreshMeshesTree) {
  31092. _this._needToRefreshMeshesTree = false;
  31093. _this._refreshMeshesTreeContent();
  31094. }
  31095. }
  31096. else {
  31097. _this._treeDiv.style.display = "none";
  31098. }
  31099. }
  31100. };
  31101. this._syncData = function () {
  31102. if (_this._labelsEnabled || !_this._showUI) {
  31103. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  31104. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  31105. var engine = _this._scene.getEngine();
  31106. var viewport = _this._camera.viewport;
  31107. var globalViewport = viewport.toGlobal(engine);
  31108. // Meshes
  31109. var meshes = _this._camera.getActiveMeshes();
  31110. for (var index = 0; index < meshes.length; index++) {
  31111. var mesh = meshes.data[index];
  31112. var position = mesh.getBoundingInfo().boundingSphere.center;
  31113. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31114. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  31115. _this._renderAxis(projectedPosition, mesh, globalViewport);
  31116. }
  31117. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  31118. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  31119. }
  31120. }
  31121. // Cameras
  31122. var cameras = _this._scene.cameras;
  31123. for (index = 0; index < cameras.length; index++) {
  31124. var camera = cameras[index];
  31125. if (camera === _this._camera) {
  31126. continue;
  31127. }
  31128. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31129. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  31130. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  31131. _this._camera.detachControl(engine.getRenderingCanvas());
  31132. _this._camera = camera;
  31133. _this._camera.attachControl(engine.getRenderingCanvas());
  31134. }, function () { return "purple"; });
  31135. }
  31136. }
  31137. // Lights
  31138. var lights = _this._scene.lights;
  31139. for (index = 0; index < lights.length; index++) {
  31140. var light = lights[index];
  31141. if (light.position) {
  31142. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  31143. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  31144. _this._renderLabel(light.name, projectedPosition, -20, function () {
  31145. light.setEnabled(!light.isEnabled());
  31146. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  31147. }
  31148. }
  31149. }
  31150. }
  31151. _this._clickPosition = undefined;
  31152. };
  31153. }
  31154. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  31155. while (this._treeSubsetDiv.hasChildNodes()) {
  31156. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  31157. }
  31158. // Add meshes
  31159. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  31160. sortedArray.sort(function (a, b) {
  31161. if (a.name === b.name) {
  31162. return 0;
  31163. }
  31164. return (a.name > b.name) ? 1 : -1;
  31165. });
  31166. for (var index = 0; index < sortedArray.length; index++) {
  31167. var mesh = sortedArray[index];
  31168. if (!mesh.isEnabled()) {
  31169. continue;
  31170. }
  31171. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  31172. m.isVisible = element.checked;
  31173. }, mesh);
  31174. }
  31175. };
  31176. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  31177. this._drawingContext.beginPath();
  31178. this._drawingContext.moveTo(zero.x, zero.y);
  31179. this._drawingContext.lineTo(unit.x, unit.y);
  31180. this._drawingContext.strokeStyle = color;
  31181. this._drawingContext.lineWidth = 4;
  31182. this._drawingContext.stroke();
  31183. this._drawingContext.font = "normal 14px Segoe UI";
  31184. this._drawingContext.fillStyle = color;
  31185. this._drawingContext.fillText(label, unitText.x, unitText.y);
  31186. };
  31187. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  31188. var position = mesh.getBoundingInfo().boundingSphere.center;
  31189. var worldMatrix = mesh.getWorldMatrix();
  31190. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  31191. var unit = (unprojectedVector.subtract(position)).length();
  31192. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31193. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31194. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  31195. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31196. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31197. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  31198. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  31199. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  31200. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  31201. };
  31202. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  31203. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  31204. this._drawingContext.font = "normal 12px Segoe UI";
  31205. var textMetrics = this._drawingContext.measureText(text);
  31206. var centerX = projectedPosition.x - textMetrics.width / 2;
  31207. var centerY = projectedPosition.y;
  31208. var clientRect = this._drawingCanvas.getBoundingClientRect();
  31209. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  31210. onClick();
  31211. }
  31212. this._drawingContext.beginPath();
  31213. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  31214. this._drawingContext.fillStyle = getFillStyle();
  31215. this._drawingContext.globalAlpha = 0.5;
  31216. this._drawingContext.fill();
  31217. this._drawingContext.globalAlpha = 1.0;
  31218. this._drawingContext.strokeStyle = '#FFFFFF';
  31219. this._drawingContext.lineWidth = 1;
  31220. this._drawingContext.stroke();
  31221. this._drawingContext.fillStyle = "#FFFFFF";
  31222. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  31223. this._drawingContext.beginPath();
  31224. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  31225. this._drawingContext.fill();
  31226. }
  31227. };
  31228. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  31229. if (!this._clickPosition) {
  31230. return false;
  31231. }
  31232. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  31233. return false;
  31234. }
  31235. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  31236. return false;
  31237. }
  31238. return true;
  31239. };
  31240. DebugLayer.prototype.isVisible = function () {
  31241. return this._enabled;
  31242. };
  31243. DebugLayer.prototype.hide = function () {
  31244. if (!this._enabled) {
  31245. return;
  31246. }
  31247. this._enabled = false;
  31248. var engine = this._scene.getEngine();
  31249. this._scene.unregisterBeforeRender(this._syncData);
  31250. this._scene.unregisterAfterRender(this._syncUI);
  31251. document.body.removeChild(this._globalDiv);
  31252. window.removeEventListener("resize", this._syncPositions);
  31253. this._scene.forceShowBoundingBoxes = false;
  31254. this._scene.forceWireframe = false;
  31255. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  31256. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  31257. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  31258. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  31259. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  31260. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  31261. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  31262. BABYLON.StandardMaterial.LightmapEnabled = true;
  31263. this._scene.shadowsEnabled = true;
  31264. this._scene.particlesEnabled = true;
  31265. this._scene.postProcessesEnabled = true;
  31266. this._scene.collisionsEnabled = true;
  31267. this._scene.lightsEnabled = true;
  31268. this._scene.texturesEnabled = true;
  31269. this._scene.lensFlaresEnabled = true;
  31270. this._scene.proceduralTexturesEnabled = true;
  31271. this._scene.renderTargetsEnabled = true;
  31272. this._scene.probesEnabled = true;
  31273. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  31274. };
  31275. DebugLayer.prototype.show = function (showUI, camera) {
  31276. if (showUI === void 0) { showUI = true; }
  31277. if (camera === void 0) { camera = null; }
  31278. if (this._enabled) {
  31279. return;
  31280. }
  31281. this._enabled = true;
  31282. if (camera) {
  31283. this._camera = camera;
  31284. }
  31285. else {
  31286. this._camera = this._scene.activeCamera;
  31287. }
  31288. this._showUI = showUI;
  31289. var engine = this._scene.getEngine();
  31290. this._globalDiv = document.createElement("div");
  31291. document.body.appendChild(this._globalDiv);
  31292. this._generateDOMelements();
  31293. window.addEventListener("resize", this._syncPositions);
  31294. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  31295. this._syncPositions();
  31296. this._scene.registerBeforeRender(this._syncData);
  31297. this._scene.registerAfterRender(this._syncUI);
  31298. };
  31299. DebugLayer.prototype._clearLabels = function () {
  31300. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  31301. for (var index = 0; index < this._scene.meshes.length; index++) {
  31302. var mesh = this._scene.meshes[index];
  31303. mesh.renderOverlay = false;
  31304. }
  31305. };
  31306. DebugLayer.prototype._generateheader = function (root, text) {
  31307. var header = document.createElement("div");
  31308. header.innerHTML = text + "&nbsp;";
  31309. header.style.textAlign = "right";
  31310. header.style.width = "100%";
  31311. header.style.color = "white";
  31312. header.style.backgroundColor = "Black";
  31313. header.style.padding = "5px 5px 4px 0px";
  31314. header.style.marginLeft = "-5px";
  31315. header.style.fontWeight = "bold";
  31316. root.appendChild(header);
  31317. };
  31318. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  31319. var label = document.createElement("label");
  31320. label.innerHTML = title;
  31321. label.style.color = color;
  31322. root.appendChild(label);
  31323. root.appendChild(document.createElement("br"));
  31324. };
  31325. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  31326. if (tag === void 0) { tag = null; }
  31327. var label = document.createElement("label");
  31328. var boundingBoxesCheckbox = document.createElement("input");
  31329. boundingBoxesCheckbox.type = "checkbox";
  31330. boundingBoxesCheckbox.checked = initialState;
  31331. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  31332. task(evt.target, tag);
  31333. });
  31334. label.appendChild(boundingBoxesCheckbox);
  31335. var container = document.createElement("span");
  31336. var leftPart = document.createElement("span");
  31337. var rightPart = document.createElement("span");
  31338. rightPart.style.cssFloat = "right";
  31339. leftPart.innerHTML = leftTitle;
  31340. rightPart.innerHTML = rightTitle;
  31341. rightPart.style.fontSize = "12px";
  31342. rightPart.style.maxWidth = "200px";
  31343. container.appendChild(leftPart);
  31344. container.appendChild(rightPart);
  31345. label.appendChild(container);
  31346. root.appendChild(label);
  31347. root.appendChild(document.createElement("br"));
  31348. };
  31349. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  31350. if (tag === void 0) { tag = null; }
  31351. var label = document.createElement("label");
  31352. var checkBox = document.createElement("input");
  31353. checkBox.type = "checkbox";
  31354. checkBox.checked = initialState;
  31355. checkBox.addEventListener("change", function (evt) {
  31356. task(evt.target, tag);
  31357. });
  31358. label.appendChild(checkBox);
  31359. label.appendChild(document.createTextNode(title));
  31360. root.appendChild(label);
  31361. root.appendChild(document.createElement("br"));
  31362. };
  31363. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  31364. if (tag === void 0) { tag = null; }
  31365. var button = document.createElement("button");
  31366. button.innerHTML = title;
  31367. button.style.height = "24px";
  31368. button.style.color = "#444444";
  31369. button.style.border = "1px solid white";
  31370. button.className = "debugLayerButton";
  31371. button.addEventListener("click", function (evt) {
  31372. task(evt.target, tag);
  31373. });
  31374. root.appendChild(button);
  31375. root.appendChild(document.createElement("br"));
  31376. };
  31377. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  31378. if (tag === void 0) { tag = null; }
  31379. var label = document.createElement("label");
  31380. var boundingBoxesRadio = document.createElement("input");
  31381. boundingBoxesRadio.type = "radio";
  31382. boundingBoxesRadio.name = name;
  31383. boundingBoxesRadio.checked = initialState;
  31384. boundingBoxesRadio.addEventListener("change", function (evt) {
  31385. task(evt.target, tag);
  31386. });
  31387. label.appendChild(boundingBoxesRadio);
  31388. label.appendChild(document.createTextNode(title));
  31389. root.appendChild(label);
  31390. root.appendChild(document.createElement("br"));
  31391. };
  31392. DebugLayer.prototype._generateDOMelements = function () {
  31393. var _this = this;
  31394. this._globalDiv.id = "DebugLayer";
  31395. this._globalDiv.style.position = "absolute";
  31396. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  31397. this._globalDiv.style.fontSize = "14px";
  31398. this._globalDiv.style.color = "white";
  31399. // Drawing canvas
  31400. this._drawingCanvas = document.createElement("canvas");
  31401. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  31402. this._drawingCanvas.style.position = "absolute";
  31403. this._drawingCanvas.style.pointerEvents = "none";
  31404. this._drawingContext = this._drawingCanvas.getContext("2d");
  31405. this._globalDiv.appendChild(this._drawingCanvas);
  31406. if (this._showUI) {
  31407. var background = "rgba(128, 128, 128, 0.4)";
  31408. var border = "rgb(180, 180, 180) solid 1px";
  31409. // Stats
  31410. this._statsDiv = document.createElement("div");
  31411. this._statsDiv.id = "DebugLayerStats";
  31412. this._statsDiv.style.border = border;
  31413. this._statsDiv.style.position = "absolute";
  31414. this._statsDiv.style.background = background;
  31415. this._statsDiv.style.padding = "0px 0px 0px 5px";
  31416. this._generateheader(this._statsDiv, "STATISTICS");
  31417. this._statsSubsetDiv = document.createElement("div");
  31418. this._statsSubsetDiv.style.paddingTop = "5px";
  31419. this._statsSubsetDiv.style.paddingBottom = "5px";
  31420. this._statsSubsetDiv.style.overflowY = "auto";
  31421. this._statsDiv.appendChild(this._statsSubsetDiv);
  31422. // Tree
  31423. this._treeDiv = document.createElement("div");
  31424. this._treeDiv.id = "DebugLayerTree";
  31425. this._treeDiv.style.border = border;
  31426. this._treeDiv.style.position = "absolute";
  31427. this._treeDiv.style.background = background;
  31428. this._treeDiv.style.padding = "0px 0px 0px 5px";
  31429. this._treeDiv.style.display = "none";
  31430. this._generateheader(this._treeDiv, "MESHES TREE");
  31431. this._treeSubsetDiv = document.createElement("div");
  31432. this._treeSubsetDiv.style.paddingTop = "5px";
  31433. this._treeSubsetDiv.style.paddingRight = "5px";
  31434. this._treeSubsetDiv.style.overflowY = "auto";
  31435. this._treeSubsetDiv.style.maxHeight = "300px";
  31436. this._treeDiv.appendChild(this._treeSubsetDiv);
  31437. this._needToRefreshMeshesTree = true;
  31438. // Logs
  31439. this._logDiv = document.createElement("div");
  31440. this._logDiv.style.border = border;
  31441. this._logDiv.id = "DebugLayerLogs";
  31442. this._logDiv.style.position = "absolute";
  31443. this._logDiv.style.background = background;
  31444. this._logDiv.style.padding = "0px 0px 0px 5px";
  31445. this._logDiv.style.display = "none";
  31446. this._generateheader(this._logDiv, "LOGS");
  31447. this._logSubsetDiv = document.createElement("div");
  31448. this._logSubsetDiv.style.height = "127px";
  31449. this._logSubsetDiv.style.paddingTop = "5px";
  31450. this._logSubsetDiv.style.overflowY = "auto";
  31451. this._logSubsetDiv.style.fontSize = "12px";
  31452. this._logSubsetDiv.style.fontFamily = "consolas";
  31453. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31454. this._logDiv.appendChild(this._logSubsetDiv);
  31455. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31456. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31457. };
  31458. // Options
  31459. this._optionsDiv = document.createElement("div");
  31460. this._optionsDiv.id = "DebugLayerOptions";
  31461. this._optionsDiv.style.border = border;
  31462. this._optionsDiv.style.position = "absolute";
  31463. this._optionsDiv.style.background = background;
  31464. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31465. this._optionsDiv.style.overflowY = "auto";
  31466. this._generateheader(this._optionsDiv, "OPTIONS");
  31467. this._optionsSubsetDiv = document.createElement("div");
  31468. this._optionsSubsetDiv.style.paddingTop = "5px";
  31469. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31470. this._optionsSubsetDiv.style.overflowY = "auto";
  31471. this._optionsSubsetDiv.style.maxHeight = "200px";
  31472. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31473. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31474. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31475. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31476. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31477. _this._displayTree = element.checked;
  31478. _this._needToRefreshMeshesTree = true;
  31479. });
  31480. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31481. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31482. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31483. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31484. _this._labelsEnabled = element.checked;
  31485. if (!_this._labelsEnabled) {
  31486. _this._clearLabels();
  31487. }
  31488. });
  31489. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31490. if (element.checked) {
  31491. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31492. }
  31493. else {
  31494. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31495. }
  31496. });
  31497. ;
  31498. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31499. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31500. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31501. if (element.checked) {
  31502. _this._scene.forceWireframe = false;
  31503. _this._scene.forcePointsCloud = false;
  31504. }
  31505. });
  31506. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31507. if (element.checked) {
  31508. _this._scene.forceWireframe = true;
  31509. _this._scene.forcePointsCloud = false;
  31510. }
  31511. });
  31512. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31513. if (element.checked) {
  31514. _this._scene.forceWireframe = false;
  31515. _this._scene.forcePointsCloud = true;
  31516. }
  31517. });
  31518. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31519. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31520. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31521. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31522. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31523. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31524. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31525. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31526. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31527. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31528. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  31529. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31530. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31531. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31532. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31533. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31534. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31535. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31536. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31537. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31538. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  31539. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31540. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31541. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31542. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31543. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31544. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31545. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31546. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31547. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31548. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31549. if (element.checked) {
  31550. _this._scene.headphone = true;
  31551. }
  31552. });
  31553. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31554. if (element.checked) {
  31555. _this._scene.headphone = false;
  31556. }
  31557. });
  31558. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31559. _this._scene.audioEnabled = !element.checked;
  31560. });
  31561. }
  31562. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31563. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31564. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31565. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31566. this._globalDiv.appendChild(this._statsDiv);
  31567. this._globalDiv.appendChild(this._logDiv);
  31568. this._globalDiv.appendChild(this._optionsDiv);
  31569. this._globalDiv.appendChild(this._treeDiv);
  31570. }
  31571. };
  31572. DebugLayer.prototype._displayStats = function () {
  31573. var scene = this._scene;
  31574. var engine = scene.getEngine();
  31575. var glInfo = engine.getGlInfo();
  31576. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31577. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31578. + "<b>Count</b><br>"
  31579. + "Total meshes: " + scene.meshes.length + "<br>"
  31580. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31581. + "Total materials: " + scene.materials.length + "<br>"
  31582. + "Total textures: " + scene.textures.length + "<br>"
  31583. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31584. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31585. + "Active bones: " + scene.getActiveBones() + "<br>"
  31586. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31587. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31588. + "<b>Duration</b><br>"
  31589. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31590. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31591. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31592. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31593. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31594. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31595. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31596. + "</div>"
  31597. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31598. + "<b>Extensions</b><br>"
  31599. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31600. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31601. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31602. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31603. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31604. + "<b>Caps.</b><br>"
  31605. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31606. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31607. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31608. + "</div><br>"
  31609. + "<b>Info</b><br>"
  31610. + glInfo.version + "<br>"
  31611. + glInfo.renderer + "<br>";
  31612. if (this.customStatsFunction) {
  31613. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31614. }
  31615. };
  31616. return DebugLayer;
  31617. })();
  31618. BABYLON.DebugLayer = DebugLayer;
  31619. })(BABYLON || (BABYLON = {}));
  31620. var BABYLON;
  31621. (function (BABYLON) {
  31622. var RawTexture = (function (_super) {
  31623. __extends(RawTexture, _super);
  31624. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31625. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31626. if (invertY === void 0) { invertY = false; }
  31627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31628. _super.call(this, null, scene, !generateMipMaps, invertY);
  31629. this.format = format;
  31630. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31631. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31632. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31633. }
  31634. RawTexture.prototype.update = function (data) {
  31635. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31636. };
  31637. // Statics
  31638. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31639. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31640. if (invertY === void 0) { invertY = false; }
  31641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31642. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31643. };
  31644. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31645. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31646. if (invertY === void 0) { invertY = false; }
  31647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31648. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31649. };
  31650. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31651. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31652. if (invertY === void 0) { invertY = false; }
  31653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31654. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31655. };
  31656. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31657. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31658. if (invertY === void 0) { invertY = false; }
  31659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31660. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31661. };
  31662. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31663. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31664. if (invertY === void 0) { invertY = false; }
  31665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31666. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31667. };
  31668. return RawTexture;
  31669. })(BABYLON.Texture);
  31670. BABYLON.RawTexture = RawTexture;
  31671. })(BABYLON || (BABYLON = {}));
  31672. var BABYLON;
  31673. (function (BABYLON) {
  31674. var IndexedVector2 = (function (_super) {
  31675. __extends(IndexedVector2, _super);
  31676. function IndexedVector2(original, index) {
  31677. _super.call(this, original.x, original.y);
  31678. this.index = index;
  31679. }
  31680. return IndexedVector2;
  31681. })(BABYLON.Vector2);
  31682. var PolygonPoints = (function () {
  31683. function PolygonPoints() {
  31684. this.elements = new Array();
  31685. }
  31686. PolygonPoints.prototype.add = function (originalPoints) {
  31687. var _this = this;
  31688. var result = new Array();
  31689. originalPoints.forEach(function (point) {
  31690. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31691. var newPoint = new IndexedVector2(point, _this.elements.length);
  31692. result.push(newPoint);
  31693. _this.elements.push(newPoint);
  31694. }
  31695. });
  31696. return result;
  31697. };
  31698. PolygonPoints.prototype.computeBounds = function () {
  31699. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31700. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31701. this.elements.forEach(function (point) {
  31702. // x
  31703. if (point.x < lmin.x) {
  31704. lmin.x = point.x;
  31705. }
  31706. else if (point.x > lmax.x) {
  31707. lmax.x = point.x;
  31708. }
  31709. // y
  31710. if (point.y < lmin.y) {
  31711. lmin.y = point.y;
  31712. }
  31713. else if (point.y > lmax.y) {
  31714. lmax.y = point.y;
  31715. }
  31716. });
  31717. return {
  31718. min: lmin,
  31719. max: lmax,
  31720. width: lmax.x - lmin.x,
  31721. height: lmax.y - lmin.y
  31722. };
  31723. };
  31724. return PolygonPoints;
  31725. })();
  31726. var Polygon = (function () {
  31727. function Polygon() {
  31728. }
  31729. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31730. return [
  31731. new BABYLON.Vector2(xmin, ymin),
  31732. new BABYLON.Vector2(xmax, ymin),
  31733. new BABYLON.Vector2(xmax, ymax),
  31734. new BABYLON.Vector2(xmin, ymax)
  31735. ];
  31736. };
  31737. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31738. if (cx === void 0) { cx = 0; }
  31739. if (cy === void 0) { cy = 0; }
  31740. if (numberOfSides === void 0) { numberOfSides = 32; }
  31741. var result = new Array();
  31742. var angle = 0;
  31743. var increment = (Math.PI * 2) / numberOfSides;
  31744. for (var i = 0; i < numberOfSides; i++) {
  31745. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31746. angle -= increment;
  31747. }
  31748. return result;
  31749. };
  31750. Polygon.Parse = function (input) {
  31751. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31752. var i, result = [];
  31753. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31754. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31755. }
  31756. return result;
  31757. };
  31758. Polygon.StartingAt = function (x, y) {
  31759. return BABYLON.Path2.StartingAt(x, y);
  31760. };
  31761. return Polygon;
  31762. })();
  31763. BABYLON.Polygon = Polygon;
  31764. var PolygonMeshBuilder = (function () {
  31765. function PolygonMeshBuilder(name, contours, scene) {
  31766. this._points = new PolygonPoints();
  31767. this._outlinepoints = new PolygonPoints();
  31768. this._holes = [];
  31769. if (!("poly2tri" in window)) {
  31770. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31771. }
  31772. this._name = name;
  31773. this._scene = scene;
  31774. var points;
  31775. if (contours instanceof BABYLON.Path2) {
  31776. points = contours.getPoints();
  31777. }
  31778. else {
  31779. points = contours;
  31780. }
  31781. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31782. this._outlinepoints.add(points);
  31783. }
  31784. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31785. this._swctx.addHole(this._points.add(hole));
  31786. var holepoints = new PolygonPoints();
  31787. holepoints.add(hole);
  31788. this._holes.push(holepoints);
  31789. return this;
  31790. };
  31791. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31792. var _this = this;
  31793. if (updatable === void 0) { updatable = false; }
  31794. var result = new BABYLON.Mesh(this._name, this._scene);
  31795. var normals = [];
  31796. var positions = [];
  31797. var uvs = [];
  31798. var bounds = this._points.computeBounds();
  31799. this._points.elements.forEach(function (p) {
  31800. normals.push(0, 1.0, 0);
  31801. positions.push(p.x, 0, p.y);
  31802. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31803. });
  31804. var indices = [];
  31805. this._swctx.triangulate();
  31806. this._swctx.getTriangles().forEach(function (triangle) {
  31807. triangle.getPoints().forEach(function (point) {
  31808. indices.push(point.index);
  31809. });
  31810. });
  31811. if (depth > 0) {
  31812. var positionscount = (positions.length / 3); //get the current pointcount
  31813. this._points.elements.forEach(function (p) {
  31814. normals.push(0, -1.0, 0);
  31815. positions.push(p.x, -depth, p.y);
  31816. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31817. });
  31818. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31819. var p2;
  31820. var poscounter = 0;
  31821. this._swctx.getTriangles().forEach(function (triangle) {
  31822. triangle.getPoints().forEach(function (point) {
  31823. switch (poscounter) {
  31824. case 0:
  31825. p1 = point;
  31826. break;
  31827. case 1:
  31828. p2 = point;
  31829. break;
  31830. case 2:
  31831. indices.push(point.index + positionscount);
  31832. indices.push(p2.index + positionscount);
  31833. indices.push(p1.index + positionscount);
  31834. poscounter = -1;
  31835. break;
  31836. }
  31837. poscounter++;
  31838. //indices.push((<IndexedVector2>point).index + positionscount);
  31839. });
  31840. });
  31841. //Add the sides
  31842. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31843. this._holes.forEach(function (hole) {
  31844. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31845. });
  31846. }
  31847. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31848. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31849. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31850. result.setIndices(indices);
  31851. return result;
  31852. };
  31853. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31854. var StartIndex = positions.length / 3;
  31855. var ulength = 0;
  31856. for (var i = 0; i < points.elements.length; i++) {
  31857. var p = points.elements[i];
  31858. var p1;
  31859. if ((i + 1) > points.elements.length - 1) {
  31860. p1 = points.elements[0];
  31861. }
  31862. else {
  31863. p1 = points.elements[i + 1];
  31864. }
  31865. positions.push(p.x, 0, p.y);
  31866. positions.push(p.x, -depth, p.y);
  31867. positions.push(p1.x, 0, p1.y);
  31868. positions.push(p1.x, -depth, p1.y);
  31869. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31870. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31871. var v3 = v2.subtract(v1);
  31872. var v4 = new BABYLON.Vector3(0, 1, 0);
  31873. var vn = BABYLON.Vector3.Cross(v3, v4);
  31874. vn = vn.normalize();
  31875. uvs.push(ulength / bounds.width, 0);
  31876. uvs.push(ulength / bounds.width, 1);
  31877. ulength += v3.length();
  31878. uvs.push((ulength / bounds.width), 0);
  31879. uvs.push((ulength / bounds.width), 1);
  31880. if (!flip) {
  31881. normals.push(-vn.x, -vn.y, -vn.z);
  31882. normals.push(-vn.x, -vn.y, -vn.z);
  31883. normals.push(-vn.x, -vn.y, -vn.z);
  31884. normals.push(-vn.x, -vn.y, -vn.z);
  31885. indices.push(StartIndex);
  31886. indices.push(StartIndex + 1);
  31887. indices.push(StartIndex + 2);
  31888. indices.push(StartIndex + 1);
  31889. indices.push(StartIndex + 3);
  31890. indices.push(StartIndex + 2);
  31891. }
  31892. else {
  31893. normals.push(vn.x, vn.y, vn.z);
  31894. normals.push(vn.x, vn.y, vn.z);
  31895. normals.push(vn.x, vn.y, vn.z);
  31896. normals.push(vn.x, vn.y, vn.z);
  31897. indices.push(StartIndex);
  31898. indices.push(StartIndex + 2);
  31899. indices.push(StartIndex + 1);
  31900. indices.push(StartIndex + 1);
  31901. indices.push(StartIndex + 2);
  31902. indices.push(StartIndex + 3);
  31903. }
  31904. StartIndex += 4;
  31905. }
  31906. ;
  31907. };
  31908. return PolygonMeshBuilder;
  31909. })();
  31910. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31911. })(BABYLON || (BABYLON = {}));
  31912. var BABYLON;
  31913. (function (BABYLON) {
  31914. var SimplificationSettings = (function () {
  31915. function SimplificationSettings(quality, distance, optimizeMesh) {
  31916. this.quality = quality;
  31917. this.distance = distance;
  31918. this.optimizeMesh = optimizeMesh;
  31919. }
  31920. return SimplificationSettings;
  31921. })();
  31922. BABYLON.SimplificationSettings = SimplificationSettings;
  31923. var SimplificationQueue = (function () {
  31924. function SimplificationQueue() {
  31925. this.running = false;
  31926. this._simplificationArray = [];
  31927. }
  31928. SimplificationQueue.prototype.addTask = function (task) {
  31929. this._simplificationArray.push(task);
  31930. };
  31931. SimplificationQueue.prototype.executeNext = function () {
  31932. var task = this._simplificationArray.pop();
  31933. if (task) {
  31934. this.running = true;
  31935. this.runSimplification(task);
  31936. }
  31937. else {
  31938. this.running = false;
  31939. }
  31940. };
  31941. SimplificationQueue.prototype.runSimplification = function (task) {
  31942. var _this = this;
  31943. if (task.parallelProcessing) {
  31944. //parallel simplifier
  31945. task.settings.forEach(function (setting) {
  31946. var simplifier = _this.getSimplifier(task);
  31947. simplifier.simplify(setting, function (newMesh) {
  31948. task.mesh.addLODLevel(setting.distance, newMesh);
  31949. newMesh.isVisible = true;
  31950. //check if it is the last
  31951. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31952. //all done, run the success callback.
  31953. task.successCallback();
  31954. }
  31955. _this.executeNext();
  31956. });
  31957. });
  31958. }
  31959. else {
  31960. //single simplifier.
  31961. var simplifier = this.getSimplifier(task);
  31962. var runDecimation = function (setting, callback) {
  31963. simplifier.simplify(setting, function (newMesh) {
  31964. task.mesh.addLODLevel(setting.distance, newMesh);
  31965. newMesh.isVisible = true;
  31966. //run the next quality level
  31967. callback();
  31968. });
  31969. };
  31970. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31971. runDecimation(task.settings[loop.index], function () {
  31972. loop.executeNext();
  31973. });
  31974. }, function () {
  31975. //execution ended, run the success callback.
  31976. if (task.successCallback) {
  31977. task.successCallback();
  31978. }
  31979. _this.executeNext();
  31980. });
  31981. }
  31982. };
  31983. SimplificationQueue.prototype.getSimplifier = function (task) {
  31984. switch (task.simplificationType) {
  31985. case SimplificationType.QUADRATIC:
  31986. default:
  31987. return new QuadraticErrorSimplification(task.mesh);
  31988. }
  31989. };
  31990. return SimplificationQueue;
  31991. })();
  31992. BABYLON.SimplificationQueue = SimplificationQueue;
  31993. /**
  31994. * The implemented types of simplification.
  31995. * At the moment only Quadratic Error Decimation is implemented.
  31996. */
  31997. (function (SimplificationType) {
  31998. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31999. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  32000. var SimplificationType = BABYLON.SimplificationType;
  32001. var DecimationTriangle = (function () {
  32002. function DecimationTriangle(vertices) {
  32003. this.vertices = vertices;
  32004. this.error = new Array(4);
  32005. this.deleted = false;
  32006. this.isDirty = false;
  32007. this.deletePending = false;
  32008. this.borderFactor = 0;
  32009. }
  32010. return DecimationTriangle;
  32011. })();
  32012. BABYLON.DecimationTriangle = DecimationTriangle;
  32013. var DecimationVertex = (function () {
  32014. function DecimationVertex(position, id) {
  32015. this.position = position;
  32016. this.id = id;
  32017. this.isBorder = true;
  32018. this.q = new QuadraticMatrix();
  32019. this.triangleCount = 0;
  32020. this.triangleStart = 0;
  32021. this.originalOffsets = [];
  32022. }
  32023. DecimationVertex.prototype.updatePosition = function (newPosition) {
  32024. this.position.copyFrom(newPosition);
  32025. };
  32026. return DecimationVertex;
  32027. })();
  32028. BABYLON.DecimationVertex = DecimationVertex;
  32029. var QuadraticMatrix = (function () {
  32030. function QuadraticMatrix(data) {
  32031. this.data = new Array(10);
  32032. for (var i = 0; i < 10; ++i) {
  32033. if (data && data[i]) {
  32034. this.data[i] = data[i];
  32035. }
  32036. else {
  32037. this.data[i] = 0;
  32038. }
  32039. }
  32040. }
  32041. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  32042. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  32043. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  32044. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  32045. return det;
  32046. };
  32047. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  32048. for (var i = 0; i < 10; ++i) {
  32049. this.data[i] += matrix.data[i];
  32050. }
  32051. };
  32052. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  32053. for (var i = 0; i < 10; ++i) {
  32054. this.data[i] += data[i];
  32055. }
  32056. };
  32057. QuadraticMatrix.prototype.add = function (matrix) {
  32058. var m = new QuadraticMatrix();
  32059. for (var i = 0; i < 10; ++i) {
  32060. m.data[i] = this.data[i] + matrix.data[i];
  32061. }
  32062. return m;
  32063. };
  32064. QuadraticMatrix.FromData = function (a, b, c, d) {
  32065. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  32066. };
  32067. //returning an array to avoid garbage collection
  32068. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  32069. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  32070. };
  32071. return QuadraticMatrix;
  32072. })();
  32073. BABYLON.QuadraticMatrix = QuadraticMatrix;
  32074. var Reference = (function () {
  32075. function Reference(vertexId, triangleId) {
  32076. this.vertexId = vertexId;
  32077. this.triangleId = triangleId;
  32078. }
  32079. return Reference;
  32080. })();
  32081. BABYLON.Reference = Reference;
  32082. /**
  32083. * An implementation of the Quadratic Error simplification algorithm.
  32084. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  32085. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  32086. * @author RaananW
  32087. */
  32088. var QuadraticErrorSimplification = (function () {
  32089. function QuadraticErrorSimplification(_mesh) {
  32090. this._mesh = _mesh;
  32091. this.initialized = false;
  32092. this.syncIterations = 5000;
  32093. this.aggressiveness = 7;
  32094. this.decimationIterations = 100;
  32095. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  32096. }
  32097. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  32098. var _this = this;
  32099. this.initDecimatedMesh();
  32100. //iterating through the submeshes array, one after the other.
  32101. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  32102. _this.initWithMesh(loop.index, function () {
  32103. _this.runDecimation(settings, loop.index, function () {
  32104. loop.executeNext();
  32105. });
  32106. }, settings.optimizeMesh);
  32107. }, function () {
  32108. setTimeout(function () {
  32109. successCallback(_this._reconstructedMesh);
  32110. }, 0);
  32111. });
  32112. };
  32113. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  32114. var _this = this;
  32115. var gCount = 0;
  32116. triangle.vertices.forEach(function (vertex) {
  32117. var count = 0;
  32118. var vPos = vertex.position;
  32119. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  32120. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  32121. ++count;
  32122. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  32123. ++count;
  32124. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  32125. ++count;
  32126. if (count > 1) {
  32127. ++gCount;
  32128. }
  32129. ;
  32130. });
  32131. if (gCount > 1) {
  32132. console.log(triangle, gCount);
  32133. }
  32134. return gCount > 1;
  32135. };
  32136. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  32137. var _this = this;
  32138. var targetCount = ~~(this.triangles.length * settings.quality);
  32139. var deletedTriangles = 0;
  32140. var triangleCount = this.triangles.length;
  32141. var iterationFunction = function (iteration, callback) {
  32142. setTimeout(function () {
  32143. if (iteration % 5 === 0) {
  32144. _this.updateMesh(iteration === 0);
  32145. }
  32146. for (var i = 0; i < _this.triangles.length; ++i) {
  32147. _this.triangles[i].isDirty = false;
  32148. }
  32149. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  32150. var trianglesIterator = function (i) {
  32151. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  32152. var t = _this.triangles[tIdx];
  32153. if (!t)
  32154. return;
  32155. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  32156. return;
  32157. }
  32158. for (var j = 0; j < 3; ++j) {
  32159. if (t.error[j] < threshold) {
  32160. var deleted0 = [];
  32161. var deleted1 = [];
  32162. var v0 = t.vertices[j];
  32163. var v1 = t.vertices[(j + 1) % 3];
  32164. if (v0.isBorder !== v1.isBorder)
  32165. continue;
  32166. var p = BABYLON.Vector3.Zero();
  32167. var n = BABYLON.Vector3.Zero();
  32168. var uv = BABYLON.Vector2.Zero();
  32169. var color = new BABYLON.Color4(0, 0, 0, 1);
  32170. _this.calculateError(v0, v1, p, n, uv, color);
  32171. var delTr = [];
  32172. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  32173. continue;
  32174. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  32175. continue;
  32176. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  32177. continue;
  32178. var uniqueArray = [];
  32179. delTr.forEach(function (deletedT) {
  32180. if (uniqueArray.indexOf(deletedT) === -1) {
  32181. deletedT.deletePending = true;
  32182. uniqueArray.push(deletedT);
  32183. }
  32184. });
  32185. if (uniqueArray.length % 2 != 0) {
  32186. continue;
  32187. }
  32188. v0.q = v1.q.add(v0.q);
  32189. v0.updatePosition(p);
  32190. var tStart = _this.references.length;
  32191. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  32192. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  32193. var tCount = _this.references.length - tStart;
  32194. if (tCount <= v0.triangleCount) {
  32195. if (tCount) {
  32196. for (var c = 0; c < tCount; c++) {
  32197. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  32198. }
  32199. }
  32200. }
  32201. else {
  32202. v0.triangleStart = tStart;
  32203. }
  32204. v0.triangleCount = tCount;
  32205. break;
  32206. }
  32207. }
  32208. };
  32209. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  32210. }, 0);
  32211. };
  32212. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  32213. if (triangleCount - deletedTriangles <= targetCount)
  32214. loop.breakLoop();
  32215. else {
  32216. iterationFunction(loop.index, function () {
  32217. loop.executeNext();
  32218. });
  32219. }
  32220. }, function () {
  32221. setTimeout(function () {
  32222. //reconstruct this part of the mesh
  32223. _this.reconstructMesh(submeshIndex);
  32224. successCallback();
  32225. }, 0);
  32226. });
  32227. };
  32228. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  32229. var _this = this;
  32230. this.vertices = [];
  32231. this.triangles = [];
  32232. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32233. var indices = this._mesh.getIndices();
  32234. var submesh = this._mesh.subMeshes[submeshIndex];
  32235. var findInVertices = function (positionToSearch) {
  32236. if (optimizeMesh) {
  32237. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  32238. if (_this.vertices[ii].position.equals(positionToSearch)) {
  32239. return _this.vertices[ii];
  32240. }
  32241. }
  32242. }
  32243. return null;
  32244. };
  32245. var vertexReferences = [];
  32246. var vertexInit = function (i) {
  32247. var offset = i + submesh.verticesStart;
  32248. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  32249. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  32250. vertex.originalOffsets.push(offset);
  32251. if (vertex.id == _this.vertices.length) {
  32252. _this.vertices.push(vertex);
  32253. }
  32254. vertexReferences.push(vertex.id);
  32255. };
  32256. //var totalVertices = mesh.getTotalVertices();
  32257. var totalVertices = submesh.verticesCount;
  32258. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  32259. var indicesInit = function (i) {
  32260. var offset = (submesh.indexStart / 3) + i;
  32261. var pos = (offset * 3);
  32262. var i0 = indices[pos + 0];
  32263. var i1 = indices[pos + 1];
  32264. var i2 = indices[pos + 2];
  32265. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  32266. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  32267. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  32268. var triangle = new DecimationTriangle([v0, v1, v2]);
  32269. triangle.originalOffset = pos;
  32270. _this.triangles.push(triangle);
  32271. };
  32272. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  32273. _this.init(callback);
  32274. });
  32275. });
  32276. };
  32277. QuadraticErrorSimplification.prototype.init = function (callback) {
  32278. var _this = this;
  32279. var triangleInit1 = function (i) {
  32280. var t = _this.triangles[i];
  32281. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  32282. for (var j = 0; j < 3; j++) {
  32283. 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))));
  32284. }
  32285. };
  32286. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  32287. var triangleInit2 = function (i) {
  32288. var t = _this.triangles[i];
  32289. for (var j = 0; j < 3; ++j) {
  32290. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  32291. }
  32292. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32293. };
  32294. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  32295. _this.initialized = true;
  32296. callback();
  32297. });
  32298. });
  32299. };
  32300. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  32301. var newTriangles = [];
  32302. var i;
  32303. for (i = 0; i < this.vertices.length; ++i) {
  32304. this.vertices[i].triangleCount = 0;
  32305. }
  32306. var t;
  32307. var j;
  32308. for (i = 0; i < this.triangles.length; ++i) {
  32309. if (!this.triangles[i].deleted) {
  32310. t = this.triangles[i];
  32311. for (j = 0; j < 3; ++j) {
  32312. t.vertices[j].triangleCount = 1;
  32313. }
  32314. newTriangles.push(t);
  32315. }
  32316. }
  32317. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  32318. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  32319. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  32320. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  32321. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32322. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32323. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32324. var vertexCount = 0;
  32325. for (i = 0; i < this.vertices.length; ++i) {
  32326. var vertex = this.vertices[i];
  32327. vertex.id = vertexCount;
  32328. if (vertex.triangleCount) {
  32329. vertex.originalOffsets.forEach(function (originalOffset) {
  32330. newPositionData.push(vertex.position.x);
  32331. newPositionData.push(vertex.position.y);
  32332. newPositionData.push(vertex.position.z);
  32333. newNormalData.push(normalData[originalOffset * 3]);
  32334. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  32335. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  32336. if (uvs && uvs.length) {
  32337. newUVsData.push(uvs[(originalOffset * 2)]);
  32338. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  32339. }
  32340. else if (colorsData && colorsData.length) {
  32341. newColorsData.push(colorsData[(originalOffset * 4)]);
  32342. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  32343. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  32344. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  32345. }
  32346. ++vertexCount;
  32347. });
  32348. }
  32349. }
  32350. var startingIndex = this._reconstructedMesh.getTotalIndices();
  32351. var startingVertex = this._reconstructedMesh.getTotalVertices();
  32352. var submeshesArray = this._reconstructedMesh.subMeshes;
  32353. this._reconstructedMesh.subMeshes = [];
  32354. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  32355. var originalIndices = this._mesh.getIndices();
  32356. for (i = 0; i < newTriangles.length; ++i) {
  32357. var t = newTriangles[i];
  32358. //now get the new referencing point for each vertex
  32359. [0, 1, 2].forEach(function (idx) {
  32360. var id = originalIndices[t.originalOffset + idx];
  32361. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  32362. if (offset < 0)
  32363. offset = 0;
  32364. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  32365. });
  32366. }
  32367. //overwriting the old vertex buffers and indices.
  32368. this._reconstructedMesh.setIndices(newIndicesArray);
  32369. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  32370. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  32371. if (newUVsData.length > 0)
  32372. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  32373. if (newColorsData.length > 0)
  32374. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  32375. //create submesh
  32376. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  32377. if (submeshIndex > 0) {
  32378. this._reconstructedMesh.subMeshes = [];
  32379. submeshesArray.forEach(function (submesh) {
  32380. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  32381. });
  32382. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  32383. }
  32384. };
  32385. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  32386. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  32387. this._reconstructedMesh.material = this._mesh.material;
  32388. this._reconstructedMesh.parent = this._mesh.parent;
  32389. this._reconstructedMesh.isVisible = false;
  32390. };
  32391. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  32392. for (var i = 0; i < vertex1.triangleCount; ++i) {
  32393. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  32394. if (t.deleted)
  32395. continue;
  32396. var s = this.references[vertex1.triangleStart + i].vertexId;
  32397. var v1 = t.vertices[(s + 1) % 3];
  32398. var v2 = t.vertices[(s + 2) % 3];
  32399. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  32400. deletedArray[i] = true;
  32401. delTr.push(t);
  32402. continue;
  32403. }
  32404. var d1 = v1.position.subtract(point);
  32405. d1 = d1.normalize();
  32406. var d2 = v2.position.subtract(point);
  32407. d2 = d2.normalize();
  32408. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  32409. return true;
  32410. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  32411. deletedArray[i] = false;
  32412. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  32413. return true;
  32414. }
  32415. return false;
  32416. };
  32417. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32418. var newDeleted = deletedTriangles;
  32419. for (var i = 0; i < vertex.triangleCount; ++i) {
  32420. var ref = this.references[vertex.triangleStart + i];
  32421. var t = this.triangles[ref.triangleId];
  32422. if (t.deleted)
  32423. continue;
  32424. if (deletedArray[i] && t.deletePending) {
  32425. t.deleted = true;
  32426. newDeleted++;
  32427. continue;
  32428. }
  32429. t.vertices[ref.vertexId] = origVertex;
  32430. t.isDirty = true;
  32431. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32432. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32433. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32434. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32435. this.references.push(ref);
  32436. }
  32437. return newDeleted;
  32438. };
  32439. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32440. for (var i = 0; i < this.vertices.length; ++i) {
  32441. var vCount = [];
  32442. var vId = [];
  32443. var v = this.vertices[i];
  32444. var j;
  32445. for (j = 0; j < v.triangleCount; ++j) {
  32446. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32447. for (var ii = 0; ii < 3; ii++) {
  32448. var ofs = 0;
  32449. var vv = triangle.vertices[ii];
  32450. while (ofs < vCount.length) {
  32451. if (vId[ofs] === vv.id)
  32452. break;
  32453. ++ofs;
  32454. }
  32455. if (ofs === vCount.length) {
  32456. vCount.push(1);
  32457. vId.push(vv.id);
  32458. }
  32459. else {
  32460. vCount[ofs]++;
  32461. }
  32462. }
  32463. }
  32464. for (j = 0; j < vCount.length; ++j) {
  32465. if (vCount[j] === 1) {
  32466. this.vertices[vId[j]].isBorder = true;
  32467. }
  32468. else {
  32469. this.vertices[vId[j]].isBorder = false;
  32470. }
  32471. }
  32472. }
  32473. };
  32474. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32475. if (identifyBorders === void 0) { identifyBorders = false; }
  32476. var i;
  32477. if (!identifyBorders) {
  32478. var newTrianglesVector = [];
  32479. for (i = 0; i < this.triangles.length; ++i) {
  32480. if (!this.triangles[i].deleted) {
  32481. newTrianglesVector.push(this.triangles[i]);
  32482. }
  32483. }
  32484. this.triangles = newTrianglesVector;
  32485. }
  32486. for (i = 0; i < this.vertices.length; ++i) {
  32487. this.vertices[i].triangleCount = 0;
  32488. this.vertices[i].triangleStart = 0;
  32489. }
  32490. var t;
  32491. var j;
  32492. var v;
  32493. for (i = 0; i < this.triangles.length; ++i) {
  32494. t = this.triangles[i];
  32495. for (j = 0; j < 3; ++j) {
  32496. v = t.vertices[j];
  32497. v.triangleCount++;
  32498. }
  32499. }
  32500. var tStart = 0;
  32501. for (i = 0; i < this.vertices.length; ++i) {
  32502. this.vertices[i].triangleStart = tStart;
  32503. tStart += this.vertices[i].triangleCount;
  32504. this.vertices[i].triangleCount = 0;
  32505. }
  32506. var newReferences = new Array(this.triangles.length * 3);
  32507. for (i = 0; i < this.triangles.length; ++i) {
  32508. t = this.triangles[i];
  32509. for (j = 0; j < 3; ++j) {
  32510. v = t.vertices[j];
  32511. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32512. v.triangleCount++;
  32513. }
  32514. }
  32515. this.references = newReferences;
  32516. if (identifyBorders) {
  32517. this.identifyBorder();
  32518. }
  32519. };
  32520. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32521. var x = point.x;
  32522. var y = point.y;
  32523. var z = point.z;
  32524. 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
  32525. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32526. };
  32527. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32528. var q = vertex1.q.add(vertex2.q);
  32529. var border = vertex1.isBorder && vertex2.isBorder;
  32530. var error = 0;
  32531. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32532. if (qDet !== 0 && !border) {
  32533. if (!pointResult) {
  32534. pointResult = BABYLON.Vector3.Zero();
  32535. }
  32536. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32537. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32538. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32539. error = this.vertexError(q, pointResult);
  32540. }
  32541. else {
  32542. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32543. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32544. var error1 = this.vertexError(q, vertex1.position);
  32545. var error2 = this.vertexError(q, vertex2.position);
  32546. var error3 = this.vertexError(q, p3);
  32547. error = Math.min(error1, error2, error3);
  32548. if (error === error1) {
  32549. if (pointResult) {
  32550. pointResult.copyFrom(vertex1.position);
  32551. }
  32552. }
  32553. else if (error === error2) {
  32554. if (pointResult) {
  32555. pointResult.copyFrom(vertex2.position);
  32556. }
  32557. }
  32558. else {
  32559. if (pointResult) {
  32560. pointResult.copyFrom(p3);
  32561. }
  32562. }
  32563. }
  32564. return error;
  32565. };
  32566. return QuadraticErrorSimplification;
  32567. })();
  32568. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32569. })(BABYLON || (BABYLON = {}));
  32570. var BABYLON;
  32571. (function (BABYLON) {
  32572. var Analyser = (function () {
  32573. function Analyser(scene) {
  32574. this.SMOOTHING = 0.75;
  32575. this.FFT_SIZE = 512;
  32576. this.BARGRAPHAMPLITUDE = 256;
  32577. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32578. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32579. this._scene = scene;
  32580. this._audioEngine = BABYLON.Engine.audioEngine;
  32581. if (this._audioEngine.canUseWebAudio) {
  32582. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32583. this._webAudioAnalyser.minDecibels = -140;
  32584. this._webAudioAnalyser.maxDecibels = 0;
  32585. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32586. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32587. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32588. }
  32589. }
  32590. Analyser.prototype.getFrequencyBinCount = function () {
  32591. if (this._audioEngine.canUseWebAudio) {
  32592. return this._webAudioAnalyser.frequencyBinCount;
  32593. }
  32594. else {
  32595. return 0;
  32596. }
  32597. };
  32598. Analyser.prototype.getByteFrequencyData = function () {
  32599. if (this._audioEngine.canUseWebAudio) {
  32600. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32601. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32602. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32603. }
  32604. return this._byteFreqs;
  32605. };
  32606. Analyser.prototype.getByteTimeDomainData = function () {
  32607. if (this._audioEngine.canUseWebAudio) {
  32608. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32609. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32610. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32611. }
  32612. return this._byteTime;
  32613. };
  32614. Analyser.prototype.getFloatFrequencyData = function () {
  32615. if (this._audioEngine.canUseWebAudio) {
  32616. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32617. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32618. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32619. }
  32620. return this._floatFreqs;
  32621. };
  32622. Analyser.prototype.drawDebugCanvas = function () {
  32623. var _this = this;
  32624. if (this._audioEngine.canUseWebAudio) {
  32625. if (!this._debugCanvas) {
  32626. this._debugCanvas = document.createElement("canvas");
  32627. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32628. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32629. this._debugCanvas.style.position = "absolute";
  32630. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32631. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32632. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32633. document.body.appendChild(this._debugCanvas);
  32634. this._registerFunc = function () {
  32635. _this.drawDebugCanvas();
  32636. };
  32637. this._scene.registerBeforeRender(this._registerFunc);
  32638. }
  32639. if (this._registerFunc) {
  32640. var workingArray = this.getByteFrequencyData();
  32641. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32642. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32643. // Draw the frequency domain chart.
  32644. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32645. var value = workingArray[i];
  32646. var percent = value / this.BARGRAPHAMPLITUDE;
  32647. var height = this.DEBUGCANVASSIZE.height * percent;
  32648. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32649. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32650. var hue = i / this.getFrequencyBinCount() * 360;
  32651. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32652. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32653. }
  32654. }
  32655. }
  32656. };
  32657. Analyser.prototype.stopDebugCanvas = function () {
  32658. if (this._debugCanvas) {
  32659. this._scene.unregisterBeforeRender(this._registerFunc);
  32660. this._registerFunc = null;
  32661. document.body.removeChild(this._debugCanvas);
  32662. this._debugCanvas = null;
  32663. this._debugCanvasContext = null;
  32664. }
  32665. };
  32666. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32667. if (this._audioEngine.canUseWebAudio) {
  32668. inputAudioNode.connect(this._webAudioAnalyser);
  32669. this._webAudioAnalyser.connect(outputAudioNode);
  32670. }
  32671. };
  32672. Analyser.prototype.dispose = function () {
  32673. if (this._audioEngine.canUseWebAudio) {
  32674. this._webAudioAnalyser.disconnect();
  32675. }
  32676. };
  32677. return Analyser;
  32678. })();
  32679. BABYLON.Analyser = Analyser;
  32680. })(BABYLON || (BABYLON = {}));
  32681. var BABYLON;
  32682. (function (BABYLON) {
  32683. var DepthRenderer = (function () {
  32684. function DepthRenderer(scene, type) {
  32685. var _this = this;
  32686. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32687. this._viewMatrix = BABYLON.Matrix.Zero();
  32688. this._projectionMatrix = BABYLON.Matrix.Zero();
  32689. this._transformMatrix = BABYLON.Matrix.Zero();
  32690. this._worldViewProjection = BABYLON.Matrix.Zero();
  32691. this._scene = scene;
  32692. var engine = scene.getEngine();
  32693. // Render target
  32694. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32695. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32696. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32697. this._depthMap.refreshRate = 1;
  32698. this._depthMap.renderParticles = false;
  32699. this._depthMap.renderList = null;
  32700. // set default depth value to 1.0 (far away)
  32701. this._depthMap.onClear = function (engine) {
  32702. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32703. };
  32704. // Custom render function
  32705. var renderSubMesh = function (subMesh) {
  32706. var mesh = subMesh.getRenderingMesh();
  32707. var scene = _this._scene;
  32708. var engine = scene.getEngine();
  32709. // Culling
  32710. engine.setState(subMesh.getMaterial().backFaceCulling);
  32711. // Managing instances
  32712. var batch = mesh._getInstancesRenderList(subMesh._id);
  32713. if (batch.mustReturn) {
  32714. return;
  32715. }
  32716. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32717. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32718. engine.enableEffect(_this._effect);
  32719. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32720. var material = subMesh.getMaterial();
  32721. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32722. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32723. // Alpha test
  32724. if (material && material.needAlphaTesting()) {
  32725. var alphaTexture = material.getAlphaTestTexture();
  32726. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32727. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32728. }
  32729. // Bones
  32730. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32731. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32732. }
  32733. // Draw
  32734. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32735. }
  32736. };
  32737. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32738. var index;
  32739. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32740. renderSubMesh(opaqueSubMeshes.data[index]);
  32741. }
  32742. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32743. renderSubMesh(alphaTestSubMeshes.data[index]);
  32744. }
  32745. };
  32746. }
  32747. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32748. var defines = [];
  32749. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32750. var mesh = subMesh.getMesh();
  32751. var scene = mesh.getScene();
  32752. var material = subMesh.getMaterial();
  32753. // Alpha test
  32754. if (material && material.needAlphaTesting()) {
  32755. defines.push("#define ALPHATEST");
  32756. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32757. attribs.push(BABYLON.VertexBuffer.UVKind);
  32758. defines.push("#define UV1");
  32759. }
  32760. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32761. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32762. defines.push("#define UV2");
  32763. }
  32764. }
  32765. // Bones
  32766. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32767. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32768. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32769. defines.push("#define BONES");
  32770. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32771. }
  32772. // Instances
  32773. if (useInstances) {
  32774. defines.push("#define INSTANCES");
  32775. attribs.push("world0");
  32776. attribs.push("world1");
  32777. attribs.push("world2");
  32778. attribs.push("world3");
  32779. }
  32780. // Get correct effect
  32781. var join = defines.join("\n");
  32782. if (this._cachedDefines !== join) {
  32783. this._cachedDefines = join;
  32784. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32785. }
  32786. return this._effect.isReady();
  32787. };
  32788. DepthRenderer.prototype.getDepthMap = function () {
  32789. return this._depthMap;
  32790. };
  32791. // Methods
  32792. DepthRenderer.prototype.dispose = function () {
  32793. this._depthMap.dispose();
  32794. };
  32795. return DepthRenderer;
  32796. })();
  32797. BABYLON.DepthRenderer = DepthRenderer;
  32798. })(BABYLON || (BABYLON = {}));
  32799. var BABYLON;
  32800. (function (BABYLON) {
  32801. var SSAORenderingPipeline = (function (_super) {
  32802. __extends(SSAORenderingPipeline, _super);
  32803. /**
  32804. * @constructor
  32805. * @param {string} name - The rendering pipeline name
  32806. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32807. * @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 }
  32808. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32809. */
  32810. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32811. var _this = this;
  32812. _super.call(this, scene.getEngine(), name);
  32813. // Members
  32814. /**
  32815. * The PassPostProcess id in the pipeline that contains the original scene color
  32816. * @type {string}
  32817. */
  32818. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32819. /**
  32820. * The SSAO PostProcess id in the pipeline
  32821. * @type {string}
  32822. */
  32823. this.SSAORenderEffect = "SSAORenderEffect";
  32824. /**
  32825. * The horizontal blur PostProcess id in the pipeline
  32826. * @type {string}
  32827. */
  32828. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32829. /**
  32830. * The vertical blur PostProcess id in the pipeline
  32831. * @type {string}
  32832. */
  32833. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32834. /**
  32835. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32836. * @type {string}
  32837. */
  32838. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32839. /**
  32840. * The output strength of the SSAO post-process. Default value is 1.0.
  32841. * @type {number}
  32842. */
  32843. this.totalStrength = 1.0;
  32844. /**
  32845. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32846. * @type {number}
  32847. */
  32848. this.radius = 0.0002;
  32849. /**
  32850. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32851. * Must not be equal to fallOff and superior to fallOff.
  32852. * Default value is 0.0075
  32853. * @type {number}
  32854. */
  32855. this.area = 0.0075;
  32856. /**
  32857. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32858. * Must not be equal to area and inferior to area.
  32859. * Default value is 0.0002
  32860. * @type {number}
  32861. */
  32862. this.fallOff = 0.0002;
  32863. this._firstUpdate = true;
  32864. this._scene = scene;
  32865. // Set up assets
  32866. this._createRandomTexture();
  32867. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32868. var ssaoRatio = ratio.ssaoRatio || ratio;
  32869. var combineRatio = ratio.combineRatio || ratio;
  32870. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32871. this._createSSAOPostProcess(ssaoRatio);
  32872. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32873. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32874. this._createSSAOCombinePostProcess(combineRatio);
  32875. // Set up pipeline
  32876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32877. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32878. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32879. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32880. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32881. // Finish
  32882. scene.postProcessRenderPipelineManager.addPipeline(this);
  32883. if (cameras)
  32884. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32885. }
  32886. // Public Methods
  32887. /**
  32888. * Returns the horizontal blur PostProcess
  32889. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32890. */
  32891. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32892. return this._blurHPostProcess;
  32893. };
  32894. /**
  32895. * Returns the vertical blur PostProcess
  32896. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32897. */
  32898. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32899. return this._blurVPostProcess;
  32900. };
  32901. /**
  32902. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32903. */
  32904. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32905. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32906. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32907. this._originalColorPostProcess = undefined;
  32908. this._ssaoPostProcess = undefined;
  32909. this._blurHPostProcess = undefined;
  32910. this._blurVPostProcess = undefined;
  32911. this._ssaoCombinePostProcess = undefined;
  32912. this._randomTexture.dispose();
  32913. if (disableDepthRender)
  32914. this._scene.disableDepthRenderer();
  32915. };
  32916. // Private Methods
  32917. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32918. var _this = this;
  32919. var sampleSphere = [
  32920. 0.5381, 0.1856, -0.4319,
  32921. 0.1379, 0.2486, 0.4430,
  32922. 0.3371, 0.5679, -0.0057,
  32923. -0.6999, -0.0451, -0.0019,
  32924. 0.0689, -0.1598, -0.8547,
  32925. 0.0560, 0.0069, -0.1843,
  32926. -0.0146, 0.1402, 0.0762,
  32927. 0.0100, -0.1924, -0.0344,
  32928. -0.3577, -0.5301, -0.4358,
  32929. -0.3169, 0.1063, 0.0158,
  32930. 0.0103, -0.5869, 0.0046,
  32931. -0.0897, -0.4940, 0.3287,
  32932. 0.7119, -0.0154, -0.0918,
  32933. -0.0533, 0.0596, -0.5411,
  32934. 0.0352, -0.0631, 0.5460,
  32935. -0.4776, 0.2847, -0.0271
  32936. ];
  32937. var samplesFactor = 1.0 / 16.0;
  32938. 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);
  32939. this._ssaoPostProcess.onApply = function (effect) {
  32940. if (_this._firstUpdate) {
  32941. effect.setArray3("sampleSphere", sampleSphere);
  32942. effect.setFloat("samplesFactor", samplesFactor);
  32943. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32944. _this._firstUpdate = false;
  32945. }
  32946. effect.setFloat("totalStrength", _this.totalStrength);
  32947. effect.setFloat("radius", _this.radius);
  32948. effect.setFloat("area", _this.area);
  32949. effect.setFloat("fallOff", _this.fallOff);
  32950. effect.setTexture("textureSampler", _this._depthTexture);
  32951. effect.setTexture("randomSampler", _this._randomTexture);
  32952. };
  32953. };
  32954. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32955. var _this = this;
  32956. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32957. this._ssaoCombinePostProcess.onApply = function (effect) {
  32958. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32959. };
  32960. };
  32961. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32962. var size = 512;
  32963. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32964. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32965. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32966. var context = this._randomTexture.getContext();
  32967. var rand = function (min, max) {
  32968. return Math.random() * (max - min) + min;
  32969. };
  32970. for (var x = 0; x < size; x++) {
  32971. for (var y = 0; y < size; y++) {
  32972. var randVector = BABYLON.Vector3.Zero();
  32973. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32974. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32975. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32976. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32977. context.fillRect(x, y, 1, 1);
  32978. }
  32979. }
  32980. this._randomTexture.update(false);
  32981. };
  32982. return SSAORenderingPipeline;
  32983. })(BABYLON.PostProcessRenderPipeline);
  32984. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32985. })(BABYLON || (BABYLON = {}));
  32986. var BABYLON;
  32987. (function (BABYLON) {
  32988. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32989. var VolumetricLightScatteringPostProcess = (function (_super) {
  32990. __extends(VolumetricLightScatteringPostProcess, _super);
  32991. /**
  32992. * @constructor
  32993. * @param {string} name - The post-process name
  32994. * @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)
  32995. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32996. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32997. * @param {number} samples - The post-process quality, default 100
  32998. * @param {number} samplingMode - The post-process filtering mode
  32999. * @param {BABYLON.Engine} engine - The babylon engine
  33000. * @param {boolean} reusable - If the post-process is reusable
  33001. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  33002. */
  33003. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  33004. var _this = this;
  33005. if (samples === void 0) { samples = 100; }
  33006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33007. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  33008. this._screenCoordinates = BABYLON.Vector2.Zero();
  33009. /**
  33010. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  33011. * @type {boolean}
  33012. */
  33013. this.useCustomMeshPosition = false;
  33014. /**
  33015. * If the post-process should inverse the light scattering direction
  33016. * @type {boolean}
  33017. */
  33018. this.invert = true;
  33019. /**
  33020. * Set to true to use the diffuseColor instead of the diffuseTexture
  33021. * @type {boolean}
  33022. */
  33023. this.useDiffuseColor = false;
  33024. /**
  33025. * Array containing the excluded meshes not rendered in the internal pass
  33026. */
  33027. this.excludedMeshes = new Array();
  33028. /**
  33029. * Controls the overall intensity of the post-process
  33030. * @type {number}
  33031. */
  33032. this.exposure = 0.3;
  33033. /**
  33034. * Dissipates each sample's contribution in range [0, 1]
  33035. * @type {number}
  33036. */
  33037. this.decay = 0.96815;
  33038. /**
  33039. * Controls the overall intensity of each sample
  33040. * @type {number}
  33041. */
  33042. this.weight = 0.58767;
  33043. /**
  33044. * Controls the density of each sample
  33045. * @type {number}
  33046. */
  33047. this.density = 0.926;
  33048. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  33049. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  33050. // Configure mesh
  33051. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  33052. // Configure
  33053. this._createPass(scene, ratio.passRatio || ratio);
  33054. this.onApply = function (effect) {
  33055. _this._updateMeshScreenCoordinates(scene);
  33056. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  33057. effect.setFloat("exposure", _this.exposure);
  33058. effect.setFloat("decay", _this.decay);
  33059. effect.setFloat("weight", _this.weight);
  33060. effect.setFloat("density", _this.density);
  33061. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  33062. };
  33063. }
  33064. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  33065. var mesh = subMesh.getMesh();
  33066. var defines = [];
  33067. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33068. var material = subMesh.getMaterial();
  33069. var needUV = false;
  33070. // Render this.mesh as default
  33071. if (mesh === this.mesh) {
  33072. if (this.useDiffuseColor) {
  33073. defines.push("#define DIFFUSE_COLOR_RENDER");
  33074. }
  33075. else if (material) {
  33076. if (material.diffuseTexture !== undefined) {
  33077. defines.push("#define BASIC_RENDER");
  33078. }
  33079. else {
  33080. defines.push("#define DIFFUSE_COLOR_RENDER");
  33081. }
  33082. }
  33083. defines.push("#define NEED_UV");
  33084. needUV = true;
  33085. }
  33086. // Alpha test
  33087. if (material) {
  33088. if (material.needAlphaTesting()) {
  33089. defines.push("#define ALPHATEST");
  33090. }
  33091. if (material.opacityTexture !== undefined) {
  33092. defines.push("#define OPACITY");
  33093. if (material.opacityTexture.getAlphaFromRGB) {
  33094. defines.push("#define OPACITYRGB");
  33095. }
  33096. if (!needUV) {
  33097. defines.push("#define NEED_UV");
  33098. }
  33099. }
  33100. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33101. attribs.push(BABYLON.VertexBuffer.UVKind);
  33102. defines.push("#define UV1");
  33103. }
  33104. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33105. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33106. defines.push("#define UV2");
  33107. }
  33108. }
  33109. // Bones
  33110. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33111. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33112. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33113. defines.push("#define BONES");
  33114. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33115. }
  33116. // Instances
  33117. if (useInstances) {
  33118. defines.push("#define INSTANCES");
  33119. attribs.push("world0");
  33120. attribs.push("world1");
  33121. attribs.push("world2");
  33122. attribs.push("world3");
  33123. }
  33124. // Get correct effect
  33125. var join = defines.join("\n");
  33126. if (this._cachedDefines !== join) {
  33127. this._cachedDefines = join;
  33128. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  33129. }
  33130. return this._volumetricLightScatteringPass.isReady();
  33131. };
  33132. /**
  33133. * Sets the new light position for light scattering effect
  33134. * @param {BABYLON.Vector3} The new custom light position
  33135. */
  33136. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  33137. this._customMeshPosition = position;
  33138. };
  33139. /**
  33140. * Returns the light position for light scattering effect
  33141. * @return {BABYLON.Vector3} The custom light position
  33142. */
  33143. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  33144. return this._customMeshPosition;
  33145. };
  33146. /**
  33147. * Disposes the internal assets and detaches the post-process from the camera
  33148. */
  33149. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  33150. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  33151. if (rttIndex !== -1) {
  33152. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  33153. }
  33154. this._volumetricLightScatteringRTT.dispose();
  33155. _super.prototype.dispose.call(this, camera);
  33156. };
  33157. /**
  33158. * Returns the render target texture used by the post-process
  33159. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  33160. */
  33161. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  33162. return this._volumetricLightScatteringRTT;
  33163. };
  33164. // Private methods
  33165. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  33166. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  33167. return true;
  33168. }
  33169. return false;
  33170. };
  33171. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  33172. var _this = this;
  33173. var engine = scene.getEngine();
  33174. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  33175. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33176. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33177. this._volumetricLightScatteringRTT.renderList = null;
  33178. this._volumetricLightScatteringRTT.renderParticles = false;
  33179. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  33180. // Custom render function for submeshes
  33181. var renderSubMesh = function (subMesh) {
  33182. var mesh = subMesh.getRenderingMesh();
  33183. if (_this._meshExcluded(mesh)) {
  33184. return;
  33185. }
  33186. var scene = mesh.getScene();
  33187. var engine = scene.getEngine();
  33188. // Culling
  33189. engine.setState(subMesh.getMaterial().backFaceCulling);
  33190. // Managing instances
  33191. var batch = mesh._getInstancesRenderList(subMesh._id);
  33192. if (batch.mustReturn) {
  33193. return;
  33194. }
  33195. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33196. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33197. engine.enableEffect(_this._volumetricLightScatteringPass);
  33198. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  33199. var material = subMesh.getMaterial();
  33200. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  33201. // Alpha test
  33202. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  33203. var alphaTexture = material.getAlphaTestTexture();
  33204. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  33205. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  33206. }
  33207. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  33208. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  33209. if (alphaTexture) {
  33210. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33211. }
  33212. }
  33213. if (material.opacityTexture !== undefined) {
  33214. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  33215. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  33216. }
  33217. }
  33218. // Bones
  33219. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33220. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33221. }
  33222. // Draw
  33223. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  33224. }
  33225. };
  33226. // Render target texture callbacks
  33227. var savedSceneClearColor;
  33228. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  33229. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  33230. savedSceneClearColor = scene.clearColor;
  33231. scene.clearColor = sceneClearColor;
  33232. };
  33233. this._volumetricLightScatteringRTT.onAfterRender = function () {
  33234. scene.clearColor = savedSceneClearColor;
  33235. };
  33236. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33237. var engine = scene.getEngine();
  33238. var index;
  33239. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33240. renderSubMesh(opaqueSubMeshes.data[index]);
  33241. }
  33242. engine.setAlphaTesting(true);
  33243. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33244. renderSubMesh(alphaTestSubMeshes.data[index]);
  33245. }
  33246. engine.setAlphaTesting(false);
  33247. if (transparentSubMeshes.length) {
  33248. // Sort sub meshes
  33249. for (index = 0; index < transparentSubMeshes.length; index++) {
  33250. var submesh = transparentSubMeshes.data[index];
  33251. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  33252. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  33253. }
  33254. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  33255. sortedArray.sort(function (a, b) {
  33256. // Alpha index first
  33257. if (a._alphaIndex > b._alphaIndex) {
  33258. return 1;
  33259. }
  33260. if (a._alphaIndex < b._alphaIndex) {
  33261. return -1;
  33262. }
  33263. // Then distance to camera
  33264. if (a._distanceToCamera < b._distanceToCamera) {
  33265. return 1;
  33266. }
  33267. if (a._distanceToCamera > b._distanceToCamera) {
  33268. return -1;
  33269. }
  33270. return 0;
  33271. });
  33272. // Render sub meshes
  33273. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33274. for (index = 0; index < sortedArray.length; index++) {
  33275. renderSubMesh(sortedArray[index]);
  33276. }
  33277. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33278. }
  33279. };
  33280. };
  33281. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  33282. var transform = scene.getTransformMatrix();
  33283. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  33284. this._screenCoordinates.x = pos.x / this._viewPort.width;
  33285. this._screenCoordinates.y = pos.y / this._viewPort.height;
  33286. if (this.invert)
  33287. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  33288. };
  33289. // Static methods
  33290. /**
  33291. * Creates a default mesh for the Volumeric Light Scattering post-process
  33292. * @param {string} The mesh name
  33293. * @param {BABYLON.Scene} The scene where to create the mesh
  33294. * @return {BABYLON.Mesh} the default mesh
  33295. */
  33296. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  33297. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  33298. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  33299. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  33300. return mesh;
  33301. };
  33302. return VolumetricLightScatteringPostProcess;
  33303. })(BABYLON.PostProcess);
  33304. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  33305. })(BABYLON || (BABYLON = {}));
  33306. var BABYLON;
  33307. (function (BABYLON) {
  33308. var LensRenderingPipeline = (function (_super) {
  33309. __extends(LensRenderingPipeline, _super);
  33310. /**
  33311. * @constructor
  33312. *
  33313. * Effect parameters are as follow:
  33314. * {
  33315. * chromatic_aberration: number; // from 0 to x (1 for realism)
  33316. * edge_blur: number; // from 0 to x (1 for realism)
  33317. * distortion: number; // from 0 to x (1 for realism)
  33318. * grain_amount: number; // from 0 to 1
  33319. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  33320. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  33321. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  33322. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  33323. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  33324. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  33325. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  33326. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  33327. * }
  33328. * Note: if an effect parameter is unset, effect is disabled
  33329. *
  33330. * @param {string} name - The rendering pipeline name
  33331. * @param {object} parameters - An object containing all parameters (see above)
  33332. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33333. * @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)
  33334. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33335. */
  33336. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  33337. var _this = this;
  33338. if (ratio === void 0) { ratio = 1.0; }
  33339. _super.call(this, scene.getEngine(), name);
  33340. // Lens effects can be of the following:
  33341. // - chromatic aberration (slight shift of RGB colors)
  33342. // - blur on the edge of the lens
  33343. // - lens distortion
  33344. // - depth-of-field blur & highlights enhancing
  33345. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  33346. // - grain effect (noise or custom texture)
  33347. // Two additional texture samplers are needed:
  33348. // - depth map (for depth-of-field)
  33349. // - grain texture
  33350. /**
  33351. * The chromatic aberration PostProcess id in the pipeline
  33352. * @type {string}
  33353. */
  33354. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  33355. /**
  33356. * The highlights enhancing PostProcess id in the pipeline
  33357. * @type {string}
  33358. */
  33359. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  33360. /**
  33361. * The depth-of-field PostProcess id in the pipeline
  33362. * @type {string}
  33363. */
  33364. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  33365. this._scene = scene;
  33366. // Fetch texture samplers
  33367. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33368. if (parameters.grain_texture) {
  33369. this._grainTexture = parameters.grain_texture;
  33370. }
  33371. else {
  33372. this._createGrainTexture();
  33373. }
  33374. // save parameters
  33375. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  33376. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  33377. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  33378. this._distortion = parameters.distortion ? parameters.distortion : 0;
  33379. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  33380. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  33381. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  33382. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  33383. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  33384. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  33385. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  33386. // Create effects
  33387. this._createChromaticAberrationPostProcess(ratio);
  33388. this._createHighlightsPostProcess(ratio);
  33389. this._createDepthOfFieldPostProcess(ratio / 4);
  33390. // Set up pipeline
  33391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  33392. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  33393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  33394. if (this._highlightsGain == -1) {
  33395. this._disableEffect(this.HighlightsEnhancingEffect, null);
  33396. }
  33397. // Finish
  33398. scene.postProcessRenderPipelineManager.addPipeline(this);
  33399. if (cameras) {
  33400. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33401. }
  33402. }
  33403. // public methods (self explanatory)
  33404. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  33405. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  33406. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  33407. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  33408. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  33409. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  33410. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  33411. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  33412. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  33413. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  33414. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  33415. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  33416. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  33417. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  33418. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  33419. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  33420. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  33421. this._highlightsGain = amount;
  33422. };
  33423. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  33424. if (this._highlightsGain == -1) {
  33425. this._highlightsGain = 1.0;
  33426. }
  33427. this._highlightsThreshold = amount;
  33428. };
  33429. LensRenderingPipeline.prototype.disableHighlights = function () {
  33430. this._highlightsGain = -1;
  33431. };
  33432. /**
  33433. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  33434. */
  33435. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33436. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33437. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33438. this._chromaticAberrationPostProcess = undefined;
  33439. this._highlightsPostProcess = undefined;
  33440. this._depthOfFieldPostProcess = undefined;
  33441. this._grainTexture.dispose();
  33442. if (disableDepthRender)
  33443. this._scene.disableDepthRenderer();
  33444. };
  33445. // colors shifting and distortion
  33446. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  33447. var _this = this;
  33448. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  33449. [], // samplers
  33450. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33451. this._chromaticAberrationPostProcess.onApply = function (effect) {
  33452. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  33453. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33454. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33455. };
  33456. };
  33457. // highlights enhancing
  33458. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  33459. var _this = this;
  33460. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  33461. [], // samplers
  33462. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33463. this._highlightsPostProcess.onApply = function (effect) {
  33464. effect.setFloat('gain', _this._highlightsGain);
  33465. effect.setFloat('threshold', _this._highlightsThreshold);
  33466. effect.setBool('pentagon', _this._dofPentagon);
  33467. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  33468. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33469. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33470. };
  33471. };
  33472. // colors shifting and distortion
  33473. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  33474. var _this = this;
  33475. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  33476. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  33477. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  33478. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33479. this._depthOfFieldPostProcess.onApply = function (effect) {
  33480. effect.setTexture("depthSampler", _this._depthTexture);
  33481. effect.setTexture("grainSampler", _this._grainTexture);
  33482. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  33483. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  33484. effect.setFloat('grain_amount', _this._grainAmount);
  33485. effect.setBool('blur_noise', _this._blurNoise);
  33486. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33487. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33488. effect.setFloat('distortion', _this._distortion);
  33489. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33490. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33491. effect.setFloat('aperture', _this._dofAperture);
  33492. effect.setFloat('darken', _this._dofDarken);
  33493. effect.setFloat('edge_blur', _this._edgeBlur);
  33494. effect.setBool('highlights', (_this._highlightsGain != -1));
  33495. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33496. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33497. };
  33498. };
  33499. // creates a black and white random noise texture, 512x512
  33500. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33501. var size = 512;
  33502. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33503. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33504. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33505. var context = this._grainTexture.getContext();
  33506. var rand = function (min, max) {
  33507. return Math.random() * (max - min) + min;
  33508. };
  33509. var value;
  33510. for (var x = 0; x < size; x++) {
  33511. for (var y = 0; y < size; y++) {
  33512. value = Math.floor(rand(0.42, 0.58) * 255);
  33513. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33514. context.fillRect(x, y, 1, 1);
  33515. }
  33516. }
  33517. this._grainTexture.update(false);
  33518. };
  33519. return LensRenderingPipeline;
  33520. })(BABYLON.PostProcessRenderPipeline);
  33521. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33522. })(BABYLON || (BABYLON = {}));
  33523. //
  33524. // This post-process allows the modification of rendered colors by using
  33525. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33526. //
  33527. // The object needs to be provided an url to a texture containing the color
  33528. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33529. // Use an image editing software to tweak the LUT to match your needs.
  33530. //
  33531. // For an example of a color LUT, see here:
  33532. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33533. // For explanations on color grading, see here:
  33534. // http://udn.epicgames.com/Three/ColorGrading.html
  33535. //
  33536. var BABYLON;
  33537. (function (BABYLON) {
  33538. var ColorCorrectionPostProcess = (function (_super) {
  33539. __extends(ColorCorrectionPostProcess, _super);
  33540. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33541. var _this = this;
  33542. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33543. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33544. this._colorTableTexture.anisotropicFilteringLevel = 1;
  33545. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33546. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33547. this.onApply = function (effect) {
  33548. effect.setTexture("colorTable", _this._colorTableTexture);
  33549. };
  33550. }
  33551. return ColorCorrectionPostProcess;
  33552. })(BABYLON.PostProcess);
  33553. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  33554. })(BABYLON || (BABYLON = {}));
  33555. var BABYLON;
  33556. (function (BABYLON) {
  33557. var AnaglyphFreeCamera = (function (_super) {
  33558. __extends(AnaglyphFreeCamera, _super);
  33559. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  33560. _super.call(this, name, position, scene);
  33561. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33562. }
  33563. return AnaglyphFreeCamera;
  33564. })(BABYLON.FreeCamera);
  33565. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33566. var AnaglyphArcRotateCamera = (function (_super) {
  33567. __extends(AnaglyphArcRotateCamera, _super);
  33568. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33569. _super.call(this, name, alpha, beta, radius, target, scene);
  33570. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33571. }
  33572. return AnaglyphArcRotateCamera;
  33573. })(BABYLON.ArcRotateCamera);
  33574. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33575. var AnaglyphGamepadCamera = (function (_super) {
  33576. __extends(AnaglyphGamepadCamera, _super);
  33577. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33578. _super.call(this, name, position, scene);
  33579. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33580. }
  33581. return AnaglyphGamepadCamera;
  33582. })(BABYLON.GamepadCamera);
  33583. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33584. var StereoscopicFreeCamera = (function (_super) {
  33585. __extends(StereoscopicFreeCamera, _super);
  33586. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33587. _super.call(this, name, position, scene);
  33588. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33589. }
  33590. return StereoscopicFreeCamera;
  33591. })(BABYLON.FreeCamera);
  33592. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33593. var StereoscopicArcRotateCamera = (function (_super) {
  33594. __extends(StereoscopicArcRotateCamera, _super);
  33595. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33596. _super.call(this, name, alpha, beta, radius, target, scene);
  33597. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33598. }
  33599. return StereoscopicArcRotateCamera;
  33600. })(BABYLON.ArcRotateCamera);
  33601. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33602. var StereoscopicGamepadCamera = (function (_super) {
  33603. __extends(StereoscopicGamepadCamera, _super);
  33604. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33605. _super.call(this, name, position, scene);
  33606. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33607. }
  33608. return StereoscopicGamepadCamera;
  33609. })(BABYLON.GamepadCamera);
  33610. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33611. })(BABYLON || (BABYLON = {}));
  33612. var BABYLON;
  33613. (function (BABYLON) {
  33614. var HDRRenderingPipeline = (function (_super) {
  33615. __extends(HDRRenderingPipeline, _super);
  33616. /**
  33617. * @constructor
  33618. * @param {string} name - The rendering pipeline name
  33619. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33620. * @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)
  33621. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33622. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33623. */
  33624. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33625. var _this = this;
  33626. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33627. _super.call(this, scene.getEngine(), name);
  33628. /**
  33629. * Public members
  33630. */
  33631. // Gaussian Blur
  33632. /**
  33633. * Gaussian blur coefficient
  33634. * @type {number}
  33635. */
  33636. this.gaussCoeff = 0.3;
  33637. /**
  33638. * Gaussian blur mean
  33639. * @type {number}
  33640. */
  33641. this.gaussMean = 1.0;
  33642. /**
  33643. * Gaussian blur standard deviation
  33644. * @type {number}
  33645. */
  33646. this.gaussStandDev = 0.8;
  33647. // HDR
  33648. /**
  33649. * Exposure, controls the overall intensity of the pipeline
  33650. * @type {number}
  33651. */
  33652. this.exposure = 1.0;
  33653. /**
  33654. * Minimum luminance that the post-process can output. Luminance is >= 0
  33655. * @type {number}
  33656. */
  33657. this.minimumLuminance = 1.0;
  33658. /**
  33659. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33660. * @type {number}
  33661. */
  33662. this.maximumLuminance = 1e20;
  33663. /**
  33664. * Increase rate for luminance: eye adaptation speed to dark
  33665. * @type {number}
  33666. */
  33667. this.luminanceIncreaserate = 0.5;
  33668. /**
  33669. * Decrease rate for luminance: eye adaptation speed to bright
  33670. * @type {number}
  33671. */
  33672. this.luminanceDecreaseRate = 0.5;
  33673. // Bright pass
  33674. /**
  33675. * Minimum luminance needed to compute HDR
  33676. * @type {number}
  33677. */
  33678. this.brightThreshold = 0.8;
  33679. this._needUpdate = true;
  33680. this._scene = scene;
  33681. // Bright pass
  33682. this._createBrightPassPostProcess(scene, ratio);
  33683. // Down sample X4
  33684. this._createDownSampleX4PostProcess(scene, ratio);
  33685. // Create gaussian blur post-processes
  33686. this._createGaussianBlurPostProcess(scene, ratio);
  33687. // Texture adder
  33688. this._createTextureAdderPostProcess(scene, ratio);
  33689. // Luminance generator
  33690. this._createLuminanceGeneratorPostProcess(scene);
  33691. // HDR
  33692. this._createHDRPostProcess(scene, ratio);
  33693. // Pass postprocess
  33694. if (originalPostProcess === null) {
  33695. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33696. }
  33697. else {
  33698. this._originalPostProcess = originalPostProcess;
  33699. }
  33700. // Configure pipeline
  33701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33702. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33703. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33704. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33705. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33706. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33707. var addDownSamplerPostProcess = function (id) {
  33708. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33709. };
  33710. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33711. addDownSamplerPostProcess(i);
  33712. }
  33713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33714. // Finish
  33715. scene.postProcessRenderPipelineManager.addPipeline(this);
  33716. if (cameras !== null) {
  33717. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33718. }
  33719. this.update();
  33720. }
  33721. /**
  33722. * Tells the pipeline to update its post-processes
  33723. */
  33724. HDRRenderingPipeline.prototype.update = function () {
  33725. this._needUpdate = true;
  33726. };
  33727. /**
  33728. * Returns the current calculated luminance
  33729. */
  33730. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33731. return this._hdrCurrentLuminance;
  33732. };
  33733. /**
  33734. * Returns the currently drawn luminance
  33735. */
  33736. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33737. return this._hdrOutputLuminance;
  33738. };
  33739. /**
  33740. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33741. */
  33742. HDRRenderingPipeline.prototype.dispose = function () {
  33743. this._originalPostProcess = undefined;
  33744. this._brightPassPostProcess = undefined;
  33745. this._downSampleX4PostProcess = undefined;
  33746. this._guassianBlurHPostProcess = undefined;
  33747. this._guassianBlurVPostProcess = undefined;
  33748. this._textureAdderPostProcess = undefined;
  33749. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33750. this._downSamplePostProcesses[i] = undefined;
  33751. }
  33752. this._hdrPostProcess = undefined;
  33753. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33754. };
  33755. /**
  33756. * Creates the HDR post-process and computes the luminance adaptation
  33757. */
  33758. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33759. var _this = this;
  33760. var hdrLastLuminance = 0.0;
  33761. this._hdrOutputLuminance = -1.0;
  33762. this._hdrCurrentLuminance = 1.0;
  33763. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33764. this._hdrPostProcess.onApply = function (effect) {
  33765. if (_this._hdrOutputLuminance < 0.0) {
  33766. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33767. }
  33768. else {
  33769. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33770. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33771. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33772. }
  33773. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33774. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33775. }
  33776. else {
  33777. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33778. }
  33779. }
  33780. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33781. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33782. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33783. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33784. effect.setFloat("exposure", _this.exposure);
  33785. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33786. _this._needUpdate = false;
  33787. };
  33788. };
  33789. /**
  33790. * Texture Adder post-process
  33791. */
  33792. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33793. var _this = this;
  33794. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33795. this._textureAdderPostProcess.onApply = function (effect) {
  33796. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33797. };
  33798. };
  33799. /**
  33800. * Down sample X4 post-process
  33801. */
  33802. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33803. var _this = this;
  33804. var downSampleX4Offsets = new Array(32);
  33805. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33806. this._downSampleX4PostProcess.onApply = function (effect) {
  33807. if (_this._needUpdate) {
  33808. var id = 0;
  33809. for (var i = -2; i < 2; i++) {
  33810. for (var j = -2; j < 2; j++) {
  33811. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33812. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33813. id += 2;
  33814. }
  33815. }
  33816. }
  33817. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33818. };
  33819. };
  33820. /**
  33821. * Bright pass post-process
  33822. */
  33823. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33824. var _this = this;
  33825. var brightOffsets = new Array(8);
  33826. var brightPassCallback = function (effect) {
  33827. if (_this._needUpdate) {
  33828. var sU = (1.0 / _this._brightPassPostProcess.width);
  33829. var sV = (1.0 / _this._brightPassPostProcess.height);
  33830. brightOffsets[0] = -0.5 * sU;
  33831. brightOffsets[1] = 0.5 * sV;
  33832. brightOffsets[2] = 0.5 * sU;
  33833. brightOffsets[3] = 0.5 * sV;
  33834. brightOffsets[4] = -0.5 * sU;
  33835. brightOffsets[5] = -0.5 * sV;
  33836. brightOffsets[6] = 0.5 * sU;
  33837. brightOffsets[7] = -0.5 * sV;
  33838. }
  33839. effect.setArray2("dsOffsets", brightOffsets);
  33840. effect.setFloat("brightThreshold", _this.brightThreshold);
  33841. };
  33842. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33843. this._brightPassPostProcess.onApply = brightPassCallback;
  33844. };
  33845. /**
  33846. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33847. */
  33848. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33849. var _this = this;
  33850. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33851. var luminanceOffsets = new Array(8);
  33852. var downSampleOffsets = new Array(18);
  33853. var halfDestPixelSize;
  33854. this._downSamplePostProcesses = new Array(lumSteps);
  33855. // Utils for luminance
  33856. var luminanceUpdateSourceOffsets = function (width, height) {
  33857. var sU = (1.0 / width);
  33858. var sV = (1.0 / height);
  33859. luminanceOffsets[0] = -0.5 * sU;
  33860. luminanceOffsets[1] = 0.5 * sV;
  33861. luminanceOffsets[2] = 0.5 * sU;
  33862. luminanceOffsets[3] = 0.5 * sV;
  33863. luminanceOffsets[4] = -0.5 * sU;
  33864. luminanceOffsets[5] = -0.5 * sV;
  33865. luminanceOffsets[6] = 0.5 * sU;
  33866. luminanceOffsets[7] = -0.5 * sV;
  33867. };
  33868. var luminanceUpdateDestOffsets = function (width, height) {
  33869. var id = 0;
  33870. for (var x = -1; x < 2; x++) {
  33871. for (var y = -1; y < 2; y++) {
  33872. downSampleOffsets[id] = (x) / width;
  33873. downSampleOffsets[id + 1] = (y) / height;
  33874. id += 2;
  33875. }
  33876. }
  33877. };
  33878. // Luminance callback
  33879. var luminanceCallback = function (effect) {
  33880. if (_this._needUpdate) {
  33881. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33882. }
  33883. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33884. effect.setArray2("lumOffsets", luminanceOffsets);
  33885. };
  33886. // Down sample callbacks
  33887. var downSampleCallback = function (indice) {
  33888. var i = indice;
  33889. return function (effect) {
  33890. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33891. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33892. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33893. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33894. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33895. effect.setArray2("dsOffsets", downSampleOffsets);
  33896. };
  33897. };
  33898. var downSampleAfterRenderCallback = function (effect) {
  33899. // Unpack result
  33900. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33901. 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);
  33902. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33903. };
  33904. // Create luminance post-process
  33905. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33906. 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);
  33907. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33908. // Create down sample post-processes
  33909. for (var i = lumSteps - 2; i >= 0; i--) {
  33910. var length = Math.pow(3, i);
  33911. ratio = { width: length, height: length };
  33912. var defines = "#define DOWN_SAMPLE\n";
  33913. if (i === 0) {
  33914. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33915. }
  33916. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33917. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33918. if (i === 0) {
  33919. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33920. }
  33921. }
  33922. };
  33923. /**
  33924. * Gaussian blur post-processes. Horizontal and Vertical
  33925. */
  33926. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33927. var _this = this;
  33928. var blurOffsetsW = new Array(9);
  33929. var blurOffsetsH = new Array(9);
  33930. var blurWeights = new Array(9);
  33931. var uniforms = ["blurOffsets", "blurWeights"];
  33932. // Utils for gaussian blur
  33933. var calculateBlurOffsets = function (height) {
  33934. var lastOutputDimensions = {
  33935. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33936. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33937. };
  33938. for (var i = 0; i < 9; i++) {
  33939. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33940. if (height) {
  33941. blurOffsetsH[i] = value;
  33942. }
  33943. else {
  33944. blurOffsetsW[i] = value;
  33945. }
  33946. }
  33947. };
  33948. var calculateWeights = function () {
  33949. var x = 0.0;
  33950. for (var i = 0; i < 9; i++) {
  33951. x = (i - 4.0) / 4.0;
  33952. 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));
  33953. }
  33954. };
  33955. // Callback
  33956. var gaussianBlurCallback = function (height) {
  33957. return function (effect) {
  33958. if (_this._needUpdate) {
  33959. calculateWeights();
  33960. calculateBlurOffsets(height);
  33961. }
  33962. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33963. effect.setArray("blurWeights", blurWeights);
  33964. };
  33965. };
  33966. // Create horizontal gaussian blur post-processes
  33967. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33968. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33969. // Create vertical gaussian blur post-process
  33970. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33971. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33972. };
  33973. // Luminance generator
  33974. HDRRenderingPipeline.LUM_STEPS = 6;
  33975. return HDRRenderingPipeline;
  33976. })(BABYLON.PostProcessRenderPipeline);
  33977. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33978. })(BABYLON || (BABYLON = {}));
  33979. var BABYLON;
  33980. (function (BABYLON) {
  33981. var FaceAdjacencies = (function () {
  33982. function FaceAdjacencies() {
  33983. this.edges = new Array();
  33984. this.edgesConnectedCount = 0;
  33985. }
  33986. return FaceAdjacencies;
  33987. })();
  33988. var EdgesRenderer = (function () {
  33989. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33990. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33991. if (epsilon === void 0) { epsilon = 0.95; }
  33992. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33993. this._linesPositions = new Array();
  33994. this._linesNormals = new Array();
  33995. this._linesIndices = new Array();
  33996. this._buffers = new Array();
  33997. this._checkVerticesInsteadOfIndices = false;
  33998. this._source = source;
  33999. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  34000. this._epsilon = epsilon;
  34001. this._prepareRessources();
  34002. this._generateEdgesLines();
  34003. }
  34004. EdgesRenderer.prototype._prepareRessources = function () {
  34005. if (this._lineShader) {
  34006. return;
  34007. }
  34008. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  34009. attributes: ["position", "normal"],
  34010. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  34011. });
  34012. this._lineShader.disableDepthWrite = true;
  34013. this._lineShader.backFaceCulling = false;
  34014. };
  34015. EdgesRenderer.prototype.dispose = function () {
  34016. this._vb0.dispose();
  34017. this._vb1.dispose();
  34018. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  34019. this._lineShader.dispose();
  34020. };
  34021. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  34022. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  34023. return 0;
  34024. }
  34025. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  34026. return 1;
  34027. }
  34028. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  34029. return 2;
  34030. }
  34031. return -1;
  34032. };
  34033. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  34034. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  34035. return 0;
  34036. }
  34037. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  34038. return 1;
  34039. }
  34040. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  34041. return 2;
  34042. }
  34043. return -1;
  34044. };
  34045. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  34046. var needToCreateLine;
  34047. if (edge === undefined) {
  34048. needToCreateLine = true;
  34049. }
  34050. else {
  34051. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  34052. needToCreateLine = dotProduct < this._epsilon;
  34053. }
  34054. if (needToCreateLine) {
  34055. var offset = this._linesPositions.length / 3;
  34056. var normal = p0.subtract(p1);
  34057. normal.normalize();
  34058. // Positions
  34059. this._linesPositions.push(p0.x);
  34060. this._linesPositions.push(p0.y);
  34061. this._linesPositions.push(p0.z);
  34062. this._linesPositions.push(p0.x);
  34063. this._linesPositions.push(p0.y);
  34064. this._linesPositions.push(p0.z);
  34065. this._linesPositions.push(p1.x);
  34066. this._linesPositions.push(p1.y);
  34067. this._linesPositions.push(p1.z);
  34068. this._linesPositions.push(p1.x);
  34069. this._linesPositions.push(p1.y);
  34070. this._linesPositions.push(p1.z);
  34071. // Normals
  34072. this._linesNormals.push(p1.x);
  34073. this._linesNormals.push(p1.y);
  34074. this._linesNormals.push(p1.z);
  34075. this._linesNormals.push(-1);
  34076. this._linesNormals.push(p1.x);
  34077. this._linesNormals.push(p1.y);
  34078. this._linesNormals.push(p1.z);
  34079. this._linesNormals.push(1);
  34080. this._linesNormals.push(p0.x);
  34081. this._linesNormals.push(p0.y);
  34082. this._linesNormals.push(p0.z);
  34083. this._linesNormals.push(-1);
  34084. this._linesNormals.push(p0.x);
  34085. this._linesNormals.push(p0.y);
  34086. this._linesNormals.push(p0.z);
  34087. this._linesNormals.push(1);
  34088. // Indices
  34089. this._linesIndices.push(offset);
  34090. this._linesIndices.push(offset + 1);
  34091. this._linesIndices.push(offset + 2);
  34092. this._linesIndices.push(offset);
  34093. this._linesIndices.push(offset + 2);
  34094. this._linesIndices.push(offset + 3);
  34095. }
  34096. };
  34097. EdgesRenderer.prototype._generateEdgesLines = function () {
  34098. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34099. var indices = this._source.getIndices();
  34100. // First let's find adjacencies
  34101. var adjacencies = new Array();
  34102. var faceNormals = new Array();
  34103. var index;
  34104. var faceAdjacencies;
  34105. // Prepare faces
  34106. for (index = 0; index < indices.length; index += 3) {
  34107. faceAdjacencies = new FaceAdjacencies();
  34108. var p0Index = indices[index];
  34109. var p1Index = indices[index + 1];
  34110. var p2Index = indices[index + 2];
  34111. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  34112. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  34113. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  34114. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  34115. faceNormal.normalize();
  34116. faceNormals.push(faceNormal);
  34117. adjacencies.push(faceAdjacencies);
  34118. }
  34119. // Scan
  34120. for (index = 0; index < adjacencies.length; index++) {
  34121. faceAdjacencies = adjacencies[index];
  34122. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  34123. var otherFaceAdjacencies = adjacencies[otherIndex];
  34124. if (faceAdjacencies.edgesConnectedCount === 3) {
  34125. break;
  34126. }
  34127. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  34128. continue;
  34129. }
  34130. var otherP0 = indices[otherIndex * 3];
  34131. var otherP1 = indices[otherIndex * 3 + 1];
  34132. var otherP2 = indices[otherIndex * 3 + 2];
  34133. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  34134. var otherEdgeIndex;
  34135. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  34136. continue;
  34137. }
  34138. switch (edgeIndex) {
  34139. case 0:
  34140. if (this._checkVerticesInsteadOfIndices) {
  34141. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34142. }
  34143. else {
  34144. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  34145. }
  34146. break;
  34147. case 1:
  34148. if (this._checkVerticesInsteadOfIndices) {
  34149. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34150. }
  34151. else {
  34152. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  34153. }
  34154. break;
  34155. case 2:
  34156. if (this._checkVerticesInsteadOfIndices) {
  34157. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34158. }
  34159. else {
  34160. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  34161. }
  34162. break;
  34163. }
  34164. if (otherEdgeIndex === -1) {
  34165. continue;
  34166. }
  34167. faceAdjacencies.edges[edgeIndex] = otherIndex;
  34168. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  34169. faceAdjacencies.edgesConnectedCount++;
  34170. otherFaceAdjacencies.edgesConnectedCount++;
  34171. if (faceAdjacencies.edgesConnectedCount === 3) {
  34172. break;
  34173. }
  34174. }
  34175. }
  34176. }
  34177. // Create lines
  34178. for (index = 0; index < adjacencies.length; index++) {
  34179. // 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
  34180. var current = adjacencies[index];
  34181. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  34182. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  34183. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  34184. }
  34185. // Merge into a single mesh
  34186. var engine = this._source.getScene().getEngine();
  34187. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  34188. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  34189. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  34190. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  34191. this._ib = engine.createIndexBuffer(this._linesIndices);
  34192. this._indicesCount = this._linesIndices.length;
  34193. };
  34194. EdgesRenderer.prototype.render = function () {
  34195. if (!this._lineShader.isReady()) {
  34196. return;
  34197. }
  34198. var scene = this._source.getScene();
  34199. var engine = scene.getEngine();
  34200. this._lineShader._preBind();
  34201. // VBOs
  34202. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  34203. scene.resetCachedMaterial();
  34204. this._lineShader.setColor4("color", this._source.edgesColor);
  34205. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  34206. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  34207. this._lineShader.bind(this._source.getWorldMatrix());
  34208. // Draw order
  34209. engine.draw(true, 0, this._indicesCount);
  34210. this._lineShader.unbind();
  34211. engine.setDepthWrite(true);
  34212. };
  34213. return EdgesRenderer;
  34214. })();
  34215. BABYLON.EdgesRenderer = EdgesRenderer;
  34216. })(BABYLON || (BABYLON = {}));
  34217. var BABYLON;
  34218. (function (BABYLON) {
  34219. (function (TonemappingOperator) {
  34220. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  34221. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  34222. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  34223. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  34224. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  34225. var TonemappingOperator = BABYLON.TonemappingOperator;
  34226. ;
  34227. var TonemapPostProcess = (function (_super) {
  34228. __extends(TonemapPostProcess, _super);
  34229. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  34230. var _this = this;
  34231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34232. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34233. this._operator = operator;
  34234. this._exposureAdjustment = exposureAdjustment;
  34235. var params = ["_ExposureAdjustment"];
  34236. var defines = "#define ";
  34237. if (operator === TonemappingOperator.Hable)
  34238. defines += "HABLE_TONEMAPPING";
  34239. else if (operator === TonemappingOperator.Reinhard)
  34240. defines += "REINHARD_TONEMAPPING";
  34241. else if (operator === TonemappingOperator.HejiDawson)
  34242. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  34243. else if (operator === TonemappingOperator.Photographic)
  34244. defines += "PHOTOGRAPHIC_TONEMAPPING";
  34245. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  34246. this.onApply = function (effect) {
  34247. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  34248. };
  34249. }
  34250. return TonemapPostProcess;
  34251. })(BABYLON.PostProcess);
  34252. BABYLON.TonemapPostProcess = TonemapPostProcess;
  34253. })(BABYLON || (BABYLON = {}));
  34254. var BABYLON;
  34255. (function (BABYLON) {
  34256. var DefaultLoadingScreen = (function () {
  34257. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34258. var _this = this;
  34259. if (_loadingText === void 0) { _loadingText = ""; }
  34260. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34261. this._renderingCanvas = _renderingCanvas;
  34262. this._loadingText = _loadingText;
  34263. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34264. // Resize
  34265. this._resizeLoadingUI = function () {
  34266. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34267. _this._loadingDiv.style.position = "absolute";
  34268. _this._loadingDiv.style.left = canvasRect.left + "px";
  34269. _this._loadingDiv.style.top = canvasRect.top + "px";
  34270. _this._loadingDiv.style.width = canvasRect.width + "px";
  34271. _this._loadingDiv.style.height = canvasRect.height + "px";
  34272. };
  34273. }
  34274. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34275. var _this = this;
  34276. this._loadingDiv = document.createElement("div");
  34277. this._loadingDiv.style.opacity = "0";
  34278. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34279. // Loading text
  34280. this._loadingTextDiv = document.createElement("div");
  34281. this._loadingTextDiv.style.position = "absolute";
  34282. this._loadingTextDiv.style.left = "0";
  34283. this._loadingTextDiv.style.top = "50%";
  34284. this._loadingTextDiv.style.marginTop = "80px";
  34285. this._loadingTextDiv.style.width = "100%";
  34286. this._loadingTextDiv.style.height = "20px";
  34287. this._loadingTextDiv.style.fontFamily = "Arial";
  34288. this._loadingTextDiv.style.fontSize = "14px";
  34289. this._loadingTextDiv.style.color = "white";
  34290. this._loadingTextDiv.style.textAlign = "center";
  34291. this._loadingTextDiv.innerHTML = "Loading";
  34292. this._loadingDiv.appendChild(this._loadingTextDiv);
  34293. //set the predefined text
  34294. this._loadingTextDiv.innerHTML = this._loadingText;
  34295. // Loading img
  34296. var imgBack = new Image();
  34297. 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==";
  34298. imgBack.style.position = "absolute";
  34299. imgBack.style.left = "50%";
  34300. imgBack.style.top = "50%";
  34301. imgBack.style.marginLeft = "-50px";
  34302. imgBack.style.marginTop = "-50px";
  34303. imgBack.style.transition = "transform 1.0s ease";
  34304. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34305. var deg = 360;
  34306. var onTransitionEnd = function () {
  34307. deg += 360;
  34308. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34309. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34310. };
  34311. imgBack.addEventListener("transitionend", onTransitionEnd);
  34312. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34313. this._loadingDiv.appendChild(imgBack);
  34314. // front image
  34315. var imgFront = new Image();
  34316. 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=";
  34317. imgFront.style.position = "absolute";
  34318. imgFront.style.left = "50%";
  34319. imgFront.style.top = "50%";
  34320. imgFront.style.marginLeft = "-50px";
  34321. imgFront.style.marginTop = "-50px";
  34322. this._loadingDiv.appendChild(imgFront);
  34323. this._resizeLoadingUI();
  34324. window.addEventListener("resize", this._resizeLoadingUI);
  34325. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34326. document.body.appendChild(this._loadingDiv);
  34327. setTimeout(function () {
  34328. _this._loadingDiv.style.opacity = "1";
  34329. imgBack.style.transform = "rotateZ(360deg)";
  34330. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34331. }, 0);
  34332. };
  34333. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34334. var _this = this;
  34335. if (!this._loadingDiv) {
  34336. return;
  34337. }
  34338. var onTransitionEnd = function () {
  34339. if (!_this._loadingDiv) {
  34340. return;
  34341. }
  34342. document.body.removeChild(_this._loadingDiv);
  34343. window.removeEventListener("resize", _this._resizeLoadingUI);
  34344. _this._loadingDiv = null;
  34345. };
  34346. this._loadingDiv.style.opacity = "0";
  34347. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34348. };
  34349. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34350. set: function (text) {
  34351. this._loadingText = text;
  34352. if (this._loadingTextDiv) {
  34353. this._loadingTextDiv.innerHTML = this._loadingText;
  34354. }
  34355. },
  34356. enumerable: true,
  34357. configurable: true
  34358. });
  34359. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34360. get: function () {
  34361. return this._loadingDivBackgroundColor;
  34362. },
  34363. set: function (color) {
  34364. this._loadingDivBackgroundColor = color;
  34365. if (!this._loadingDiv) {
  34366. return;
  34367. }
  34368. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. return DefaultLoadingScreen;
  34374. })();
  34375. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34376. })(BABYLON || (BABYLON = {}));
  34377. var BABYLON;
  34378. (function (BABYLON) {
  34379. var maxSimultaneousLights = 4;
  34380. var PBRMaterialDefines = (function () {
  34381. function PBRMaterialDefines() {
  34382. this.ALBEDO = false;
  34383. this.CLIPPLANE = false;
  34384. this.ALPHATEST = false;
  34385. this.FOG = false;
  34386. this.NORMAL = false;
  34387. this.UV1 = false;
  34388. this.UV2 = false;
  34389. this.VERTEXCOLOR = false;
  34390. this.VERTEXALPHA = false;
  34391. this.BONES = false;
  34392. this.BONES4 = false;
  34393. this.BonesPerMesh = 0;
  34394. this.INSTANCES = false;
  34395. this.POINTSIZE = false;
  34396. this._keys = Object.keys(this);
  34397. }
  34398. PBRMaterialDefines.prototype.isEqual = function (other) {
  34399. for (var index = 0; index < this._keys.length; index++) {
  34400. var prop = this._keys[index];
  34401. if (this[prop] !== other[prop]) {
  34402. return false;
  34403. }
  34404. }
  34405. return true;
  34406. };
  34407. PBRMaterialDefines.prototype.cloneTo = function (other) {
  34408. for (var index = 0; index < this._keys.length; index++) {
  34409. var prop = this._keys[index];
  34410. other[prop] = this[prop];
  34411. }
  34412. };
  34413. PBRMaterialDefines.prototype.reset = function () {
  34414. for (var index = 0; index < this._keys.length; index++) {
  34415. var prop = this._keys[index];
  34416. if (prop === "BonesPerMesh") {
  34417. this[prop] = 0;
  34418. continue;
  34419. }
  34420. this[prop] = false;
  34421. }
  34422. };
  34423. PBRMaterialDefines.prototype.toString = function () {
  34424. var result = "";
  34425. for (var index = 0; index < this._keys.length; index++) {
  34426. var prop = this._keys[index];
  34427. if (prop === "BonesPerMesh" && this[prop] > 0) {
  34428. result += "#define BonesPerMesh " + this[prop] + "\n";
  34429. continue;
  34430. }
  34431. if (this[prop]) {
  34432. result += "#define " + prop + "\n";
  34433. }
  34434. }
  34435. return result;
  34436. };
  34437. return PBRMaterialDefines;
  34438. })();
  34439. var PBRMaterial = (function (_super) {
  34440. __extends(PBRMaterial, _super);
  34441. function PBRMaterial(name, scene) {
  34442. _super.call(this, name, scene);
  34443. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34444. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34445. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34446. this._scaledDiffuse = new BABYLON.Color3();
  34447. this._scaledSpecular = new BABYLON.Color3();
  34448. this._defines = new PBRMaterialDefines();
  34449. this._cachedDefines = new PBRMaterialDefines();
  34450. this._cachedDefines.BonesPerMesh = -1;
  34451. }
  34452. PBRMaterial.prototype.needAlphaBlending = function () {
  34453. return this.alpha < 1.0;
  34454. };
  34455. PBRMaterial.prototype.needAlphaTesting = function () {
  34456. return false;
  34457. };
  34458. PBRMaterial.prototype.getAlphaTestTexture = function () {
  34459. return null;
  34460. };
  34461. // Methods
  34462. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  34463. if (this.checkReadyOnlyOnce) {
  34464. if (this._wasPreviouslyReady) {
  34465. return true;
  34466. }
  34467. }
  34468. var scene = this.getScene();
  34469. if (!this.checkReadyOnEveryCall) {
  34470. if (this._renderId === scene.getRenderId()) {
  34471. return true;
  34472. }
  34473. }
  34474. var engine = scene.getEngine();
  34475. var needNormals = false;
  34476. var needUVs = false;
  34477. this._defines.reset();
  34478. // Textures
  34479. if (scene.texturesEnabled) {
  34480. }
  34481. // Effect
  34482. if (scene.clipPlane) {
  34483. this._defines.CLIPPLANE = true;
  34484. }
  34485. if (engine.getAlphaTesting()) {
  34486. this._defines.ALPHATEST = true;
  34487. }
  34488. // Point size
  34489. if (this.pointsCloud || scene.forcePointsCloud) {
  34490. this._defines.POINTSIZE = true;
  34491. }
  34492. // Fog
  34493. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34494. this._defines.FOG = true;
  34495. }
  34496. // Lights
  34497. // Attribs
  34498. if (mesh) {
  34499. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34500. this._defines.NORMAL = true;
  34501. }
  34502. if (needUVs) {
  34503. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34504. this._defines.UV1 = true;
  34505. }
  34506. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34507. this._defines.UV2 = true;
  34508. }
  34509. }
  34510. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34511. this._defines.VERTEXCOLOR = true;
  34512. if (mesh.hasVertexAlpha) {
  34513. this._defines.VERTEXALPHA = true;
  34514. }
  34515. }
  34516. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34517. this._defines.BONES = true;
  34518. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  34519. this._defines.BONES4 = true;
  34520. }
  34521. // Instances
  34522. if (useInstances) {
  34523. this._defines.INSTANCES = true;
  34524. }
  34525. }
  34526. // Get correct effect
  34527. if (!this._defines.isEqual(this._cachedDefines)) {
  34528. this._defines.cloneTo(this._cachedDefines);
  34529. scene.resetCachedMaterial();
  34530. // Fallbacks
  34531. var fallbacks = new BABYLON.EffectFallbacks();
  34532. if (this._defines.FOG) {
  34533. fallbacks.addFallback(1, "FOG");
  34534. }
  34535. if (this._defines.BONES4) {
  34536. fallbacks.addFallback(0, "BONES4");
  34537. }
  34538. //Attributes
  34539. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34540. if (this._defines.NORMAL) {
  34541. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34542. }
  34543. if (this._defines.UV1) {
  34544. attribs.push(BABYLON.VertexBuffer.UVKind);
  34545. }
  34546. if (this._defines.UV2) {
  34547. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34548. }
  34549. if (this._defines.VERTEXCOLOR) {
  34550. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34551. }
  34552. if (this._defines.BONES) {
  34553. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34554. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34555. }
  34556. if (this._defines.INSTANCES) {
  34557. attribs.push("world0");
  34558. attribs.push("world1");
  34559. attribs.push("world2");
  34560. attribs.push("world3");
  34561. }
  34562. // Legacy browser patch
  34563. var join = this._defines.toString();
  34564. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  34565. "vFogInfos", "vFogColor", "pointSize",
  34566. "mBones",
  34567. "vClipPlane",
  34568. ], [], join, fallbacks, this.onCompiled, this.onError);
  34569. }
  34570. if (!this._effect.isReady()) {
  34571. return false;
  34572. }
  34573. this._renderId = scene.getRenderId();
  34574. this._wasPreviouslyReady = true;
  34575. return true;
  34576. };
  34577. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34578. this._effect.setMatrix("world", world);
  34579. };
  34580. PBRMaterial.prototype.bind = function (world, mesh) {
  34581. var scene = this.getScene();
  34582. // Matrices
  34583. this.bindOnlyWorldMatrix(world);
  34584. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34585. // Bones
  34586. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34587. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34588. }
  34589. if (scene.getCachedMaterial() !== this) {
  34590. // Clip plane
  34591. if (scene.clipPlane) {
  34592. var clipPlane = scene.clipPlane;
  34593. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34594. }
  34595. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  34596. }
  34597. // Point size
  34598. if (this.pointsCloud) {
  34599. this._effect.setFloat("pointSize", this.pointSize);
  34600. }
  34601. // Colors
  34602. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  34603. // View
  34604. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34605. this._effect.setMatrix("view", scene.getViewMatrix());
  34606. }
  34607. // Fog
  34608. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34609. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34610. this._effect.setColor3("vFogColor", scene.fogColor);
  34611. }
  34612. _super.prototype.bind.call(this, world, mesh);
  34613. };
  34614. PBRMaterial.prototype.getAnimatables = function () {
  34615. var results = [];
  34616. return results;
  34617. };
  34618. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  34619. _super.prototype.dispose.call(this, forceDisposeEffect);
  34620. };
  34621. PBRMaterial.prototype.clone = function (name) {
  34622. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  34623. // Base material
  34624. this.copyTo(newPBRMaterial);
  34625. // PBRMaterial material
  34626. newPBRMaterial.albedoColor = this.albedoColor.clone();
  34627. return newPBRMaterial;
  34628. };
  34629. return PBRMaterial;
  34630. })(BABYLON.Material);
  34631. BABYLON.PBRMaterial = PBRMaterial;
  34632. })(BABYLON || (BABYLON = {}));
  34633. var BABYLON;
  34634. (function (BABYLON) {
  34635. var ReflectionProbe = (function () {
  34636. //http://localhost:61437/Playground/index%20-%20debug.html#KA93U#7
  34637. function ReflectionProbe(name, size, scene, generateMipMaps) {
  34638. var _this = this;
  34639. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34640. this.name = name;
  34641. this._viewMatrix = BABYLON.Matrix.Identity();
  34642. this._target = BABYLON.Vector3.Zero();
  34643. this._add = BABYLON.Vector3.Zero();
  34644. this.position = BABYLON.Vector3.Zero();
  34645. this._scene = scene;
  34646. this._scene.reflectionProbes.push(this);
  34647. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  34648. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  34649. switch (faceIndex) {
  34650. case 0:
  34651. _this._add.copyFromFloats(1, 0, 0);
  34652. break;
  34653. case 1:
  34654. _this._add.copyFromFloats(-1, 0, 0);
  34655. break;
  34656. case 2:
  34657. _this._add.copyFromFloats(0, -1, 0);
  34658. break;
  34659. case 3:
  34660. _this._add.copyFromFloats(0, 1, 0);
  34661. break;
  34662. case 4:
  34663. _this._add.copyFromFloats(0, 0, 1);
  34664. break;
  34665. case 5:
  34666. _this._add.copyFromFloats(0, 0, -1);
  34667. break;
  34668. }
  34669. if (_this._attachedMesh) {
  34670. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  34671. }
  34672. _this.position.addToRef(_this._add, _this._target);
  34673. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  34674. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  34675. };
  34676. this._renderTargetTexture.onAfterUnbind = function () {
  34677. scene.updateTransformMatrix(true);
  34678. };
  34679. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  34680. }
  34681. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  34682. get: function () {
  34683. return this._renderTargetTexture.refreshRate;
  34684. },
  34685. set: function (value) {
  34686. this._renderTargetTexture.refreshRate = value;
  34687. },
  34688. enumerable: true,
  34689. configurable: true
  34690. });
  34691. ReflectionProbe.prototype.getScene = function () {
  34692. return this._scene;
  34693. };
  34694. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  34695. get: function () {
  34696. return this._renderTargetTexture;
  34697. },
  34698. enumerable: true,
  34699. configurable: true
  34700. });
  34701. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  34702. get: function () {
  34703. return this._renderTargetTexture.renderList;
  34704. },
  34705. enumerable: true,
  34706. configurable: true
  34707. });
  34708. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  34709. this._attachedMesh = mesh;
  34710. };
  34711. ReflectionProbe.prototype.dispose = function () {
  34712. var index = this._scene.reflectionProbes.indexOf(this);
  34713. if (index !== -1) {
  34714. // Remove from the scene if found
  34715. this._scene.reflectionProbes.splice(index, 1);
  34716. }
  34717. };
  34718. return ReflectionProbe;
  34719. })();
  34720. BABYLON.ReflectionProbe = ReflectionProbe;
  34721. })(BABYLON || (BABYLON = {}));
  34722. 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}"};
  34723. 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={}));";
  34724. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  34725. module.exports = BABYLON;
  34726. };